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,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/VisualStudio/Core/Impl/SolutionExplorer/AnalyzerItem/AnalyzerItemSource.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; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal class AnalyzerItemSource : IAttachedCollectionSource, INotifyPropertyChanged { private readonly AnalyzersFolderItem _analyzersFolder; private readonly IAnalyzersCommandHandler _commandHandler; private IReadOnlyCollection<AnalyzerReference> _analyzerReferences; private BulkObservableCollection<AnalyzerItem> _analyzerItems; public event PropertyChangedEventHandler PropertyChanged; public AnalyzerItemSource(AnalyzersFolderItem analyzersFolder, IAnalyzersCommandHandler commandHandler) { _analyzersFolder = analyzersFolder; _commandHandler = commandHandler; _analyzersFolder.Workspace.WorkspaceChanged += Workspace_WorkspaceChanged; } private void Workspace_WorkspaceChanged(object sender, WorkspaceChangeEventArgs e) { switch (e.Kind) { case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionReloaded: UpdateAnalyzers(); break; case WorkspaceChangeKind.SolutionRemoved: case WorkspaceChangeKind.SolutionCleared: _analyzersFolder.Workspace.WorkspaceChanged -= Workspace_WorkspaceChanged; break; case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.ProjectReloaded: case WorkspaceChangeKind.ProjectChanged: if (e.ProjectId == _analyzersFolder.ProjectId) { UpdateAnalyzers(); } break; case WorkspaceChangeKind.ProjectRemoved: if (e.ProjectId == _analyzersFolder.ProjectId) { _analyzersFolder.Workspace.WorkspaceChanged -= Workspace_WorkspaceChanged; } break; } } private void UpdateAnalyzers() { if (_analyzerItems == null) { // The set of AnalyzerItems hasn't been realized yet. Just signal that HasItems // may have changed. NotifyPropertyChanged(nameof(HasItems)); return; } var project = _analyzersFolder.Workspace .CurrentSolution .GetProject(_analyzersFolder.ProjectId); if (project != null && project.AnalyzerReferences != _analyzerReferences) { _analyzerReferences = project.AnalyzerReferences; _analyzerItems.BeginBulkOperation(); var itemsToRemove = _analyzerItems .Where(item => !_analyzerReferences.Contains(item.AnalyzerReference)) .ToArray(); var referencesToAdd = GetFilteredAnalyzers(_analyzerReferences, project) .Where(r => !_analyzerItems.Any(item => item.AnalyzerReference == r)) .ToArray(); foreach (var item in itemsToRemove) { _analyzerItems.Remove(item); } foreach (var reference in referencesToAdd) { _analyzerItems.Add(new AnalyzerItem(_analyzersFolder, reference, _commandHandler.AnalyzerContextMenuController)); } var sorted = _analyzerItems.OrderBy(item => item.AnalyzerReference.Display).ToArray(); for (var i = 0; i < sorted.Length; i++) { _analyzerItems.Move(_analyzerItems.IndexOf(sorted[i]), i); } _analyzerItems.EndBulkOperation(); NotifyPropertyChanged(nameof(HasItems)); } } private void NotifyPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public bool HasItems { get { if (_analyzerItems != null) { return _analyzerItems.Count > 0; } var project = _analyzersFolder.Workspace .CurrentSolution .GetProject(_analyzersFolder.ProjectId); if (project != null) { return project.AnalyzerReferences.Count > 0; } return false; } } public IEnumerable Items { get { if (_analyzerItems == null) { _analyzerItems = new BulkObservableCollection<AnalyzerItem>(); var project = _analyzersFolder.Workspace .CurrentSolution .GetProject(_analyzersFolder.ProjectId); if (project != null) { _analyzerReferences = project.AnalyzerReferences; var initialSet = GetFilteredAnalyzers(_analyzerReferences, project) .OrderBy(ar => ar.Display) .Select(ar => new AnalyzerItem(_analyzersFolder, ar, _commandHandler.AnalyzerContextMenuController)); _analyzerItems.AddRange(initialSet); } } Logger.Log( FunctionId.SolutionExplorer_AnalyzerItemSource_GetItems, KeyValueLogMessage.Create(m => m["Count"] = _analyzerItems.Count)); return _analyzerItems; } } public object SourceItem { get { return _analyzersFolder; } } private ImmutableHashSet<string> GetAnalyzersWithLoadErrors() { if (_analyzersFolder.Workspace is VisualStudioWorkspaceImpl) { /* var vsProject = vsWorkspace.DeferredState?.ProjectTracker.GetProject(_analyzersFolder.ProjectId); var vsAnalyzersMap = vsProject?.GetProjectAnalyzersMap(); if (vsAnalyzersMap != null) { return vsAnalyzersMap.Where(kvp => kvp.Value.HasLoadErrors).Select(kvp => kvp.Key).ToImmutableHashSet(); } */ } return ImmutableHashSet<string>.Empty; } private ImmutableArray<AnalyzerReference> GetFilteredAnalyzers(IEnumerable<AnalyzerReference> analyzerReferences, Project project) { var analyzersWithLoadErrors = GetAnalyzersWithLoadErrors(); // Filter out analyzer dependencies which have no diagnostic analyzers, but still retain the unresolved analyzers and analyzers with load errors. var builder = ArrayBuilder<AnalyzerReference>.GetInstance(); foreach (var analyzerReference in analyzerReferences) { // Analyzer dependency: // 1. Must be an Analyzer file reference (we don't understand other analyzer dependencies). // 2. Mush have no diagnostic analyzers. // 3. Must have no source generators. // 4. Must have non-null full path. // 5. Must not have any assembly or analyzer load failures. if (analyzerReference is AnalyzerFileReference && analyzerReference.GetAnalyzers(project.Language).IsDefaultOrEmpty && analyzerReference.GetGenerators(project.Language).IsDefaultOrEmpty && analyzerReference.FullPath != null && !analyzersWithLoadErrors.Contains(analyzerReference.FullPath)) { continue; } builder.Add(analyzerReference); } return builder.ToImmutableAndFree(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal class AnalyzerItemSource : IAttachedCollectionSource, INotifyPropertyChanged { private readonly AnalyzersFolderItem _analyzersFolder; private readonly IAnalyzersCommandHandler _commandHandler; private IReadOnlyCollection<AnalyzerReference> _analyzerReferences; private BulkObservableCollection<AnalyzerItem> _analyzerItems; public event PropertyChangedEventHandler PropertyChanged; public AnalyzerItemSource(AnalyzersFolderItem analyzersFolder, IAnalyzersCommandHandler commandHandler) { _analyzersFolder = analyzersFolder; _commandHandler = commandHandler; _analyzersFolder.Workspace.WorkspaceChanged += Workspace_WorkspaceChanged; } private void Workspace_WorkspaceChanged(object sender, WorkspaceChangeEventArgs e) { switch (e.Kind) { case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionReloaded: UpdateAnalyzers(); break; case WorkspaceChangeKind.SolutionRemoved: case WorkspaceChangeKind.SolutionCleared: _analyzersFolder.Workspace.WorkspaceChanged -= Workspace_WorkspaceChanged; break; case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.ProjectReloaded: case WorkspaceChangeKind.ProjectChanged: if (e.ProjectId == _analyzersFolder.ProjectId) { UpdateAnalyzers(); } break; case WorkspaceChangeKind.ProjectRemoved: if (e.ProjectId == _analyzersFolder.ProjectId) { _analyzersFolder.Workspace.WorkspaceChanged -= Workspace_WorkspaceChanged; } break; } } private void UpdateAnalyzers() { if (_analyzerItems == null) { // The set of AnalyzerItems hasn't been realized yet. Just signal that HasItems // may have changed. NotifyPropertyChanged(nameof(HasItems)); return; } var project = _analyzersFolder.Workspace .CurrentSolution .GetProject(_analyzersFolder.ProjectId); if (project != null && project.AnalyzerReferences != _analyzerReferences) { _analyzerReferences = project.AnalyzerReferences; _analyzerItems.BeginBulkOperation(); var itemsToRemove = _analyzerItems .Where(item => !_analyzerReferences.Contains(item.AnalyzerReference)) .ToArray(); var referencesToAdd = GetFilteredAnalyzers(_analyzerReferences, project) .Where(r => !_analyzerItems.Any(item => item.AnalyzerReference == r)) .ToArray(); foreach (var item in itemsToRemove) { _analyzerItems.Remove(item); } foreach (var reference in referencesToAdd) { _analyzerItems.Add(new AnalyzerItem(_analyzersFolder, reference, _commandHandler.AnalyzerContextMenuController)); } var sorted = _analyzerItems.OrderBy(item => item.AnalyzerReference.Display).ToArray(); for (var i = 0; i < sorted.Length; i++) { _analyzerItems.Move(_analyzerItems.IndexOf(sorted[i]), i); } _analyzerItems.EndBulkOperation(); NotifyPropertyChanged(nameof(HasItems)); } } private void NotifyPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public bool HasItems { get { if (_analyzerItems != null) { return _analyzerItems.Count > 0; } var project = _analyzersFolder.Workspace .CurrentSolution .GetProject(_analyzersFolder.ProjectId); if (project != null) { return project.AnalyzerReferences.Count > 0; } return false; } } public IEnumerable Items { get { if (_analyzerItems == null) { _analyzerItems = new BulkObservableCollection<AnalyzerItem>(); var project = _analyzersFolder.Workspace .CurrentSolution .GetProject(_analyzersFolder.ProjectId); if (project != null) { _analyzerReferences = project.AnalyzerReferences; var initialSet = GetFilteredAnalyzers(_analyzerReferences, project) .OrderBy(ar => ar.Display) .Select(ar => new AnalyzerItem(_analyzersFolder, ar, _commandHandler.AnalyzerContextMenuController)); _analyzerItems.AddRange(initialSet); } } Logger.Log( FunctionId.SolutionExplorer_AnalyzerItemSource_GetItems, KeyValueLogMessage.Create(m => m["Count"] = _analyzerItems.Count)); return _analyzerItems; } } public object SourceItem { get { return _analyzersFolder; } } private ImmutableHashSet<string> GetAnalyzersWithLoadErrors() { if (_analyzersFolder.Workspace is VisualStudioWorkspaceImpl) { /* var vsProject = vsWorkspace.DeferredState?.ProjectTracker.GetProject(_analyzersFolder.ProjectId); var vsAnalyzersMap = vsProject?.GetProjectAnalyzersMap(); if (vsAnalyzersMap != null) { return vsAnalyzersMap.Where(kvp => kvp.Value.HasLoadErrors).Select(kvp => kvp.Key).ToImmutableHashSet(); } */ } return ImmutableHashSet<string>.Empty; } private ImmutableArray<AnalyzerReference> GetFilteredAnalyzers(IEnumerable<AnalyzerReference> analyzerReferences, Project project) { var analyzersWithLoadErrors = GetAnalyzersWithLoadErrors(); // Filter out analyzer dependencies which have no diagnostic analyzers, but still retain the unresolved analyzers and analyzers with load errors. var builder = ArrayBuilder<AnalyzerReference>.GetInstance(); foreach (var analyzerReference in analyzerReferences) { // Analyzer dependency: // 1. Must be an Analyzer file reference (we don't understand other analyzer dependencies). // 2. Mush have no diagnostic analyzers. // 3. Must have no source generators. // 4. Must have non-null full path. // 5. Must not have any assembly or analyzer load failures. if (analyzerReference is AnalyzerFileReference && analyzerReference.GetAnalyzers(project.Language).IsDefaultOrEmpty && analyzerReference.GetGenerators(project.Language).IsDefaultOrEmpty && analyzerReference.FullPath != null && !analyzersWithLoadErrors.Contains(analyzerReference.FullPath)) { continue; } builder.Add(analyzerReference); } return builder.ToImmutableAndFree(); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/Core/Portable/CommandLine/AnalyzerConfigSet.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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.AnalyzerConfig; using AnalyzerOptions = System.Collections.Immutable.ImmutableDictionary<string, string>; using TreeOptions = System.Collections.Immutable.ImmutableDictionary<string, Microsoft.CodeAnalysis.ReportDiagnostic>; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a set of <see cref="AnalyzerConfig"/>, and can compute the effective analyzer options for a given source file. This is used to /// collect all the <see cref="AnalyzerConfig"/> files for that would apply to a compilation. /// </summary> public sealed class AnalyzerConfigSet { /// <summary> /// The list of <see cref="AnalyzerConfig" />s in this set. This list has been sorted per <see cref="AnalyzerConfig.DirectoryLengthComparer"/>. /// </summary> private readonly ImmutableArray<AnalyzerConfig> _analyzerConfigs; private readonly GlobalAnalyzerConfig _globalConfig; /// <summary> /// <see cref="SectionNameMatcher"/>s for each section. The entries in the outer array correspond to entries in <see cref="_analyzerConfigs"/>, and each inner array /// corresponds to each <see cref="AnalyzerConfig.NamedSections"/>. /// </summary> private readonly ImmutableArray<ImmutableArray<SectionNameMatcher?>> _analyzerMatchers; // PERF: diagnostic IDs will appear in the output options for every syntax tree in // the solution. We share string instances for each diagnostic ID to avoid creating // excess strings private readonly ConcurrentDictionary<ReadOnlyMemory<char>, string> _diagnosticIdCache = new ConcurrentDictionary<ReadOnlyMemory<char>, string>(CharMemoryEqualityComparer.Instance); // PERF: Most files will probably have the same options, so share the dictionary instances private readonly ConcurrentCache<List<Section>, AnalyzerConfigOptionsResult> _optionsCache = new ConcurrentCache<List<Section>, AnalyzerConfigOptionsResult>(50, SequenceEqualComparer.Instance); // arbitrary size private readonly ObjectPool<TreeOptions.Builder> _treeOptionsPool = new ObjectPool<TreeOptions.Builder>(() => ImmutableDictionary.CreateBuilder<string, ReportDiagnostic>(Section.PropertiesKeyComparer)); private readonly ObjectPool<AnalyzerOptions.Builder> _analyzerOptionsPool = new ObjectPool<AnalyzerOptions.Builder>(() => ImmutableDictionary.CreateBuilder<string, string>(Section.PropertiesKeyComparer)); private readonly ObjectPool<List<Section>> _sectionKeyPool = new ObjectPool<List<Section>>(() => new List<Section>()); private StrongBox<AnalyzerConfigOptionsResult>? _lazyConfigOptions; private sealed class SequenceEqualComparer : IEqualityComparer<List<Section>> { public static SequenceEqualComparer Instance { get; } = new SequenceEqualComparer(); public bool Equals(List<Section>? x, List<Section>? y) { if (x is null || y is null) { return x is null && y is null; } if (x.Count != y.Count) { return false; } for (int i = 0; i < x.Count; i++) { if (!ReferenceEquals(x[i], y[i])) { return false; } } return true; } public int GetHashCode(List<Section> obj) => Hash.CombineValues(obj); } private static readonly DiagnosticDescriptor InvalidAnalyzerConfigSeverityDescriptor = new DiagnosticDescriptor( "InvalidSeverityInAnalyzerConfig", CodeAnalysisResources.WRN_InvalidSeverityInAnalyzerConfig_Title, CodeAnalysisResources.WRN_InvalidSeverityInAnalyzerConfig, "AnalyzerConfig", DiagnosticSeverity.Warning, isEnabledByDefault: true); private static readonly DiagnosticDescriptor MultipleGlobalAnalyzerKeysDescriptor = new DiagnosticDescriptor( "MultipleGlobalAnalyzerKeys", CodeAnalysisResources.WRN_MultipleGlobalAnalyzerKeys_Title, CodeAnalysisResources.WRN_MultipleGlobalAnalyzerKeys, "AnalyzerConfig", DiagnosticSeverity.Warning, isEnabledByDefault: true); private static readonly DiagnosticDescriptor InvalidGlobalAnalyzerSectionDescriptor = new DiagnosticDescriptor( "InvalidGlobalSectionName", CodeAnalysisResources.WRN_InvalidGlobalSectionName_Title, CodeAnalysisResources.WRN_InvalidGlobalSectionName, "AnalyzerConfig", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static AnalyzerConfigSet Create<TList>(TList analyzerConfigs) where TList : IReadOnlyCollection<AnalyzerConfig> { return Create(analyzerConfigs, out _); } public static AnalyzerConfigSet Create<TList>(TList analyzerConfigs, out ImmutableArray<Diagnostic> diagnostics) where TList : IReadOnlyCollection<AnalyzerConfig> { var sortedAnalyzerConfigs = ArrayBuilder<AnalyzerConfig>.GetInstance(analyzerConfigs.Count); sortedAnalyzerConfigs.AddRange(analyzerConfigs); sortedAnalyzerConfigs.Sort(AnalyzerConfig.DirectoryLengthComparer); var globalConfig = MergeGlobalConfigs(sortedAnalyzerConfigs, out diagnostics); return new AnalyzerConfigSet(sortedAnalyzerConfigs.ToImmutableAndFree(), globalConfig); } private AnalyzerConfigSet(ImmutableArray<AnalyzerConfig> analyzerConfigs, GlobalAnalyzerConfig globalConfig) { _analyzerConfigs = analyzerConfigs; _globalConfig = globalConfig; var allMatchers = ArrayBuilder<ImmutableArray<SectionNameMatcher?>>.GetInstance(_analyzerConfigs.Length); foreach (var config in _analyzerConfigs) { // Create an array of regexes with each entry corresponding to the same index // in <see cref="EditorConfig.NamedSections"/>. var builder = ArrayBuilder<SectionNameMatcher?>.GetInstance(config.NamedSections.Length); foreach (var section in config.NamedSections) { SectionNameMatcher? matcher = AnalyzerConfig.TryCreateSectionNameMatcher(section.Name); builder.Add(matcher); } Debug.Assert(builder.Count == config.NamedSections.Length); allMatchers.Add(builder.ToImmutableAndFree()); } Debug.Assert(allMatchers.Count == _analyzerConfigs.Length); _analyzerMatchers = allMatchers.ToImmutableAndFree(); } /// <summary> /// Gets an <see cref="AnalyzerConfigOptionsResult"/> that contain the options that apply globally /// </summary> public AnalyzerConfigOptionsResult GlobalConfigOptions { get { if (_lazyConfigOptions is null) { Interlocked.CompareExchange( ref _lazyConfigOptions, new StrongBox<AnalyzerConfigOptionsResult>(ParseGlobalConfigOptions()), null); } return _lazyConfigOptions.Value; } } /// <summary> /// Returns a <see cref="AnalyzerConfigOptionsResult"/> for a source file. This computes which <see cref="AnalyzerConfig"/> rules applies to this file, and correctly applies /// precedence rules if there are multiple rules for the same file. /// </summary> /// <param name="sourcePath">The path to a file such as a source file or additional file. Must be non-null.</param> /// <remarks>This method is safe to call from multiple threads.</remarks> public AnalyzerConfigOptionsResult GetOptionsForSourcePath(string sourcePath) { if (sourcePath == null) { throw new ArgumentNullException(nameof(sourcePath)); } var sectionKey = _sectionKeyPool.Allocate(); var normalizedPath = PathUtilities.NormalizeWithForwardSlash(sourcePath); // If we have a global config, add any sections that match the full path foreach (var section in _globalConfig.NamedSections) { var escapedSectionName = TryUnescapeSectionName(section.Name, out var sectionName); if (escapedSectionName && normalizedPath.Equals(sectionName, Section.NameComparer)) { sectionKey.Add(section); } } int globalConfigOptionsCount = sectionKey.Count; // The editorconfig paths are sorted from shortest to longest, so matches // are resolved from most nested to least nested, where last setting wins for (int analyzerConfigIndex = 0; analyzerConfigIndex < _analyzerConfigs.Length; analyzerConfigIndex++) { var config = _analyzerConfigs[analyzerConfigIndex]; if (normalizedPath.StartsWith(config.NormalizedDirectory, StringComparison.Ordinal)) { // If this config is a root config, then clear earlier options since they don't apply // to this source file. if (config.IsRoot) { sectionKey.RemoveRange(globalConfigOptionsCount, sectionKey.Count - globalConfigOptionsCount); } int dirLength = config.NormalizedDirectory.Length; // Leave '/' if the normalized directory ends with a '/'. This can happen if // we're in a root directory (e.g. '/' or 'Z:/'). The section matching // always expects that the relative path start with a '/'. if (config.NormalizedDirectory[dirLength - 1] == '/') { dirLength--; } string relativePath = normalizedPath.Substring(dirLength); ImmutableArray<SectionNameMatcher?> matchers = _analyzerMatchers[analyzerConfigIndex]; for (int sectionIndex = 0; sectionIndex < matchers.Length; sectionIndex++) { if (matchers[sectionIndex]?.IsMatch(relativePath) == true) { var section = config.NamedSections[sectionIndex]; sectionKey.Add(section); } } } } // Try to avoid creating extra dictionaries if we've already seen an options result with the // exact same options if (!_optionsCache.TryGetValue(sectionKey, out var result)) { var treeOptionsBuilder = _treeOptionsPool.Allocate(); var analyzerOptionsBuilder = _analyzerOptionsPool.Allocate(); var diagnosticBuilder = ArrayBuilder<Diagnostic>.GetInstance(); int sectionKeyIndex = 0; analyzerOptionsBuilder.AddRange(GlobalConfigOptions.AnalyzerOptions); foreach (var configSection in _globalConfig.NamedSections) { if (sectionKey.Count > 0 && configSection == sectionKey[sectionKeyIndex]) { ParseSectionOptions( sectionKey[sectionKeyIndex], treeOptionsBuilder, analyzerOptionsBuilder, diagnosticBuilder, GlobalAnalyzerConfigBuilder.GlobalConfigPath, _diagnosticIdCache); sectionKeyIndex++; if (sectionKeyIndex == sectionKey.Count) { break; } } } for (int analyzerConfigIndex = 0; analyzerConfigIndex < _analyzerConfigs.Length && sectionKeyIndex < sectionKey.Count; analyzerConfigIndex++) { AnalyzerConfig config = _analyzerConfigs[analyzerConfigIndex]; ImmutableArray<SectionNameMatcher?> matchers = _analyzerMatchers[analyzerConfigIndex]; for (int matcherIndex = 0; matcherIndex < matchers.Length; matcherIndex++) { if (sectionKey[sectionKeyIndex] == config.NamedSections[matcherIndex]) { ParseSectionOptions( sectionKey[sectionKeyIndex], treeOptionsBuilder, analyzerOptionsBuilder, diagnosticBuilder, config.PathToFile, _diagnosticIdCache); sectionKeyIndex++; if (sectionKeyIndex == sectionKey.Count) { // Exit the inner 'for' loop now that work is done. The outer loop is handled by a // top-level condition. break; } } } } result = new AnalyzerConfigOptionsResult( treeOptionsBuilder.Count > 0 ? treeOptionsBuilder.ToImmutable() : SyntaxTree.EmptyDiagnosticOptions, analyzerOptionsBuilder.Count > 0 ? analyzerOptionsBuilder.ToImmutable() : AnalyzerConfigOptions.EmptyDictionary, diagnosticBuilder.ToImmutableAndFree()); if (_optionsCache.TryAdd(sectionKey, result)) { // Release the pooled object to be used as a key _sectionKeyPool.ForgetTrackedObject(sectionKey); } else { freeKey(sectionKey, _sectionKeyPool); } treeOptionsBuilder.Clear(); analyzerOptionsBuilder.Clear(); _treeOptionsPool.Free(treeOptionsBuilder); _analyzerOptionsPool.Free(analyzerOptionsBuilder); } else { freeKey(sectionKey, _sectionKeyPool); } return result; static void freeKey(List<Section> sectionKey, ObjectPool<List<Section>> pool) { sectionKey.Clear(); pool.Free(sectionKey); } } internal static bool TryParseSeverity(string value, out ReportDiagnostic severity) { var comparer = StringComparer.OrdinalIgnoreCase; if (comparer.Equals(value, "default")) { severity = ReportDiagnostic.Default; return true; } else if (comparer.Equals(value, "error")) { severity = ReportDiagnostic.Error; return true; } else if (comparer.Equals(value, "warning")) { severity = ReportDiagnostic.Warn; return true; } else if (comparer.Equals(value, "suggestion")) { severity = ReportDiagnostic.Info; return true; } else if (comparer.Equals(value, "silent") || comparer.Equals(value, "refactoring")) { severity = ReportDiagnostic.Hidden; return true; } else if (comparer.Equals(value, "none")) { severity = ReportDiagnostic.Suppress; return true; } severity = default; return false; } private AnalyzerConfigOptionsResult ParseGlobalConfigOptions() { var treeOptionsBuilder = _treeOptionsPool.Allocate(); var analyzerOptionsBuilder = _analyzerOptionsPool.Allocate(); var diagnosticBuilder = ArrayBuilder<Diagnostic>.GetInstance(); ParseSectionOptions(_globalConfig.GlobalSection, treeOptionsBuilder, analyzerOptionsBuilder, diagnosticBuilder, GlobalAnalyzerConfigBuilder.GlobalConfigPath, _diagnosticIdCache); var options = new AnalyzerConfigOptionsResult( treeOptionsBuilder.ToImmutable(), analyzerOptionsBuilder.ToImmutable(), diagnosticBuilder.ToImmutableAndFree()); treeOptionsBuilder.Clear(); analyzerOptionsBuilder.Clear(); _treeOptionsPool.Free(treeOptionsBuilder); _analyzerOptionsPool.Free(analyzerOptionsBuilder); return options; } private static void ParseSectionOptions(Section section, TreeOptions.Builder treeBuilder, AnalyzerOptions.Builder analyzerBuilder, ArrayBuilder<Diagnostic> diagnosticBuilder, string analyzerConfigPath, ConcurrentDictionary<ReadOnlyMemory<char>, string> diagIdCache) { const string diagnosticOptionPrefix = "dotnet_diagnostic."; const string diagnosticOptionSuffix = ".severity"; foreach (var (key, value) in section.Properties) { // Keys are lowercased in editorconfig parsing int diagIdLength = -1; if (key.StartsWith(diagnosticOptionPrefix, StringComparison.Ordinal) && key.EndsWith(diagnosticOptionSuffix, StringComparison.Ordinal)) { diagIdLength = key.Length - (diagnosticOptionPrefix.Length + diagnosticOptionSuffix.Length); } if (diagIdLength >= 0) { ReadOnlyMemory<char> idSlice = key.AsMemory().Slice(diagnosticOptionPrefix.Length, diagIdLength); // PERF: this is similar to a double-checked locking pattern, and trying to fetch the ID first // lets us avoid an allocation if the id has already been added if (!diagIdCache.TryGetValue(idSlice, out var diagId)) { // We use ReadOnlyMemory<char> to allow allocation-free lookups in the // dictionary, but the actual keys stored in the dictionary are trimmed // to avoid holding GC references to larger strings than necessary. The // GetOrAdd APIs do not allow the key to be manipulated between lookup // and insertion, so we separate the operations here in code. diagId = idSlice.ToString(); diagId = diagIdCache.GetOrAdd(diagId.AsMemory(), diagId); } if (TryParseSeverity(value, out ReportDiagnostic severity)) { treeBuilder[diagId] = severity; } else { diagnosticBuilder.Add(Diagnostic.Create( InvalidAnalyzerConfigSeverityDescriptor, Location.None, diagId, value, analyzerConfigPath)); } } else { analyzerBuilder[key] = value; } } } /// <summary> /// Merge any partial global configs into a single global config, and remove the partial configs /// </summary> /// <param name="analyzerConfigs">An <see cref="ArrayBuilder{T}"/> of <see cref="AnalyzerConfig"/> containing a mix of regular and unmerged partial global configs</param> /// <param name="diagnostics">Diagnostics produced during merge will be added to this bag</param> /// <returns>A <see cref="GlobalAnalyzerConfig" /> that contains the merged partial configs, or <c>null</c> if there were no partial configs</returns> internal static GlobalAnalyzerConfig MergeGlobalConfigs(ArrayBuilder<AnalyzerConfig> analyzerConfigs, out ImmutableArray<Diagnostic> diagnostics) { GlobalAnalyzerConfigBuilder globalAnalyzerConfigBuilder = new GlobalAnalyzerConfigBuilder(); DiagnosticBag diagnosticBag = DiagnosticBag.GetInstance(); for (int i = 0; i < analyzerConfigs.Count; i++) { if (analyzerConfigs[i].IsGlobal) { globalAnalyzerConfigBuilder.MergeIntoGlobalConfig(analyzerConfigs[i], diagnosticBag); analyzerConfigs.RemoveAt(i); i--; } } var globalConfig = globalAnalyzerConfigBuilder.Build(diagnosticBag); diagnostics = diagnosticBag.ToReadOnlyAndFree(); return globalConfig; } /// <summary> /// Builds a global analyzer config from a series of partial configs /// </summary> internal struct GlobalAnalyzerConfigBuilder { private ImmutableDictionary<string, ImmutableDictionary<string, (string value, string configPath, int globalLevel)>.Builder>.Builder? _values; private ImmutableDictionary<string, ImmutableDictionary<string, (int globalLevel, ArrayBuilder<string> configPaths)>.Builder>.Builder? _duplicates; internal const string GlobalConfigPath = "<Global Config>"; internal const string GlobalSectionName = "Global Section"; internal void MergeIntoGlobalConfig(AnalyzerConfig config, DiagnosticBag diagnostics) { if (_values is null) { _values = ImmutableDictionary.CreateBuilder<string, ImmutableDictionary<string, (string, string, int)>.Builder>(Section.NameEqualityComparer); _duplicates = ImmutableDictionary.CreateBuilder<string, ImmutableDictionary<string, (int, ArrayBuilder<string>)>.Builder>(Section.NameEqualityComparer); } MergeSection(config.PathToFile, config.GlobalSection, config.GlobalLevel, isGlobalSection: true); foreach (var section in config.NamedSections) { if (IsAbsoluteEditorConfigPath(section.Name)) { MergeSection(config.PathToFile, section, config.GlobalLevel, isGlobalSection: false); } else { diagnostics.Add(Diagnostic.Create( InvalidGlobalAnalyzerSectionDescriptor, Location.None, section.Name, config.PathToFile)); } } } internal GlobalAnalyzerConfig Build(DiagnosticBag diagnostics) { if (_values is null || _duplicates is null) { return new GlobalAnalyzerConfig(new Section(GlobalSectionName, AnalyzerOptions.Empty), ImmutableArray<Section>.Empty); } // issue diagnostics for any duplicate keys foreach ((var section, var keys) in _duplicates) { bool isGlobalSection = string.IsNullOrWhiteSpace(section); string sectionName = isGlobalSection ? GlobalSectionName : section; foreach ((var keyName, (_, var configPaths)) in keys) { diagnostics.Add(Diagnostic.Create( MultipleGlobalAnalyzerKeysDescriptor, Location.None, keyName, sectionName, string.Join(", ", configPaths))); } } _duplicates = null; // gather the global and named sections Section globalSection = GetSection(string.Empty); _values.Remove(string.Empty); ArrayBuilder<Section> namedSectionBuilder = new ArrayBuilder<Section>(_values.Count); foreach (var sectionName in _values.Keys.Order()) { namedSectionBuilder.Add(GetSection(sectionName)); } // create the global config GlobalAnalyzerConfig globalConfig = new GlobalAnalyzerConfig(globalSection, namedSectionBuilder.ToImmutableAndFree()); _values = null; return globalConfig; } private Section GetSection(string sectionName) { Debug.Assert(_values is object); var dict = _values[sectionName]; var result = dict.ToImmutableDictionary(d => d.Key, d => d.Value.value, Section.PropertiesKeyComparer); return new Section(sectionName, result); } private void MergeSection(string configPath, Section section, int globalLevel, bool isGlobalSection) { Debug.Assert(_values is object); Debug.Assert(_duplicates is object); if (!_values.TryGetValue(section.Name, out var sectionDict)) { sectionDict = ImmutableDictionary.CreateBuilder<string, (string, string, int)>(Section.PropertiesKeyComparer); _values.Add(section.Name, sectionDict); } _duplicates.TryGetValue(section.Name, out var duplicateDict); foreach ((var key, var value) in section.Properties) { if (isGlobalSection && (Section.PropertiesKeyComparer.Equals(key, GlobalKey) || Section.PropertiesKeyComparer.Equals(key, GlobalLevelKey))) { continue; } bool keyInSection = sectionDict.TryGetValue(key, out var sectionValue); (int globalLevel, ArrayBuilder<string> configPaths) duplicateValue = default; bool keyDuplicated = !keyInSection && duplicateDict?.TryGetValue(key, out duplicateValue) == true; // if this key is neither already present, or already duplicate, we can add it if (!keyInSection && !keyDuplicated) { sectionDict.Add(key, (value, configPath, globalLevel)); } else { int currentGlobalLevel = keyInSection ? sectionValue.globalLevel : duplicateValue.globalLevel; // if this key overrides one we knew about previously, replace it if (currentGlobalLevel < globalLevel) { sectionDict[key] = (value, configPath, globalLevel); if (keyDuplicated) { duplicateDict!.Remove(key); } } // this key conflicts with a previous one else if (currentGlobalLevel == globalLevel) { if (duplicateDict is null) { duplicateDict = ImmutableDictionary.CreateBuilder<string, (int, ArrayBuilder<string>)>(Section.PropertiesKeyComparer); _duplicates.Add(section.Name, duplicateDict); } // record that this key is now a duplicate ArrayBuilder<string> configList = duplicateValue.configPaths ?? ArrayBuilder<string>.GetInstance(); configList.Add(configPath); duplicateDict[key] = (globalLevel, configList); // if we'd previously added this key, remove it and remember the extra duplicate location if (keyInSection) { var originalEntry = sectionValue; Debug.Assert(originalEntry.globalLevel == globalLevel); sectionDict.Remove(key); configList.Insert(0, originalEntry.configPath); } } } } } } /// <summary> /// Represents a combined global analyzer config. /// </summary> /// <remarks> /// We parse all <see cref="AnalyzerConfig"/>s as individual files, according to the editorconfig spec. /// /// However, when viewing the configs as an <see cref="AnalyzerConfigSet"/> if multiple files have the /// <c>is_global</c> property set to <c>true</c> we combine those files and treat them as a single /// 'logical' global config file. This type represents that combined file. /// </remarks> internal sealed class GlobalAnalyzerConfig { internal AnalyzerConfig.Section GlobalSection { get; } internal ImmutableArray<AnalyzerConfig.Section> NamedSections { get; } public GlobalAnalyzerConfig(AnalyzerConfig.Section globalSection, ImmutableArray<AnalyzerConfig.Section> namedSections) { GlobalSection = globalSection; NamedSections = namedSections; } } } }
// Licensed to the .NET Foundation under one or more 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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.AnalyzerConfig; using AnalyzerOptions = System.Collections.Immutable.ImmutableDictionary<string, string>; using TreeOptions = System.Collections.Immutable.ImmutableDictionary<string, Microsoft.CodeAnalysis.ReportDiagnostic>; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a set of <see cref="AnalyzerConfig"/>, and can compute the effective analyzer options for a given source file. This is used to /// collect all the <see cref="AnalyzerConfig"/> files for that would apply to a compilation. /// </summary> public sealed class AnalyzerConfigSet { /// <summary> /// The list of <see cref="AnalyzerConfig" />s in this set. This list has been sorted per <see cref="AnalyzerConfig.DirectoryLengthComparer"/>. /// </summary> private readonly ImmutableArray<AnalyzerConfig> _analyzerConfigs; private readonly GlobalAnalyzerConfig _globalConfig; /// <summary> /// <see cref="SectionNameMatcher"/>s for each section. The entries in the outer array correspond to entries in <see cref="_analyzerConfigs"/>, and each inner array /// corresponds to each <see cref="AnalyzerConfig.NamedSections"/>. /// </summary> private readonly ImmutableArray<ImmutableArray<SectionNameMatcher?>> _analyzerMatchers; // PERF: diagnostic IDs will appear in the output options for every syntax tree in // the solution. We share string instances for each diagnostic ID to avoid creating // excess strings private readonly ConcurrentDictionary<ReadOnlyMemory<char>, string> _diagnosticIdCache = new ConcurrentDictionary<ReadOnlyMemory<char>, string>(CharMemoryEqualityComparer.Instance); // PERF: Most files will probably have the same options, so share the dictionary instances private readonly ConcurrentCache<List<Section>, AnalyzerConfigOptionsResult> _optionsCache = new ConcurrentCache<List<Section>, AnalyzerConfigOptionsResult>(50, SequenceEqualComparer.Instance); // arbitrary size private readonly ObjectPool<TreeOptions.Builder> _treeOptionsPool = new ObjectPool<TreeOptions.Builder>(() => ImmutableDictionary.CreateBuilder<string, ReportDiagnostic>(Section.PropertiesKeyComparer)); private readonly ObjectPool<AnalyzerOptions.Builder> _analyzerOptionsPool = new ObjectPool<AnalyzerOptions.Builder>(() => ImmutableDictionary.CreateBuilder<string, string>(Section.PropertiesKeyComparer)); private readonly ObjectPool<List<Section>> _sectionKeyPool = new ObjectPool<List<Section>>(() => new List<Section>()); private StrongBox<AnalyzerConfigOptionsResult>? _lazyConfigOptions; private sealed class SequenceEqualComparer : IEqualityComparer<List<Section>> { public static SequenceEqualComparer Instance { get; } = new SequenceEqualComparer(); public bool Equals(List<Section>? x, List<Section>? y) { if (x is null || y is null) { return x is null && y is null; } if (x.Count != y.Count) { return false; } for (int i = 0; i < x.Count; i++) { if (!ReferenceEquals(x[i], y[i])) { return false; } } return true; } public int GetHashCode(List<Section> obj) => Hash.CombineValues(obj); } private static readonly DiagnosticDescriptor InvalidAnalyzerConfigSeverityDescriptor = new DiagnosticDescriptor( "InvalidSeverityInAnalyzerConfig", CodeAnalysisResources.WRN_InvalidSeverityInAnalyzerConfig_Title, CodeAnalysisResources.WRN_InvalidSeverityInAnalyzerConfig, "AnalyzerConfig", DiagnosticSeverity.Warning, isEnabledByDefault: true); private static readonly DiagnosticDescriptor MultipleGlobalAnalyzerKeysDescriptor = new DiagnosticDescriptor( "MultipleGlobalAnalyzerKeys", CodeAnalysisResources.WRN_MultipleGlobalAnalyzerKeys_Title, CodeAnalysisResources.WRN_MultipleGlobalAnalyzerKeys, "AnalyzerConfig", DiagnosticSeverity.Warning, isEnabledByDefault: true); private static readonly DiagnosticDescriptor InvalidGlobalAnalyzerSectionDescriptor = new DiagnosticDescriptor( "InvalidGlobalSectionName", CodeAnalysisResources.WRN_InvalidGlobalSectionName_Title, CodeAnalysisResources.WRN_InvalidGlobalSectionName, "AnalyzerConfig", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static AnalyzerConfigSet Create<TList>(TList analyzerConfigs) where TList : IReadOnlyCollection<AnalyzerConfig> { return Create(analyzerConfigs, out _); } public static AnalyzerConfigSet Create<TList>(TList analyzerConfigs, out ImmutableArray<Diagnostic> diagnostics) where TList : IReadOnlyCollection<AnalyzerConfig> { var sortedAnalyzerConfigs = ArrayBuilder<AnalyzerConfig>.GetInstance(analyzerConfigs.Count); sortedAnalyzerConfigs.AddRange(analyzerConfigs); sortedAnalyzerConfigs.Sort(AnalyzerConfig.DirectoryLengthComparer); var globalConfig = MergeGlobalConfigs(sortedAnalyzerConfigs, out diagnostics); return new AnalyzerConfigSet(sortedAnalyzerConfigs.ToImmutableAndFree(), globalConfig); } private AnalyzerConfigSet(ImmutableArray<AnalyzerConfig> analyzerConfigs, GlobalAnalyzerConfig globalConfig) { _analyzerConfigs = analyzerConfigs; _globalConfig = globalConfig; var allMatchers = ArrayBuilder<ImmutableArray<SectionNameMatcher?>>.GetInstance(_analyzerConfigs.Length); foreach (var config in _analyzerConfigs) { // Create an array of regexes with each entry corresponding to the same index // in <see cref="EditorConfig.NamedSections"/>. var builder = ArrayBuilder<SectionNameMatcher?>.GetInstance(config.NamedSections.Length); foreach (var section in config.NamedSections) { SectionNameMatcher? matcher = AnalyzerConfig.TryCreateSectionNameMatcher(section.Name); builder.Add(matcher); } Debug.Assert(builder.Count == config.NamedSections.Length); allMatchers.Add(builder.ToImmutableAndFree()); } Debug.Assert(allMatchers.Count == _analyzerConfigs.Length); _analyzerMatchers = allMatchers.ToImmutableAndFree(); } /// <summary> /// Gets an <see cref="AnalyzerConfigOptionsResult"/> that contain the options that apply globally /// </summary> public AnalyzerConfigOptionsResult GlobalConfigOptions { get { if (_lazyConfigOptions is null) { Interlocked.CompareExchange( ref _lazyConfigOptions, new StrongBox<AnalyzerConfigOptionsResult>(ParseGlobalConfigOptions()), null); } return _lazyConfigOptions.Value; } } /// <summary> /// Returns a <see cref="AnalyzerConfigOptionsResult"/> for a source file. This computes which <see cref="AnalyzerConfig"/> rules applies to this file, and correctly applies /// precedence rules if there are multiple rules for the same file. /// </summary> /// <param name="sourcePath">The path to a file such as a source file or additional file. Must be non-null.</param> /// <remarks>This method is safe to call from multiple threads.</remarks> public AnalyzerConfigOptionsResult GetOptionsForSourcePath(string sourcePath) { if (sourcePath == null) { throw new ArgumentNullException(nameof(sourcePath)); } var sectionKey = _sectionKeyPool.Allocate(); var normalizedPath = PathUtilities.NormalizeWithForwardSlash(sourcePath); // If we have a global config, add any sections that match the full path foreach (var section in _globalConfig.NamedSections) { var escapedSectionName = TryUnescapeSectionName(section.Name, out var sectionName); if (escapedSectionName && normalizedPath.Equals(sectionName, Section.NameComparer)) { sectionKey.Add(section); } } int globalConfigOptionsCount = sectionKey.Count; // The editorconfig paths are sorted from shortest to longest, so matches // are resolved from most nested to least nested, where last setting wins for (int analyzerConfigIndex = 0; analyzerConfigIndex < _analyzerConfigs.Length; analyzerConfigIndex++) { var config = _analyzerConfigs[analyzerConfigIndex]; if (normalizedPath.StartsWith(config.NormalizedDirectory, StringComparison.Ordinal)) { // If this config is a root config, then clear earlier options since they don't apply // to this source file. if (config.IsRoot) { sectionKey.RemoveRange(globalConfigOptionsCount, sectionKey.Count - globalConfigOptionsCount); } int dirLength = config.NormalizedDirectory.Length; // Leave '/' if the normalized directory ends with a '/'. This can happen if // we're in a root directory (e.g. '/' or 'Z:/'). The section matching // always expects that the relative path start with a '/'. if (config.NormalizedDirectory[dirLength - 1] == '/') { dirLength--; } string relativePath = normalizedPath.Substring(dirLength); ImmutableArray<SectionNameMatcher?> matchers = _analyzerMatchers[analyzerConfigIndex]; for (int sectionIndex = 0; sectionIndex < matchers.Length; sectionIndex++) { if (matchers[sectionIndex]?.IsMatch(relativePath) == true) { var section = config.NamedSections[sectionIndex]; sectionKey.Add(section); } } } } // Try to avoid creating extra dictionaries if we've already seen an options result with the // exact same options if (!_optionsCache.TryGetValue(sectionKey, out var result)) { var treeOptionsBuilder = _treeOptionsPool.Allocate(); var analyzerOptionsBuilder = _analyzerOptionsPool.Allocate(); var diagnosticBuilder = ArrayBuilder<Diagnostic>.GetInstance(); int sectionKeyIndex = 0; analyzerOptionsBuilder.AddRange(GlobalConfigOptions.AnalyzerOptions); foreach (var configSection in _globalConfig.NamedSections) { if (sectionKey.Count > 0 && configSection == sectionKey[sectionKeyIndex]) { ParseSectionOptions( sectionKey[sectionKeyIndex], treeOptionsBuilder, analyzerOptionsBuilder, diagnosticBuilder, GlobalAnalyzerConfigBuilder.GlobalConfigPath, _diagnosticIdCache); sectionKeyIndex++; if (sectionKeyIndex == sectionKey.Count) { break; } } } for (int analyzerConfigIndex = 0; analyzerConfigIndex < _analyzerConfigs.Length && sectionKeyIndex < sectionKey.Count; analyzerConfigIndex++) { AnalyzerConfig config = _analyzerConfigs[analyzerConfigIndex]; ImmutableArray<SectionNameMatcher?> matchers = _analyzerMatchers[analyzerConfigIndex]; for (int matcherIndex = 0; matcherIndex < matchers.Length; matcherIndex++) { if (sectionKey[sectionKeyIndex] == config.NamedSections[matcherIndex]) { ParseSectionOptions( sectionKey[sectionKeyIndex], treeOptionsBuilder, analyzerOptionsBuilder, diagnosticBuilder, config.PathToFile, _diagnosticIdCache); sectionKeyIndex++; if (sectionKeyIndex == sectionKey.Count) { // Exit the inner 'for' loop now that work is done. The outer loop is handled by a // top-level condition. break; } } } } result = new AnalyzerConfigOptionsResult( treeOptionsBuilder.Count > 0 ? treeOptionsBuilder.ToImmutable() : SyntaxTree.EmptyDiagnosticOptions, analyzerOptionsBuilder.Count > 0 ? analyzerOptionsBuilder.ToImmutable() : AnalyzerConfigOptions.EmptyDictionary, diagnosticBuilder.ToImmutableAndFree()); if (_optionsCache.TryAdd(sectionKey, result)) { // Release the pooled object to be used as a key _sectionKeyPool.ForgetTrackedObject(sectionKey); } else { freeKey(sectionKey, _sectionKeyPool); } treeOptionsBuilder.Clear(); analyzerOptionsBuilder.Clear(); _treeOptionsPool.Free(treeOptionsBuilder); _analyzerOptionsPool.Free(analyzerOptionsBuilder); } else { freeKey(sectionKey, _sectionKeyPool); } return result; static void freeKey(List<Section> sectionKey, ObjectPool<List<Section>> pool) { sectionKey.Clear(); pool.Free(sectionKey); } } internal static bool TryParseSeverity(string value, out ReportDiagnostic severity) { var comparer = StringComparer.OrdinalIgnoreCase; if (comparer.Equals(value, "default")) { severity = ReportDiagnostic.Default; return true; } else if (comparer.Equals(value, "error")) { severity = ReportDiagnostic.Error; return true; } else if (comparer.Equals(value, "warning")) { severity = ReportDiagnostic.Warn; return true; } else if (comparer.Equals(value, "suggestion")) { severity = ReportDiagnostic.Info; return true; } else if (comparer.Equals(value, "silent") || comparer.Equals(value, "refactoring")) { severity = ReportDiagnostic.Hidden; return true; } else if (comparer.Equals(value, "none")) { severity = ReportDiagnostic.Suppress; return true; } severity = default; return false; } private AnalyzerConfigOptionsResult ParseGlobalConfigOptions() { var treeOptionsBuilder = _treeOptionsPool.Allocate(); var analyzerOptionsBuilder = _analyzerOptionsPool.Allocate(); var diagnosticBuilder = ArrayBuilder<Diagnostic>.GetInstance(); ParseSectionOptions(_globalConfig.GlobalSection, treeOptionsBuilder, analyzerOptionsBuilder, diagnosticBuilder, GlobalAnalyzerConfigBuilder.GlobalConfigPath, _diagnosticIdCache); var options = new AnalyzerConfigOptionsResult( treeOptionsBuilder.ToImmutable(), analyzerOptionsBuilder.ToImmutable(), diagnosticBuilder.ToImmutableAndFree()); treeOptionsBuilder.Clear(); analyzerOptionsBuilder.Clear(); _treeOptionsPool.Free(treeOptionsBuilder); _analyzerOptionsPool.Free(analyzerOptionsBuilder); return options; } private static void ParseSectionOptions(Section section, TreeOptions.Builder treeBuilder, AnalyzerOptions.Builder analyzerBuilder, ArrayBuilder<Diagnostic> diagnosticBuilder, string analyzerConfigPath, ConcurrentDictionary<ReadOnlyMemory<char>, string> diagIdCache) { const string diagnosticOptionPrefix = "dotnet_diagnostic."; const string diagnosticOptionSuffix = ".severity"; foreach (var (key, value) in section.Properties) { // Keys are lowercased in editorconfig parsing int diagIdLength = -1; if (key.StartsWith(diagnosticOptionPrefix, StringComparison.Ordinal) && key.EndsWith(diagnosticOptionSuffix, StringComparison.Ordinal)) { diagIdLength = key.Length - (diagnosticOptionPrefix.Length + diagnosticOptionSuffix.Length); } if (diagIdLength >= 0) { ReadOnlyMemory<char> idSlice = key.AsMemory().Slice(diagnosticOptionPrefix.Length, diagIdLength); // PERF: this is similar to a double-checked locking pattern, and trying to fetch the ID first // lets us avoid an allocation if the id has already been added if (!diagIdCache.TryGetValue(idSlice, out var diagId)) { // We use ReadOnlyMemory<char> to allow allocation-free lookups in the // dictionary, but the actual keys stored in the dictionary are trimmed // to avoid holding GC references to larger strings than necessary. The // GetOrAdd APIs do not allow the key to be manipulated between lookup // and insertion, so we separate the operations here in code. diagId = idSlice.ToString(); diagId = diagIdCache.GetOrAdd(diagId.AsMemory(), diagId); } if (TryParseSeverity(value, out ReportDiagnostic severity)) { treeBuilder[diagId] = severity; } else { diagnosticBuilder.Add(Diagnostic.Create( InvalidAnalyzerConfigSeverityDescriptor, Location.None, diagId, value, analyzerConfigPath)); } } else { analyzerBuilder[key] = value; } } } /// <summary> /// Merge any partial global configs into a single global config, and remove the partial configs /// </summary> /// <param name="analyzerConfigs">An <see cref="ArrayBuilder{T}"/> of <see cref="AnalyzerConfig"/> containing a mix of regular and unmerged partial global configs</param> /// <param name="diagnostics">Diagnostics produced during merge will be added to this bag</param> /// <returns>A <see cref="GlobalAnalyzerConfig" /> that contains the merged partial configs, or <c>null</c> if there were no partial configs</returns> internal static GlobalAnalyzerConfig MergeGlobalConfigs(ArrayBuilder<AnalyzerConfig> analyzerConfigs, out ImmutableArray<Diagnostic> diagnostics) { GlobalAnalyzerConfigBuilder globalAnalyzerConfigBuilder = new GlobalAnalyzerConfigBuilder(); DiagnosticBag diagnosticBag = DiagnosticBag.GetInstance(); for (int i = 0; i < analyzerConfigs.Count; i++) { if (analyzerConfigs[i].IsGlobal) { globalAnalyzerConfigBuilder.MergeIntoGlobalConfig(analyzerConfigs[i], diagnosticBag); analyzerConfigs.RemoveAt(i); i--; } } var globalConfig = globalAnalyzerConfigBuilder.Build(diagnosticBag); diagnostics = diagnosticBag.ToReadOnlyAndFree(); return globalConfig; } /// <summary> /// Builds a global analyzer config from a series of partial configs /// </summary> internal struct GlobalAnalyzerConfigBuilder { private ImmutableDictionary<string, ImmutableDictionary<string, (string value, string configPath, int globalLevel)>.Builder>.Builder? _values; private ImmutableDictionary<string, ImmutableDictionary<string, (int globalLevel, ArrayBuilder<string> configPaths)>.Builder>.Builder? _duplicates; internal const string GlobalConfigPath = "<Global Config>"; internal const string GlobalSectionName = "Global Section"; internal void MergeIntoGlobalConfig(AnalyzerConfig config, DiagnosticBag diagnostics) { if (_values is null) { _values = ImmutableDictionary.CreateBuilder<string, ImmutableDictionary<string, (string, string, int)>.Builder>(Section.NameEqualityComparer); _duplicates = ImmutableDictionary.CreateBuilder<string, ImmutableDictionary<string, (int, ArrayBuilder<string>)>.Builder>(Section.NameEqualityComparer); } MergeSection(config.PathToFile, config.GlobalSection, config.GlobalLevel, isGlobalSection: true); foreach (var section in config.NamedSections) { if (IsAbsoluteEditorConfigPath(section.Name)) { MergeSection(config.PathToFile, section, config.GlobalLevel, isGlobalSection: false); } else { diagnostics.Add(Diagnostic.Create( InvalidGlobalAnalyzerSectionDescriptor, Location.None, section.Name, config.PathToFile)); } } } internal GlobalAnalyzerConfig Build(DiagnosticBag diagnostics) { if (_values is null || _duplicates is null) { return new GlobalAnalyzerConfig(new Section(GlobalSectionName, AnalyzerOptions.Empty), ImmutableArray<Section>.Empty); } // issue diagnostics for any duplicate keys foreach ((var section, var keys) in _duplicates) { bool isGlobalSection = string.IsNullOrWhiteSpace(section); string sectionName = isGlobalSection ? GlobalSectionName : section; foreach ((var keyName, (_, var configPaths)) in keys) { diagnostics.Add(Diagnostic.Create( MultipleGlobalAnalyzerKeysDescriptor, Location.None, keyName, sectionName, string.Join(", ", configPaths))); } } _duplicates = null; // gather the global and named sections Section globalSection = GetSection(string.Empty); _values.Remove(string.Empty); ArrayBuilder<Section> namedSectionBuilder = new ArrayBuilder<Section>(_values.Count); foreach (var sectionName in _values.Keys.Order()) { namedSectionBuilder.Add(GetSection(sectionName)); } // create the global config GlobalAnalyzerConfig globalConfig = new GlobalAnalyzerConfig(globalSection, namedSectionBuilder.ToImmutableAndFree()); _values = null; return globalConfig; } private Section GetSection(string sectionName) { Debug.Assert(_values is object); var dict = _values[sectionName]; var result = dict.ToImmutableDictionary(d => d.Key, d => d.Value.value, Section.PropertiesKeyComparer); return new Section(sectionName, result); } private void MergeSection(string configPath, Section section, int globalLevel, bool isGlobalSection) { Debug.Assert(_values is object); Debug.Assert(_duplicates is object); if (!_values.TryGetValue(section.Name, out var sectionDict)) { sectionDict = ImmutableDictionary.CreateBuilder<string, (string, string, int)>(Section.PropertiesKeyComparer); _values.Add(section.Name, sectionDict); } _duplicates.TryGetValue(section.Name, out var duplicateDict); foreach ((var key, var value) in section.Properties) { if (isGlobalSection && (Section.PropertiesKeyComparer.Equals(key, GlobalKey) || Section.PropertiesKeyComparer.Equals(key, GlobalLevelKey))) { continue; } bool keyInSection = sectionDict.TryGetValue(key, out var sectionValue); (int globalLevel, ArrayBuilder<string> configPaths) duplicateValue = default; bool keyDuplicated = !keyInSection && duplicateDict?.TryGetValue(key, out duplicateValue) == true; // if this key is neither already present, or already duplicate, we can add it if (!keyInSection && !keyDuplicated) { sectionDict.Add(key, (value, configPath, globalLevel)); } else { int currentGlobalLevel = keyInSection ? sectionValue.globalLevel : duplicateValue.globalLevel; // if this key overrides one we knew about previously, replace it if (currentGlobalLevel < globalLevel) { sectionDict[key] = (value, configPath, globalLevel); if (keyDuplicated) { duplicateDict!.Remove(key); } } // this key conflicts with a previous one else if (currentGlobalLevel == globalLevel) { if (duplicateDict is null) { duplicateDict = ImmutableDictionary.CreateBuilder<string, (int, ArrayBuilder<string>)>(Section.PropertiesKeyComparer); _duplicates.Add(section.Name, duplicateDict); } // record that this key is now a duplicate ArrayBuilder<string> configList = duplicateValue.configPaths ?? ArrayBuilder<string>.GetInstance(); configList.Add(configPath); duplicateDict[key] = (globalLevel, configList); // if we'd previously added this key, remove it and remember the extra duplicate location if (keyInSection) { var originalEntry = sectionValue; Debug.Assert(originalEntry.globalLevel == globalLevel); sectionDict.Remove(key); configList.Insert(0, originalEntry.configPath); } } } } } } /// <summary> /// Represents a combined global analyzer config. /// </summary> /// <remarks> /// We parse all <see cref="AnalyzerConfig"/>s as individual files, according to the editorconfig spec. /// /// However, when viewing the configs as an <see cref="AnalyzerConfigSet"/> if multiple files have the /// <c>is_global</c> property set to <c>true</c> we combine those files and treat them as a single /// 'logical' global config file. This type represents that combined file. /// </remarks> internal sealed class GlobalAnalyzerConfig { internal AnalyzerConfig.Section GlobalSection { get; } internal ImmutableArray<AnalyzerConfig.Section> NamedSections { get; } public GlobalAnalyzerConfig(AnalyzerConfig.Section globalSection, ImmutableArray<AnalyzerConfig.Section> namedSections) { GlobalSection = globalSection; NamedSections = namedSections; } } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Tools/ExternalAccess/FSharp/Internal/NavigateTo/FSharpNavigateToSearchService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.NavigateTo; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.NavigateTo; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.NavigateTo { [Shared] [ExportLanguageService(typeof(INavigateToSearchService), LanguageNames.FSharp)] internal class FSharpNavigateToSearchService : INavigateToSearchService { private readonly IFSharpNavigateToSearchService _service; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpNavigateToSearchService(IFSharpNavigateToSearchService service) { _service = service; } public IImmutableSet<string> KindsProvided => _service.KindsProvided; public bool CanFilter => _service.CanFilter; public async Task<NavigateToSearchLocation> SearchDocumentAsync( Document document, string searchPattern, IImmutableSet<string> kinds, Func<INavigateToSearchResult, Task> onResultFound, bool isFullyLoaded, CancellationToken cancellationToken) { var results = await _service.SearchDocumentAsync(document, searchPattern, kinds, cancellationToken).ConfigureAwait(false); foreach (var result in results) await onResultFound(new InternalFSharpNavigateToSearchResult(result)).ConfigureAwait(false); return NavigateToSearchLocation.Latest; } public async Task<NavigateToSearchLocation> SearchProjectAsync( Project project, ImmutableArray<Document> priorityDocuments, string searchPattern, IImmutableSet<string> kinds, Func<INavigateToSearchResult, Task> onResultFound, bool isFullyLoaded, CancellationToken cancellationToken) { var results = await _service.SearchProjectAsync(project, priorityDocuments, searchPattern, kinds, cancellationToken).ConfigureAwait(false); foreach (var result in results) await onResultFound(new InternalFSharpNavigateToSearchResult(result)).ConfigureAwait(false); return NavigateToSearchLocation.Latest; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.NavigateTo; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.NavigateTo; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.NavigateTo { [Shared] [ExportLanguageService(typeof(INavigateToSearchService), LanguageNames.FSharp)] internal class FSharpNavigateToSearchService : INavigateToSearchService { private readonly IFSharpNavigateToSearchService _service; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpNavigateToSearchService(IFSharpNavigateToSearchService service) { _service = service; } public IImmutableSet<string> KindsProvided => _service.KindsProvided; public bool CanFilter => _service.CanFilter; public async Task<NavigateToSearchLocation> SearchDocumentAsync( Document document, string searchPattern, IImmutableSet<string> kinds, Func<INavigateToSearchResult, Task> onResultFound, bool isFullyLoaded, CancellationToken cancellationToken) { var results = await _service.SearchDocumentAsync(document, searchPattern, kinds, cancellationToken).ConfigureAwait(false); foreach (var result in results) await onResultFound(new InternalFSharpNavigateToSearchResult(result)).ConfigureAwait(false); return NavigateToSearchLocation.Latest; } public async Task<NavigateToSearchLocation> SearchProjectAsync( Project project, ImmutableArray<Document> priorityDocuments, string searchPattern, IImmutableSet<string> kinds, Func<INavigateToSearchResult, Task> onResultFound, bool isFullyLoaded, CancellationToken cancellationToken) { var results = await _service.SearchProjectAsync(project, priorityDocuments, searchPattern, kinds, cancellationToken).ConfigureAwait(false); foreach (var result in results) await onResultFound(new InternalFSharpNavigateToSearchResult(result)).ConfigureAwait(false); return NavigateToSearchLocation.Latest; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Features/Core/Portable/CodeFixes/CodeFixService.FixAllPredefinedDiagnosticProvider.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.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { internal partial class CodeFixService { private class FixAllPredefinedDiagnosticProvider : FixAllContext.DiagnosticProvider { private readonly ImmutableArray<Diagnostic> _diagnostics; public FixAllPredefinedDiagnosticProvider(ImmutableArray<Diagnostic> diagnostics) => _diagnostics = diagnostics; public override Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken) => Task.FromResult<IEnumerable<Diagnostic>>(_diagnostics); public override Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken) => Task.FromResult<IEnumerable<Diagnostic>>(_diagnostics); public override Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken) => SpecializedTasks.EmptyEnumerable<Diagnostic>(); } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { internal partial class CodeFixService { private class FixAllPredefinedDiagnosticProvider : FixAllContext.DiagnosticProvider { private readonly ImmutableArray<Diagnostic> _diagnostics; public FixAllPredefinedDiagnosticProvider(ImmutableArray<Diagnostic> diagnostics) => _diagnostics = diagnostics; public override Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken) => Task.FromResult<IEnumerable<Diagnostic>>(_diagnostics); public override Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken) => Task.FromResult<IEnumerable<Diagnostic>>(_diagnostics); public override Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken) => SpecializedTasks.EmptyEnumerable<Diagnostic>(); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Features/Core/Portable/Intents/IIntentProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Features.Intents { internal interface IIntentProvider { Task<ImmutableArray<IntentProcessorResult>> ComputeIntentAsync( Document priorDocument, TextSpan priorSelection, Document currentDocument, string? serializedIntentData, 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.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Features.Intents { internal interface IIntentProvider { Task<ImmutableArray<IntentProcessorResult>> ComputeIntentAsync( Document priorDocument, TextSpan priorSelection, Document currentDocument, string? serializedIntentData, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForAccessorsAnalyzerTests.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.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { using VerifyCS = CSharpCodeFixVerifier< UseExpressionBodyDiagnosticAnalyzer, UseExpressionBodyCodeFixProvider>; public class UseExpressionBodyForAccessorsTests { private static async Task TestWithUseExpressionBody(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } private static async Task TestWithUseExpressionBodyIncludingPropertiesAndIndexers(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible }, } }.RunAsync(); } private static async Task TestWithUseBlockBodyIncludingPropertiesAndIndexers(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody1() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get { return Bar(); }|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUpdatePropertyInsteadOfAccessor() { // TODO: Should this test move to properties tests? var code = @" class C { int Bar() { return 0; } {|IDE0025:int Goo { get { return Bar(); } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo => Bar(); }"; await TestWithUseExpressionBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnIndexer1() { var code = @" class C { int Bar() { return 0; } int this[int i] { {|IDE0027:get { return Bar(); }|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int this[int i] { get => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUpdateIndexerIfIndexerAndAccessorCanBeUpdated() { // TODO: Should this test move to indexers tests? var code = @" class C { int Bar() { return 0; } {|IDE0026:int this[int i] { get { return Bar(); } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int this[int i] => Bar(); }"; await TestWithUseExpressionBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnSetter1() { var code = @" class C { void Bar() { } int Goo { {|IDE0027:set { Bar(); }|} } }"; var fixedCode = @" class C { void Bar() { } int Goo { set => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnInit1() { var code = @"class C { int Goo { {|IDE0027:init { Bar(); }|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { init => Bar(); } int Bar() { return 0; } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp9); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithOnlySetter() { await VerifyCS.VerifyAnalyzerAsync(@" class C { void Bar() { } int Goo { set => Bar(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithOnlyInit() { var code = @"class C { int Goo { init => Bar(); } int Bar() { return 0; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = code, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody3() { var code = @" using System; class C { int Goo { {|IDE0027:get { throw new NotImplementedException(); }|} } }"; var fixedCode = @" using System; class C { int Goo { get => throw new NotImplementedException(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody4() { var code = @" using System; class C { int Goo { {|IDE0027:get { throw new NotImplementedException(); // comment }|} } }"; var fixedCode = @" using System; class C { int Goo { get => throw new NotImplementedException(); // comment } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody1() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyForSetter1() { var code = @" class C { void Bar() { } int Goo { {|IDE0027:set => Bar();|} } }"; var fixedCode = @" class C { void Bar() { } int Goo { set { Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyForInit1() { var code = @"class C { int Goo { {|IDE0027:init => Bar();|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { init { Bar(); } } int Bar() { return 0; } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode, LanguageVersion.CSharp9); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody3() { var code = @" using System; class C { int Goo { {|IDE0027:get => throw new NotImplementedException();|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody4() { var code = @" using System; class C { int Goo { {|IDE0027:get => throw new NotImplementedException();|} // comment } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); // comment } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [WorkItem(31308, "https://github.com/dotnet/roslyn/issues/31308")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody5() { var code = @" class C { C this[int index] { get => default; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, } }.RunAsync(); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting_FixAll() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} {|IDE0027:set => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } set { Bar(); } } }"; var batchFixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } set { Bar(); } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, BatchFixedCode = batchFixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, }, }.RunAsync(); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting_FixAll2() { var code = @"class C { int Goo { {|IDE0027:get => Bar();|} {|IDE0027:init => Bar();|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { get { return Bar(); } init { Bar(); } } int Bar() { return 0; } }"; var batchFixedCode = @"class C { int Goo { get { return Bar(); } init { Bar(); } } int Bar() { return 0; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = code, FixedCode = fixedCode, BatchFixedCode = batchFixedCode, LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7() { var code = @" using System; class C { int Goo { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7_FixAll() { var code = @" using System; class C { int Goo { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } int Bar { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } int Bar { get { throw new NotImplementedException(); } } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } } }
// Licensed to the .NET Foundation under one or more 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.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { using VerifyCS = CSharpCodeFixVerifier< UseExpressionBodyDiagnosticAnalyzer, UseExpressionBodyCodeFixProvider>; public class UseExpressionBodyForAccessorsTests { private static async Task TestWithUseExpressionBody(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } private static async Task TestWithUseExpressionBodyIncludingPropertiesAndIndexers(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible }, } }.RunAsync(); } private static async Task TestWithUseBlockBodyIncludingPropertiesAndIndexers(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody1() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get { return Bar(); }|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUpdatePropertyInsteadOfAccessor() { // TODO: Should this test move to properties tests? var code = @" class C { int Bar() { return 0; } {|IDE0025:int Goo { get { return Bar(); } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo => Bar(); }"; await TestWithUseExpressionBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnIndexer1() { var code = @" class C { int Bar() { return 0; } int this[int i] { {|IDE0027:get { return Bar(); }|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int this[int i] { get => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUpdateIndexerIfIndexerAndAccessorCanBeUpdated() { // TODO: Should this test move to indexers tests? var code = @" class C { int Bar() { return 0; } {|IDE0026:int this[int i] { get { return Bar(); } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int this[int i] => Bar(); }"; await TestWithUseExpressionBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnSetter1() { var code = @" class C { void Bar() { } int Goo { {|IDE0027:set { Bar(); }|} } }"; var fixedCode = @" class C { void Bar() { } int Goo { set => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnInit1() { var code = @"class C { int Goo { {|IDE0027:init { Bar(); }|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { init => Bar(); } int Bar() { return 0; } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp9); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithOnlySetter() { await VerifyCS.VerifyAnalyzerAsync(@" class C { void Bar() { } int Goo { set => Bar(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithOnlyInit() { var code = @"class C { int Goo { init => Bar(); } int Bar() { return 0; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = code, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody3() { var code = @" using System; class C { int Goo { {|IDE0027:get { throw new NotImplementedException(); }|} } }"; var fixedCode = @" using System; class C { int Goo { get => throw new NotImplementedException(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody4() { var code = @" using System; class C { int Goo { {|IDE0027:get { throw new NotImplementedException(); // comment }|} } }"; var fixedCode = @" using System; class C { int Goo { get => throw new NotImplementedException(); // comment } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody1() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyForSetter1() { var code = @" class C { void Bar() { } int Goo { {|IDE0027:set => Bar();|} } }"; var fixedCode = @" class C { void Bar() { } int Goo { set { Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyForInit1() { var code = @"class C { int Goo { {|IDE0027:init => Bar();|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { init { Bar(); } } int Bar() { return 0; } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode, LanguageVersion.CSharp9); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody3() { var code = @" using System; class C { int Goo { {|IDE0027:get => throw new NotImplementedException();|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody4() { var code = @" using System; class C { int Goo { {|IDE0027:get => throw new NotImplementedException();|} // comment } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); // comment } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [WorkItem(31308, "https://github.com/dotnet/roslyn/issues/31308")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody5() { var code = @" class C { C this[int index] { get => default; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, } }.RunAsync(); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting_FixAll() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} {|IDE0027:set => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } set { Bar(); } } }"; var batchFixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } set { Bar(); } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, BatchFixedCode = batchFixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, }, }.RunAsync(); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting_FixAll2() { var code = @"class C { int Goo { {|IDE0027:get => Bar();|} {|IDE0027:init => Bar();|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { get { return Bar(); } init { Bar(); } } int Bar() { return 0; } }"; var batchFixedCode = @"class C { int Goo { get { return Bar(); } init { Bar(); } } int Bar() { return 0; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = code, FixedCode = fixedCode, BatchFixedCode = batchFixedCode, LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7() { var code = @" using System; class C { int Goo { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7_FixAll() { var code = @" using System; class C { int Goo { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } int Bar { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } int Bar { get { throw new NotImplementedException(); } } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Workspaces/Core/Portable/Shared/Extensions/IPropertySymbolExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class IPropertySymbolExtensions { public static IPropertySymbol RenameParameters(this IPropertySymbol property, ImmutableArray<string> parameterNames) { var parameterList = property.Parameters; if (parameterList.Select(p => p.Name).SequenceEqual(parameterNames)) { return property; } var parameters = parameterList.RenameParameters(parameterNames); return CodeGenerationSymbolFactory.CreatePropertySymbol( property.ContainingType, property.GetAttributes(), property.DeclaredAccessibility, property.GetSymbolModifiers(), property.Type, property.RefKind, property.ExplicitInterfaceImplementations, property.Name, parameters, property.GetMethod, property.SetMethod, property.IsIndexer); } public static IPropertySymbol RemoveInaccessibleAttributesAndAttributesOfTypes( this IPropertySymbol property, ISymbol accessibleWithin, params INamedTypeSymbol[] attributesToRemove) { var someParameterHasAttribute = property.Parameters .Any(p => p.GetAttributes().Any(shouldRemoveAttribute)); if (!someParameterHasAttribute) { return property; } return CodeGenerationSymbolFactory.CreatePropertySymbol( property.ContainingType, property.GetAttributes(), property.DeclaredAccessibility, property.GetSymbolModifiers(), property.Type, property.RefKind, property.ExplicitInterfaceImplementations, property.Name, property.Parameters.SelectAsArray(p => CodeGenerationSymbolFactory.CreateParameterSymbol( p.GetAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)), p.RefKind, p.IsParams, p.Type, p.Name, p.IsOptional, p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)), property.GetMethod, property.SetMethod, property.IsIndexer); bool shouldRemoveAttribute(AttributeData a) => attributesToRemove.Any(attr => attr.Equals(a.AttributeClass)) || a.AttributeClass?.IsAccessibleWithin(accessibleWithin) == false; } public static bool IsWritableInConstructor(this IPropertySymbol property) => (property.SetMethod != null || ContainsBackingField(property)); public static IFieldSymbol? GetBackingFieldIfAny(this IPropertySymbol property) => property.ContainingType.GetMembers() .OfType<IFieldSymbol>() .FirstOrDefault(f => property.Equals(f.AssociatedSymbol)); private static bool ContainsBackingField(IPropertySymbol property) => property.GetBackingFieldIfAny() != null; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class IPropertySymbolExtensions { public static IPropertySymbol RenameParameters(this IPropertySymbol property, ImmutableArray<string> parameterNames) { var parameterList = property.Parameters; if (parameterList.Select(p => p.Name).SequenceEqual(parameterNames)) { return property; } var parameters = parameterList.RenameParameters(parameterNames); return CodeGenerationSymbolFactory.CreatePropertySymbol( property.ContainingType, property.GetAttributes(), property.DeclaredAccessibility, property.GetSymbolModifiers(), property.Type, property.RefKind, property.ExplicitInterfaceImplementations, property.Name, parameters, property.GetMethod, property.SetMethod, property.IsIndexer); } public static IPropertySymbol RemoveInaccessibleAttributesAndAttributesOfTypes( this IPropertySymbol property, ISymbol accessibleWithin, params INamedTypeSymbol[] attributesToRemove) { var someParameterHasAttribute = property.Parameters .Any(p => p.GetAttributes().Any(shouldRemoveAttribute)); if (!someParameterHasAttribute) { return property; } return CodeGenerationSymbolFactory.CreatePropertySymbol( property.ContainingType, property.GetAttributes(), property.DeclaredAccessibility, property.GetSymbolModifiers(), property.Type, property.RefKind, property.ExplicitInterfaceImplementations, property.Name, property.Parameters.SelectAsArray(p => CodeGenerationSymbolFactory.CreateParameterSymbol( p.GetAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)), p.RefKind, p.IsParams, p.Type, p.Name, p.IsOptional, p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)), property.GetMethod, property.SetMethod, property.IsIndexer); bool shouldRemoveAttribute(AttributeData a) => attributesToRemove.Any(attr => attr.Equals(a.AttributeClass)) || a.AttributeClass?.IsAccessibleWithin(accessibleWithin) == false; } public static bool IsWritableInConstructor(this IPropertySymbol property) => (property.SetMethod != null || ContainsBackingField(property)); public static IFieldSymbol? GetBackingFieldIfAny(this IPropertySymbol property) => property.ContainingType.GetMembers() .OfType<IFieldSymbol>() .FirstOrDefault(f => property.Equals(f.AssociatedSymbol)); private static bool ContainsBackingField(IPropertySymbol property) => property.GetBackingFieldIfAny() != null; } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/Core/Portable/PEWriter/IFileReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Reflection; namespace Microsoft.Cci { /// <summary> /// Represents a file referenced by an assembly. /// </summary> internal interface IFileReference { /// <summary> /// True if the file has metadata. /// </summary> bool HasMetadata { get; } /// <summary> /// File name with extension. /// </summary> string? FileName { get; } /// <summary> /// A hash of the file contents. /// </summary> ImmutableArray<byte> GetHashValue(AssemblyHashAlgorithm algorithmId); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Reflection; namespace Microsoft.Cci { /// <summary> /// Represents a file referenced by an assembly. /// </summary> internal interface IFileReference { /// <summary> /// True if the file has metadata. /// </summary> bool HasMetadata { get; } /// <summary> /// File name with extension. /// </summary> string? FileName { get; } /// <summary> /// A hash of the file contents. /// </summary> ImmutableArray<byte> GetHashValue(AssemblyHashAlgorithm algorithmId); } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a set of projects and their source code documents. /// /// this is a green node of Solution like ProjectState/DocumentState are for /// Project and Document. /// </summary> internal partial class SolutionState { // branch id for this solution private readonly BranchId _branchId; // the version of the workspace this solution is from private readonly int _workspaceVersion; private readonly SolutionInfo.SolutionAttributes _solutionAttributes; private readonly SolutionServices _solutionServices; private readonly ImmutableDictionary<ProjectId, ProjectState> _projectIdToProjectStateMap; private readonly ImmutableHashSet<string> _remoteSupportedLanguages; private readonly ImmutableDictionary<string, ImmutableArray<DocumentId>> _filePathToDocumentIdsMap; private readonly ProjectDependencyGraph _dependencyGraph; public readonly IReadOnlyList<AnalyzerReference> AnalyzerReferences; // Values for all these are created on demand. private ImmutableDictionary<ProjectId, ICompilationTracker> _projectIdToTrackerMap; // Checksums for this solution state private readonly ValueSource<SolutionStateChecksums> _lazyChecksums; /// <summary> /// Mapping from project-id to the options and checksums needed to synchronize it (and the projects it depends on) over /// to an OOP host. Options are stored as well so that when we are attempting to match a request for a particular project-subset /// we can return the options specific to that project-subset (which may be different from the <see cref="Options"/> defined /// for the entire solution). Lock this specific field before reading/writing to it. /// </summary> private readonly Dictionary<ProjectId, (SerializableOptionSet options, ValueSource<SolutionStateChecksums> checksums)> _lazyProjectChecksums = new(); // holds on data calculated based on the AnalyzerReferences list private readonly Lazy<HostDiagnosticAnalyzers> _lazyAnalyzers; /// <summary> /// Cache we use to map between unrooted symbols (i.e. assembly, module and dynamic symbols) and the project /// they came from. That way if we are asked about many symbols from the same assembly/module we can answer the /// question quickly after computing for the first one. Created on demand. /// </summary> private ConditionalWeakTable<ISymbol, ProjectId?>? _unrootedSymbolToProjectId; private static readonly Func<ConditionalWeakTable<ISymbol, ProjectId?>> s_createTable = () => new ConditionalWeakTable<ISymbol, ProjectId?>(); private readonly SourceGeneratedDocumentState? _frozenSourceGeneratedDocumentState; private SolutionState( BranchId branchId, int workspaceVersion, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, IReadOnlyList<ProjectId> projectIds, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences, ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap, ImmutableHashSet<string> remoteSupportedLanguages, ImmutableDictionary<ProjectId, ICompilationTracker> projectIdToTrackerMap, ImmutableDictionary<string, ImmutableArray<DocumentId>> filePathToDocumentIdsMap, ProjectDependencyGraph dependencyGraph, Lazy<HostDiagnosticAnalyzers>? lazyAnalyzers, SourceGeneratedDocumentState? frozenSourceGeneratedDocument) { _branchId = branchId; _workspaceVersion = workspaceVersion; _solutionAttributes = solutionAttributes; _solutionServices = solutionServices; ProjectIds = projectIds; Options = options; AnalyzerReferences = analyzerReferences; _projectIdToProjectStateMap = idToProjectStateMap; _remoteSupportedLanguages = remoteSupportedLanguages; _projectIdToTrackerMap = projectIdToTrackerMap; _filePathToDocumentIdsMap = filePathToDocumentIdsMap; _dependencyGraph = dependencyGraph; _lazyAnalyzers = lazyAnalyzers ?? CreateLazyHostDiagnosticAnalyzers(analyzerReferences); _frozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument; // when solution state is changed, we recalculate its checksum _lazyChecksums = new AsyncLazy<SolutionStateChecksums>( c => ComputeChecksumsAsync(projectsToInclude: null, Options, c), cacheResult: true); CheckInvariants(); // make sure we don't accidentally capture any state but the list of references: static Lazy<HostDiagnosticAnalyzers> CreateLazyHostDiagnosticAnalyzers(IReadOnlyList<AnalyzerReference> analyzerReferences) => new(() => new HostDiagnosticAnalyzers(analyzerReferences)); } public SolutionState( BranchId primaryBranchId, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences) : this( primaryBranchId, workspaceVersion: 0, solutionServices, solutionAttributes, projectIds: SpecializedCollections.EmptyBoxedImmutableArray<ProjectId>(), options, analyzerReferences, idToProjectStateMap: ImmutableDictionary<ProjectId, ProjectState>.Empty, remoteSupportedLanguages: ImmutableHashSet<string>.Empty, projectIdToTrackerMap: ImmutableDictionary<ProjectId, ICompilationTracker>.Empty, filePathToDocumentIdsMap: ImmutableDictionary.Create<string, ImmutableArray<DocumentId>>(StringComparer.OrdinalIgnoreCase), dependencyGraph: ProjectDependencyGraph.Empty, lazyAnalyzers: null, frozenSourceGeneratedDocument: null) { } public SolutionState WithNewWorkspace(Workspace workspace, int workspaceVersion) { var services = workspace != _solutionServices.Workspace ? new SolutionServices(workspace) : _solutionServices; // Note: this will potentially have problems if the workspace services are different, as some services // get locked-in by document states and project states when first constructed. return CreatePrimarySolution(branchId: workspace.PrimaryBranchId, workspaceVersion: workspaceVersion, services: services); } public HostDiagnosticAnalyzers Analyzers => _lazyAnalyzers.Value; public SolutionInfo.SolutionAttributes SolutionAttributes => _solutionAttributes; public SourceGeneratedDocumentState? FrozenSourceGeneratedDocumentState => _frozenSourceGeneratedDocumentState; public ImmutableDictionary<ProjectId, ProjectState> ProjectStates => _projectIdToProjectStateMap; public int WorkspaceVersion => _workspaceVersion; public SolutionServices Services => _solutionServices; public SerializableOptionSet Options { get; } /// <summary> /// branch id of this solution /// /// currently, it only supports one level of branching. there is a primary branch of a workspace and all other /// branches that are branched from the primary branch. /// /// one still can create multiple forked solutions from an already branched solution, but versions among those /// can't be reliably used and compared. /// /// version only has a meaning between primary solution and branched one or between solutions from same branch. /// </summary> public BranchId BranchId => _branchId; /// <summary> /// The Workspace this solution is associated with. /// </summary> public Workspace Workspace => _solutionServices.Workspace; /// <summary> /// The Id of the solution. Multiple solution instances may share the same Id. /// </summary> public SolutionId Id => _solutionAttributes.Id; /// <summary> /// The path to the solution file or null if there is no solution file. /// </summary> public string? FilePath => _solutionAttributes.FilePath; /// <summary> /// The solution version. This equates to the solution file's version. /// </summary> public VersionStamp Version => _solutionAttributes.Version; /// <summary> /// A list of all the ids for all the projects contained by the solution. /// </summary> public IReadOnlyList<ProjectId> ProjectIds { get; } // Only run this in debug builds; even the .Any() call across all projects can be expensive when there's a lot of them. [Conditional("DEBUG")] private void CheckInvariants() { Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == ProjectIds.Count); Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == _dependencyGraph.ProjectIds.Count); // An id shouldn't point at a tracker for a different project. Contract.ThrowIfTrue(_projectIdToTrackerMap.Any(kvp => kvp.Key != kvp.Value.ProjectState.Id)); // project ids must be the same: Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(ProjectIds)); Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(_dependencyGraph.ProjectIds)); Debug.Assert(_remoteSupportedLanguages.SetEquals(GetRemoteSupportedProjectLanguages(_projectIdToProjectStateMap))); } private SolutionState Branch( SolutionInfo.SolutionAttributes? solutionAttributes = null, IReadOnlyList<ProjectId>? projectIds = null, SerializableOptionSet? options = null, IReadOnlyList<AnalyzerReference>? analyzerReferences = null, ImmutableDictionary<ProjectId, ProjectState>? idToProjectStateMap = null, ImmutableHashSet<string>? remoteSupportedProjectLanguages = null, ImmutableDictionary<ProjectId, ICompilationTracker>? projectIdToTrackerMap = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? filePathToDocumentIdsMap = null, ProjectDependencyGraph? dependencyGraph = null, Optional<SourceGeneratedDocumentState?> frozenSourceGeneratedDocument = default) { var branchId = GetBranchId(); if (idToProjectStateMap is not null) { Contract.ThrowIfNull(remoteSupportedProjectLanguages); } solutionAttributes ??= _solutionAttributes; projectIds ??= ProjectIds; idToProjectStateMap ??= _projectIdToProjectStateMap; remoteSupportedProjectLanguages ??= _remoteSupportedLanguages; Debug.Assert(remoteSupportedProjectLanguages.SetEquals(GetRemoteSupportedProjectLanguages(idToProjectStateMap))); options ??= Options.WithLanguages(remoteSupportedProjectLanguages); analyzerReferences ??= AnalyzerReferences; projectIdToTrackerMap ??= _projectIdToTrackerMap; filePathToDocumentIdsMap ??= _filePathToDocumentIdsMap; dependencyGraph ??= _dependencyGraph; var newFrozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument.HasValue ? frozenSourceGeneratedDocument.Value : _frozenSourceGeneratedDocumentState; var analyzerReferencesEqual = AnalyzerReferences.SequenceEqual(analyzerReferences); if (branchId == _branchId && solutionAttributes == _solutionAttributes && projectIds == ProjectIds && options == Options && analyzerReferencesEqual && idToProjectStateMap == _projectIdToProjectStateMap && projectIdToTrackerMap == _projectIdToTrackerMap && filePathToDocumentIdsMap == _filePathToDocumentIdsMap && dependencyGraph == _dependencyGraph && newFrozenSourceGeneratedDocumentState == _frozenSourceGeneratedDocumentState) { return this; } return new SolutionState( branchId, _workspaceVersion, _solutionServices, solutionAttributes, projectIds, options, analyzerReferences, idToProjectStateMap, remoteSupportedProjectLanguages, projectIdToTrackerMap, filePathToDocumentIdsMap, dependencyGraph, analyzerReferencesEqual ? _lazyAnalyzers : null, newFrozenSourceGeneratedDocumentState); } private SolutionState CreatePrimarySolution( BranchId branchId, int workspaceVersion, SolutionServices services) { if (branchId == _branchId && workspaceVersion == _workspaceVersion && services == _solutionServices) { return this; } return new SolutionState( branchId, workspaceVersion, services, _solutionAttributes, ProjectIds, Options, AnalyzerReferences, _projectIdToProjectStateMap, _remoteSupportedLanguages, _projectIdToTrackerMap, _filePathToDocumentIdsMap, _dependencyGraph, _lazyAnalyzers, frozenSourceGeneratedDocument: null); } private BranchId GetBranchId() { // currently we only support one level branching. // my reasonings are // 1. it seems there is no-one who needs sub branches. // 2. this lets us to branch without explicit branch API return _branchId == Workspace.PrimaryBranchId ? BranchId.GetNextId() : _branchId; } /// <summary> /// The version of the most recently modified project. /// </summary> public VersionStamp GetLatestProjectVersion() { // this may produce a version that is out of sync with the actual Document versions. var latestVersion = VersionStamp.Default; foreach (var project in this.ProjectStates.Values) { latestVersion = project.Version.GetNewerVersion(latestVersion); } return latestVersion; } /// <summary> /// True if the solution contains a project with the specified project ID. /// </summary> public bool ContainsProject([NotNullWhen(returnValue: true)] ProjectId? projectId) => projectId != null && _projectIdToProjectStateMap.ContainsKey(projectId); /// <summary> /// True if the solution contains the document in one of its projects /// </summary> public bool ContainsDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.DocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the additional document in one of its projects /// </summary> public bool ContainsAdditionalDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AdditionalDocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the analyzer config document in one of its projects /// </summary> public bool ContainsAnalyzerConfigDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AnalyzerConfigDocumentStates.Contains(documentId); } private DocumentState GetRequiredDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).DocumentStates.GetRequiredState(documentId); private AdditionalDocumentState GetRequiredAdditionalDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AdditionalDocumentStates.GetRequiredState(documentId); private AnalyzerConfigDocumentState GetRequiredAnalyzerConfigDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AnalyzerConfigDocumentStates.GetRequiredState(documentId); internal DocumentState? GetDocumentState(SyntaxTree? syntaxTree, ProjectId? projectId) { if (syntaxTree != null) { // is this tree known to be associated with a document? var documentId = DocumentState.GetDocumentIdForTree(syntaxTree); if (documentId != null && (projectId == null || documentId.ProjectId == projectId)) { // does this solution even have the document? var projectState = GetProjectState(documentId.ProjectId); if (projectState != null) { var document = projectState.DocumentStates.GetState(documentId); if (document != null) { // does this document really have the syntax tree? if (document.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return document; } } else { var generatedDocument = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); if (generatedDocument != null) { // does this document really have the syntax tree? if (generatedDocument.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return generatedDocument; } } } } } } return null; } public Task<VersionStamp> GetDependentVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentVersionAsync(this, cancellationToken); public Task<VersionStamp> GetDependentSemanticVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentSemanticVersionAsync(this, cancellationToken); public ProjectState? GetProjectState(ProjectId projectId) { _projectIdToProjectStateMap.TryGetValue(projectId, out var state); return state; } public ProjectState GetRequiredProjectState(ProjectId projectId) { var result = GetProjectState(projectId); Contract.ThrowIfNull(result); return result; } /// <summary> /// Gets the <see cref="Project"/> associated with an assembly symbol. /// </summary> public ProjectState? GetProjectState(IAssemblySymbol? assemblySymbol) { if (assemblySymbol == null) return null; s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblySymbol, out var id); return id == null ? null : this.GetProjectState(id); } private bool TryGetCompilationTracker(ProjectId projectId, [NotNullWhen(returnValue: true)] out ICompilationTracker? tracker) => _projectIdToTrackerMap.TryGetValue(projectId, out tracker); private static readonly Func<ProjectId, SolutionState, CompilationTracker> s_createCompilationTrackerFunction = CreateCompilationTracker; private static CompilationTracker CreateCompilationTracker(ProjectId projectId, SolutionState solution) { var projectState = solution.GetProjectState(projectId); Contract.ThrowIfNull(projectState); return new CompilationTracker(projectState); } private ICompilationTracker GetCompilationTracker(ProjectId projectId) { if (!_projectIdToTrackerMap.TryGetValue(projectId, out var tracker)) { tracker = ImmutableInterlocked.GetOrAdd(ref _projectIdToTrackerMap, projectId, s_createCompilationTrackerFunction, this); } return tracker; } private SolutionState AddProject(ProjectId projectId, ProjectState projectState) { // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Add(projectId); var newStateMap = _projectIdToProjectStateMap.Add(projectId, projectState); var newLanguages = RemoteSupportedLanguages.IsSupported(projectState.Language) ? _remoteSupportedLanguages.Add(projectState.Language) : _remoteSupportedLanguages; var newDependencyGraph = _dependencyGraph .WithAdditionalProject(projectId) .WithAdditionalProjectReferences(projectId, projectState.ProjectReferences); // It's possible that another project already in newStateMap has a reference to this project that we're adding, since we allow // dangling references like that. If so, we'll need to link those in too. foreach (var newState in newStateMap) { foreach (var projectReference in newState.Value.ProjectReferences) { if (projectReference.ProjectId == projectId) { newDependencyGraph = newDependencyGraph.WithAdditionalProjectReferences( newState.Key, SpecializedCollections.SingletonReadOnlyList(projectReference)); break; } } } var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithAddedDocuments(GetDocumentStates(newStateMap[projectId])); return Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance that includes a project with the specified project information. /// </summary> public SolutionState AddProject(ProjectInfo projectInfo) { if (projectInfo == null) { throw new ArgumentNullException(nameof(projectInfo)); } var projectId = projectInfo.Id; var language = projectInfo.Language; if (language == null) { throw new ArgumentNullException(nameof(language)); } var displayName = projectInfo.Name; if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } CheckNotContainsProject(projectId); var languageServices = this.Workspace.Services.GetLanguageServices(language); if (languageServices == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_language_0_is_not_supported, language)); } var newProject = new ProjectState(projectInfo, languageServices, _solutionServices); return this.AddProject(newProject.Id, newProject); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithAddedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } builder.MultiAdd(filePath, documentState.Id); } return builder.ToImmutable(); } private static IEnumerable<TextDocumentState> GetDocumentStates(ProjectState projectState) => projectState.DocumentStates.States.Values .Concat<TextDocumentState>(projectState.AdditionalDocumentStates.States.Values) .Concat(projectState.AnalyzerConfigDocumentStates.States.Values); /// <summary> /// Create a new solution instance without the project specified. /// </summary> public SolutionState RemoveProject(ProjectId projectId) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } CheckContainsProject(projectId); // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: this.Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Remove(projectId); var newStateMap = _projectIdToProjectStateMap.Remove(projectId); // Remote supported languages only changes if the removed project is the last project of a supported language. var newLanguages = _remoteSupportedLanguages; if (_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) && RemoteSupportedLanguages.IsSupported(projectState.Language)) { var stillSupportsLanguage = false; foreach (var (id, state) in _projectIdToProjectStateMap) { if (id == projectId) continue; if (state.Language == projectState.Language) { stillSupportsLanguage = true; break; } } if (!stillSupportsLanguage) { newLanguages = newLanguages.Remove(projectState.Language); } } var newDependencyGraph = _dependencyGraph.WithProjectRemoved(projectId); var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithRemovedDocuments(GetDocumentStates(_projectIdToProjectStateMap[projectId])); return this.Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap.Remove(projectId), filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithRemovedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } if (!builder.TryGetValue(filePath, out var documentIdsWithPath) || !documentIdsWithPath.Contains(documentState.Id)) { throw new ArgumentException($"The given documentId was not found in '{nameof(_filePathToDocumentIdsMap)}'."); } builder.MultiRemove(filePath, documentState.Id); } return builder.ToImmutable(); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithFilePath(DocumentId documentId, string? oldFilePath, string? newFilePath) { if (oldFilePath == newFilePath) { return _filePathToDocumentIdsMap; } var builder = _filePathToDocumentIdsMap.ToBuilder(); if (!RoslynString.IsNullOrEmpty(oldFilePath)) { builder.MultiRemove(oldFilePath, documentId); } if (!RoslynString.IsNullOrEmpty(newFilePath)) { builder.MultiAdd(newFilePath, documentId); } return builder.ToImmutable(); } /// <summary> /// Creates a new solution instance with the project specified updated to have the new /// assembly name. /// </summary> public SolutionState WithProjectAssemblyName(ProjectId projectId, string assemblyName) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAssemblyName(assemblyName); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectAssemblyNameAction(assemblyName)); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputFilePath(ProjectId projectId, string? outputFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputFilePath(outputFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputRefFilePath(ProjectId projectId, string? outputRefFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputRefFilePath(outputRefFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the compiler output file path. /// </summary> public SolutionState WithProjectCompilationOutputInfo(ProjectId projectId, in CompilationOutputInfo info) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOutputInfo(info); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the default namespace. /// </summary> public SolutionState WithProjectDefaultNamespace(ProjectId projectId, string? defaultNamespace) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithDefaultNamespace(defaultNamespace); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the name. /// </summary> public SolutionState WithProjectName(ProjectId projectId, string name) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithName(name); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the project file path. /// </summary> public SolutionState WithProjectFilePath(ProjectId projectId, string? filePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithFilePath(filePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified compilation options. /// </summary> public SolutionState WithProjectCompilationOptions(ProjectId projectId, CompilationOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOptions(options); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified parse options. /// </summary> public SolutionState WithProjectParseOptions(ProjectId projectId, ParseOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithParseOptions(options); if (oldProject == newProject) { return this; } if (Workspace.PartialSemanticsEnabled) { // don't fork tracker with queued action since access via partial semantics can become inconsistent (throw). // Since changing options is rare event, it is okay to start compilation building from scratch. return ForkProject(newProject, forkTracker: false); } else { return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: true)); } } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified hasAllInformation. /// </summary> public SolutionState WithHasAllInformation(ProjectId projectId, bool hasAllInformation) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithHasAllInformation(hasAllInformation); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified runAnalyzers. /// </summary> public SolutionState WithRunAnalyzers(ProjectId projectId, bool runAnalyzers) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithRunAnalyzers(runAnalyzers); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include /// the specified project references. /// </summary> public SolutionState AddProjectReferences(ProjectId projectId, IReadOnlyCollection<ProjectReference> projectReferences) { if (projectReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(projectReferences); var newProject = oldProject.WithProjectReferences(newReferences); var newDependencyGraph = _dependencyGraph.WithAdditionalProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to no longer /// include the specified project reference. /// </summary> public SolutionState RemoveProjectReference(ProjectId projectId, ProjectReference projectReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); // Note: uses ProjectReference equality to compare references. var newReferences = oldReferences.Remove(projectReference); if (oldReferences == newReferences) { return this; } var newProject = oldProject.WithProjectReferences(newReferences); ProjectDependencyGraph newDependencyGraph; if (newProject.ContainsReferenceToProject(projectReference.ProjectId) || !_projectIdToProjectStateMap.ContainsKey(projectReference.ProjectId)) { // Two cases: // 1) The project contained multiple non-equivalent references to the project, // and not all of them were removed. The dependency graph doesn't change. // Note that there might be two references to the same project, one with // extern alias and the other without. These are not considered duplicates. // 2) The referenced project is not part of the solution and hence not included // in the dependency graph. newDependencyGraph = _dependencyGraph; } else { newDependencyGraph = _dependencyGraph.WithProjectReferenceRemoved(projectId, projectReference.ProjectId); } return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to contain /// the specified list of project references. /// </summary> public SolutionState WithProjectReferences(ProjectId projectId, IReadOnlyList<ProjectReference> projectReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithProjectReferences(projectReferences); if (oldProject == newProject) { return this; } var newDependencyGraph = _dependencyGraph.WithProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Creates a new solution instance with the project documents in the order by the specified document ids. /// The specified document ids must be the same as what is already in the project; no adding or removing is allowed. /// </summary> public SolutionState WithProjectDocumentsOrder(ProjectId projectId, ImmutableList<DocumentId> documentIds) { var oldProject = GetRequiredProjectState(projectId); if (documentIds.Count != oldProject.DocumentStates.Count) { throw new ArgumentException($"The specified documents do not equal the project document count.", nameof(documentIds)); } foreach (var id in documentIds) { if (!oldProject.DocumentStates.Contains(id)) { throw new InvalidOperationException($"The document '{id}' does not exist in the project."); } } var newProject = oldProject.UpdateDocumentsOrder(documentIds); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified metadata references. /// </summary> public SolutionState AddMetadataReferences(ProjectId projectId, IReadOnlyCollection<MetadataReference> metadataReferences) { if (metadataReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(metadataReferences); return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified metadata reference. /// </summary> public SolutionState RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(metadataReference); if (oldReferences == newReferences) { return this; } return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified metadata references. /// </summary> public SolutionState WithProjectMetadataReferences(ProjectId projectId, IReadOnlyList<MetadataReference> metadataReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithMetadataReferences(metadataReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified analyzer references. /// </summary> public SolutionState AddAnalyzerReferences(ProjectId projectId, ImmutableArray<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Length == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.AddAnalyzerReferencesAction(analyzerReferences, oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified analyzer reference. /// </summary> public SolutionState RemoveAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.RemoveAnalyzerReferencesAction(ImmutableArray.Create(analyzerReference), oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified analyzer references. /// </summary> public SolutionState WithProjectAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAnalyzerReferences(analyzerReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the corresponding projects updated to include new /// documents defined by the document info. /// </summary> public SolutionState AddDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => project.CreateDocument(documentInfo, project.ParseOptions), (oldProject, documents) => (oldProject.AddDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddDocumentsAction(documents))); } /// <summary> /// Core helper that takes a set of <see cref="DocumentInfo" />s and does the application of the appropriate documents to each project. /// </summary> /// <param name="documentInfos">The set of documents to add.</param> /// <param name="addDocumentsToProjectState">Returns the new <see cref="ProjectState"/> with the documents added, and the <see cref="CompilationAndGeneratorDriverTranslationAction"/> needed as well.</param> /// <returns></returns> private SolutionState AddDocumentsToMultipleProjects<T>( ImmutableArray<DocumentInfo> documentInfos, Func<DocumentInfo, ProjectState, T> createDocumentState, Func<ProjectState, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> addDocumentsToProjectState) where T : TextDocumentState { if (documentInfos.IsDefault) { throw new ArgumentNullException(nameof(documentInfos)); } if (documentInfos.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentInfosByProjectId = documentInfos.ToLookup(d => d.Id.ProjectId); var newSolutionState = this; foreach (var documentInfosInProject in documentInfosByProjectId) { CheckContainsProject(documentInfosInProject.Key); var oldProjectState = this.GetProjectState(documentInfosInProject.Key)!; var newDocumentStatesForProjectBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentInfo in documentInfosInProject) { newDocumentStatesForProjectBuilder.Add(createDocumentState(documentInfo, oldProjectState)); } var newDocumentStatesForProject = newDocumentStatesForProjectBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = addDocumentsToProjectState(oldProjectState, newDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithAddedDocuments(newDocumentStatesForProject)); } return newSolutionState; } public SolutionState AddAdditionalDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AdditionalDocumentState(documentInfo, _solutionServices), (projectState, documents) => (projectState.AddAdditionalDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddAdditionalDocumentsAction(documents))); } public SolutionState AddAnalyzerConfigDocuments(ImmutableArray<DocumentInfo> documentInfos) { // Adding a new analyzer config potentially modifies the compilation options return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AnalyzerConfigDocumentState(documentInfo, _solutionServices), (oldProject, documents) => { var newProject = oldProject.AddAnalyzerConfigDocuments(documents); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } public SolutionState RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AnalyzerConfigDocumentStates.GetRequiredState(documentId), (oldProject, documentIds, _) => { var newProject = oldProject.RemoveAnalyzerConfigDocuments(documentIds); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } /// <summary> /// Creates a new solution instance that no longer includes the specified document. /// </summary> public SolutionState RemoveDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.DocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveDocumentsAction(documentStates))); } private SolutionState RemoveDocumentsFromMultipleProjects<T>( ImmutableArray<DocumentId> documentIds, Func<ProjectState, DocumentId, T> getExistingTextDocumentState, Func<ProjectState, ImmutableArray<DocumentId>, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> removeDocumentsFromProjectState) where T : TextDocumentState { if (documentIds.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentIdsByProjectId = documentIds.ToLookup(id => id.ProjectId); var newSolutionState = this; foreach (var documentIdsInProject in documentIdsByProjectId) { var oldProjectState = this.GetProjectState(documentIdsInProject.Key); if (oldProjectState == null) { throw new InvalidOperationException(string.Format(WorkspacesResources._0_is_not_part_of_the_workspace, documentIdsInProject.Key)); } var removedDocumentStatesBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentId in documentIdsInProject) { removedDocumentStatesBuilder.Add(getExistingTextDocumentState(oldProjectState, documentId)); } var removedDocumentStatesForProject = removedDocumentStatesBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = removeDocumentsFromProjectState(oldProjectState, documentIdsInProject.ToImmutableArray(), removedDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithRemovedDocuments(removedDocumentStatesForProject)); } return newSolutionState; } /// <summary> /// Creates a new solution instance that no longer includes the specified additional documents. /// </summary> public SolutionState RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AdditionalDocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveAdditionalDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveAdditionalDocumentsAction(documentStates))); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified name. /// </summary> public SolutionState WithDocumentName(DocumentId documentId, string name) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Attributes.Name == name) { return this; } return UpdateDocumentState(oldDocument.UpdateName(name)); } /// <summary> /// Creates a new solution instance with the document specified updated to be contained in /// the sequence of logical folders. /// </summary> public SolutionState WithDocumentFolders(DocumentId documentId, IReadOnlyList<string> folders) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Folders.SequenceEqual(folders)) { return this; } return UpdateDocumentState(oldDocument.UpdateFolders(folders)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified file path. /// </summary> public SolutionState WithDocumentFilePath(DocumentId documentId, string? filePath) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.FilePath == filePath) { return this; } return UpdateDocumentState(oldDocument.UpdateFilePath(filePath)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(text, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(textAndVersion, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have a syntax tree /// rooted by the specified syntax node. /// </summary> public SolutionState WithDocumentSyntaxRoot(DocumentId documentId, SyntaxNode root, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetSyntaxTree(out var oldTree) && oldTree.TryGetRoot(out var oldRoot) && oldRoot == root) { return this; } return UpdateDocumentState(oldDocument.UpdateTree(root, mode), textChanged: true); } private static async Task<Compilation> UpdateDocumentInCompilationAsync( Compilation compilation, DocumentState oldDocument, DocumentState newDocument, CancellationToken cancellationToken) { return compilation.ReplaceSyntaxTree( await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false), await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the source /// code kind specified. /// </summary> public SolutionState WithDocumentSourceCodeKind(DocumentId documentId, SourceCodeKind sourceCodeKind) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.SourceCodeKind == sourceCodeKind) { return this; } return UpdateDocumentState(oldDocument.UpdateSourceCodeKind(sourceCodeKind), textChanged: true); } public SolutionState UpdateDocumentTextLoader(DocumentId documentId, TextLoader loader, SourceText? text, PreservationMode mode) { var oldDocument = GetRequiredDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateDocumentState(oldDocument.UpdateText(loader, text, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAdditionalDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAdditionalDocumentState(oldDocument.UpdateText(loader, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAnalyzerConfigDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(loader, mode)); } private SolutionState UpdateDocumentState(DocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.DocumentStates.GetRequiredState(newDocument.Id); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithFilePath(newDocument.Id, oldDocument.FilePath, newDocument.FilePath); return ForkProject( newProject, new CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction(oldDocument, newDocument), newFilePathToDocumentIdsMap: newFilePathToDocumentIdsMap); } private SolutionState UpdateAdditionalDocumentState(AdditionalDocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAdditionalDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.AdditionalDocumentStates.GetRequiredState(newDocument.Id); return ForkProject( newProject, translate: new CompilationAndGeneratorDriverTranslationAction.TouchAdditionalDocumentAction(oldDocument, newDocument)); } private SolutionState UpdateAnalyzerConfigDocumentState(AnalyzerConfigDocumentState newDocument) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAnalyzerConfigDocument(newDocument); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); return ForkProject(newProject, newProject.CompilationOptions != null ? new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true) : null); } /// <summary> /// Creates a new snapshot with an updated project and an action that will produce a new /// compilation matching the new project out of an old compilation. All dependent projects /// are fixed-up if the change to the new project affects its public metadata, and old /// dependent compilations are forgotten. /// </summary> private SolutionState ForkProject( ProjectState newProjectState, CompilationAndGeneratorDriverTranslationAction? translate = null, ProjectDependencyGraph? newDependencyGraph = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? newFilePathToDocumentIdsMap = null, bool forkTracker = true) { var projectId = newProjectState.Id; var newStateMap = _projectIdToProjectStateMap.SetItem(projectId, newProjectState); // Remote supported languages can only change if the project changes language. This is an unexpected edge // case, so it's not optimized for incremental updates. var newLanguages = !_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) || projectState.Language != newProjectState.Language ? GetRemoteSupportedProjectLanguages(newStateMap) : _remoteSupportedLanguages; newDependencyGraph ??= _dependencyGraph; var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); // If we have a tracker for this project, then fork it as well (along with the // translation action and store it in the tracker map. if (newTrackerMap.TryGetValue(projectId, out var tracker)) { newTrackerMap = newTrackerMap.Remove(projectId); if (forkTracker) { newTrackerMap = newTrackerMap.Add(projectId, tracker.Fork(newProjectState, translate)); } } return this.Branch( idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, dependencyGraph: newDependencyGraph, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap ?? _filePathToDocumentIdsMap); } /// <summary> /// Gets the set of <see cref="DocumentId"/>s in this <see cref="Solution"/> with a /// <see cref="TextDocument.FilePath"/> that matches the given file path. /// </summary> public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string? filePath) { if (string.IsNullOrEmpty(filePath)) { return ImmutableArray<DocumentId>.Empty; } return _filePathToDocumentIdsMap.TryGetValue(filePath!, out var documentIds) ? documentIds : ImmutableArray<DocumentId>.Empty; } private static ProjectDependencyGraph CreateDependencyGraph( IReadOnlyList<ProjectId> projectIds, ImmutableDictionary<ProjectId, ProjectState> projectStates) { var map = projectStates.Values.Select(state => new KeyValuePair<ProjectId, ImmutableHashSet<ProjectId>>( state.Id, state.ProjectReferences.Where(pr => projectStates.ContainsKey(pr.ProjectId)).Select(pr => pr.ProjectId).ToImmutableHashSet())) .ToImmutableDictionary(); return new ProjectDependencyGraph(projectIds.ToImmutableHashSet(), map); } private ImmutableDictionary<ProjectId, ICompilationTracker> CreateCompilationTrackerMap(ProjectId changedProjectId, ProjectDependencyGraph dependencyGraph) { var builder = ImmutableDictionary.CreateBuilder<ProjectId, ICompilationTracker>(); IEnumerable<ProjectId>? dependencies = null; foreach (var (id, tracker) in _projectIdToTrackerMap) { if (!tracker.HasCompilation) { continue; } builder.Add(id, CanReuse(id) ? tracker : tracker.Fork(tracker.ProjectState)); } return builder.ToImmutable(); // Returns true if 'tracker' can be reused for project 'id' bool CanReuse(ProjectId id) { if (id == changedProjectId) { return true; } // Check the dependency graph to see if project 'id' directly or transitively depends on 'projectId'. // If the information is not available, do not compute it. var forwardDependencies = dependencyGraph.TryGetProjectsThatThisProjectTransitivelyDependsOn(id); if (forwardDependencies is object && !forwardDependencies.Contains(changedProjectId)) { return true; } // Compute the set of all projects that depend on 'projectId'. This information answers the same // question as the previous check, but involves at most one transitive computation within the // dependency graph. dependencies ??= dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(changedProjectId); return !dependencies.Contains(id); } } /// <summary> /// Gets a copy of the solution isolated from the original so that they do not share computed state. /// /// Use isolated solutions when doing operations that are likely to access a lot of text, /// syntax trees or compilations that are unlikely to be needed again after the operation is done. /// When the isolated solution is reclaimed so will the computed state. /// </summary> public SolutionState GetIsolatedSolution() { var forkedMap = ImmutableDictionary.CreateRange( _projectIdToTrackerMap.Where(kvp => kvp.Value.HasCompilation) .Select(kvp => KeyValuePairUtil.Create(kvp.Key, kvp.Value.Clone()))); return this.Branch(projectIdToTrackerMap: forkedMap); } public SolutionState WithOptions(SerializableOptionSet options) => Branch(options: options); public SolutionState AddAnalyzerReferences(IReadOnlyCollection<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Count == 0) { return this; } var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return Branch(analyzerReferences: newReferences); } public SolutionState RemoveAnalyzerReference(AnalyzerReference analyzerReference) { var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return Branch(analyzerReferences: newReferences); } public SolutionState WithAnalyzerReferences(IReadOnlyList<AnalyzerReference> analyzerReferences) { if (analyzerReferences == AnalyzerReferences) { return this; } return Branch(analyzerReferences: analyzerReferences); } // this lock guards all the mutable fields (do not share lock with derived classes) private NonReentrantLock? _stateLockBackingField; private NonReentrantLock StateLock { get { // TODO: why did I need to do a nullable suppression here? return LazyInitializer.EnsureInitialized(ref _stateLockBackingField, NonReentrantLock.Factory)!; } } private WeakReference<SolutionState>? _latestSolutionWithPartialCompilation; private DateTime _timeOfLatestSolutionWithPartialCompilation; private DocumentId? _documentIdOfLatestSolutionWithPartialCompilation; /// <summary> /// Creates a branch of the solution that has its compilations frozen in whatever state they are in at the time, assuming a background compiler is /// busy building this compilations. /// /// A compilation for the project containing the specified document id will be guaranteed to exist with at least the syntax tree for the document. /// /// This not intended to be the public API, use Document.WithFrozenPartialSemantics() instead. /// </summary> public SolutionState WithFrozenPartialCompilationIncludingSpecificDocument(DocumentId documentId, CancellationToken cancellationToken) { try { var doc = this.GetRequiredDocumentState(documentId); var tree = doc.GetSyntaxTree(cancellationToken); using (this.StateLock.DisposableWait(cancellationToken)) { // in progress solutions are disabled for some testing if (this.Workspace is Workspace ws && ws.TestHookPartialSolutionsDisabled) { return this; } SolutionState? currentPartialSolution = null; if (_latestSolutionWithPartialCompilation != null) { _latestSolutionWithPartialCompilation.TryGetTarget(out currentPartialSolution); } var reuseExistingPartialSolution = currentPartialSolution != null && (DateTime.UtcNow - _timeOfLatestSolutionWithPartialCompilation).TotalSeconds < 0.1 && _documentIdOfLatestSolutionWithPartialCompilation == documentId; if (reuseExistingPartialSolution) { SolutionLogger.UseExistingPartialSolution(); return currentPartialSolution!; } // if we don't have one or it is stale, create a new partial solution var tracker = this.GetCompilationTracker(documentId.ProjectId); var newTracker = tracker.FreezePartialStateWithTree(this, doc, tree, cancellationToken); var newIdToProjectStateMap = _projectIdToProjectStateMap.SetItem(documentId.ProjectId, newTracker.ProjectState); var newLanguages = _remoteSupportedLanguages; var newIdToTrackerMap = _projectIdToTrackerMap.SetItem(documentId.ProjectId, newTracker); currentPartialSolution = this.Branch( idToProjectStateMap: newIdToProjectStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newIdToTrackerMap, dependencyGraph: CreateDependencyGraph(ProjectIds, newIdToProjectStateMap)); _latestSolutionWithPartialCompilation = new WeakReference<SolutionState>(currentPartialSolution); _timeOfLatestSolutionWithPartialCompilation = DateTime.UtcNow; _documentIdOfLatestSolutionWithPartialCompilation = documentId; SolutionLogger.CreatePartialSolution(); return currentPartialSolution; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new solution instance with all the documents specified updated to have the same specified text. /// </summary> public SolutionState WithDocumentText(IEnumerable<DocumentId?> documentIds, SourceText text, PreservationMode mode) { var solution = this; foreach (var documentId in documentIds) { if (documentId == null) { continue; } var doc = GetProjectState(documentId.ProjectId)?.DocumentStates.GetState(documentId); if (doc != null) { if (!doc.TryGetText(out var existingText) || existingText != text) { solution = solution.WithDocumentText(documentId, text, mode); } } } return solution; } public bool TryGetCompilation(ProjectId projectId, [NotNullWhen(returnValue: true)] out Compilation? compilation) { CheckContainsProject(projectId); compilation = null; return this.TryGetCompilationTracker(projectId, out var tracker) && tracker.TryGetCompilation(out compilation); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectId"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> private Task<Compilation?> GetCompilationAsync(ProjectId projectId, CancellationToken cancellationToken) { // TODO: figure out where this is called and why the nullable suppression is required return GetCompilationAsync(GetProjectState(projectId)!, cancellationToken); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectState"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> public Task<Compilation?> GetCompilationAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetCompilationAsync(this, cancellationToken).AsNullable() : SpecializedTasks.Null<Compilation>(); } /// <summary> /// Return reference completeness for the given project and all projects this references. /// </summary> public Task<bool> HasSuccessfullyLoadedAsync(ProjectState project, CancellationToken cancellationToken) { // return HasAllInformation when compilation is not supported. // regardless whether project support compilation or not, if projectInfo is not complete, we can't guarantee its reference completeness return project.SupportsCompilation ? this.GetCompilationTracker(project.Id).HasSuccessfullyLoadedAsync(this, cancellationToken) : project.HasAllInformation ? SpecializedTasks.True : SpecializedTasks.False; } /// <summary> /// Returns the generated document states for source generated documents. /// </summary> public ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetSourceGeneratedDocumentStatesAsync(this, cancellationToken) : new(TextDocumentStates<SourceGeneratedDocumentState>.Empty); } /// <summary> /// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed. /// </summary> /// <remarks> /// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been /// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something /// similarly tricky like that. /// </remarks> public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { return GetCompilationTracker(documentId.ProjectId).TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); } /// <summary> /// Returns a new SolutionState that will always produce a specific output for a generated file. This is used only in the /// implementation of <see cref="TextExtensions.GetOpenDocumentInCurrentContextWithChanges"/> where if a user has a source /// generated file open, we need to make sure everything lines up. /// </summary> public SolutionState WithFrozenSourceGeneratedDocument(SourceGeneratedDocumentIdentity documentIdentity, SourceText sourceText) { // We won't support freezing multiple source generated documents at once. Although nothing in the implementation // of this method would have problems, this simplifies the handling of serializing this solution to out-of-proc. // Since we only produce these snapshots from an open document, there should be no way to observe this, so this assertion // also serves as a good check on the system. If down the road we need to support this, we can remove this check and // update the out-of-process serialization logic accordingly. Contract.ThrowIfTrue(_frozenSourceGeneratedDocumentState != null, "We shouldn't be calling WithFrozenSourceGeneratedDocument on a solution with a frozen source generated document."); var existingGeneratedState = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentIdentity.DocumentId); SourceGeneratedDocumentState newGeneratedState; if (existingGeneratedState != null) { newGeneratedState = existingGeneratedState.WithUpdatedGeneratedContent(sourceText, existingGeneratedState.ParseOptions); // If the content already matched, we can just reuse the existing state if (newGeneratedState == existingGeneratedState) { return this; } } else { var projectState = GetRequiredProjectState(documentIdentity.DocumentId.ProjectId); newGeneratedState = SourceGeneratedDocumentState.Create( documentIdentity, sourceText, projectState.ParseOptions!, projectState.LanguageServices, _solutionServices); } var projectId = documentIdentity.DocumentId.ProjectId; var newTrackerMap = CreateCompilationTrackerMap(projectId, _dependencyGraph); // We want to create a new snapshot with a new compilation tracker that will do this replacement. // If we already have an existing tracker we'll just wrap that (so we also are reusing any underlying // computations). If we don't have one, we'll create one and then wrap it. if (!newTrackerMap.TryGetValue(projectId, out var existingTracker)) { existingTracker = CreateCompilationTracker(projectId, this); } newTrackerMap = newTrackerMap.SetItem( projectId, new GeneratedFileReplacingCompilationTracker(existingTracker, newGeneratedState)); return this.Branch( projectIdToTrackerMap: newTrackerMap, frozenSourceGeneratedDocument: newGeneratedState); } /// <summary> /// Symbols need to be either <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/>. /// </summary> private static readonly ConditionalWeakTable<ISymbol, ProjectId> s_assemblyOrModuleSymbolToProjectMap = new(); /// <summary> /// Get a metadata reference for the project's compilation /// </summary> public Task<MetadataReference> GetMetadataReferenceAsync(ProjectReference projectReference, ProjectState fromProject, CancellationToken cancellationToken) { try { // Get the compilation state for this project. If it's not already created, then this // will create it. Then force that state to completion and get a metadata reference to it. var tracker = this.GetCompilationTracker(projectReference.ProjectId); return tracker.GetMetadataReferenceAsync(this, fromProject, projectReference, cancellationToken); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempt to get the best readily available compilation for the project. It may be a /// partially built compilation. /// </summary> private MetadataReference? GetPartialMetadataReference( ProjectReference projectReference, ProjectState fromProject) { // Try to get the compilation state for this project. If it doesn't exist, don't do any // more work. if (!_projectIdToTrackerMap.TryGetValue(projectReference.ProjectId, out var state)) { return null; } return state.GetPartialMetadataReference(fromProject, projectReference); } public async Task<bool> ContainsSymbolsWithNameAsync(ProjectId id, string name, SymbolFilter filter, CancellationToken cancellationToken) { var result = GetCompilationTracker(id).ContainsSymbolsWithNameFromDeclarationOnlyCompilation(name, filter, cancellationToken); if (result.HasValue) { return result.Value; } // it looks like declaration compilation doesn't exist yet. we have to build full compilation var compilation = await GetCompilationAsync(id, cancellationToken).ConfigureAwait(false); if (compilation == null) { // some projects don't support compilations (e.g., TypeScript) so there's nothing to check return false; } return compilation.ContainsSymbolsWithName(name, filter, cancellationToken); } public async Task<bool> ContainsSymbolsWithNameAsync(ProjectId id, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { var result = GetCompilationTracker(id).ContainsSymbolsWithNameFromDeclarationOnlyCompilation(predicate, filter, cancellationToken); if (result.HasValue) { return result.Value; } // it looks like declaration compilation doesn't exist yet. we have to build full compilation var compilation = await GetCompilationAsync(id, cancellationToken).ConfigureAwait(false); if (compilation == null) { // some projects don't support compilations (e.g., TypeScript) so there's nothing to check return false; } return compilation.ContainsSymbolsWithName(predicate, filter, cancellationToken); } public async Task<ImmutableArray<DocumentState>> GetDocumentsWithNameAsync( ProjectId id, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { // this will be used to find documents that contain declaration information in IDE cache such as DeclarationSyntaxTreeInfo for "NavigateTo" var trees = GetCompilationTracker(id).GetSyntaxTreesWithNameFromDeclarationOnlyCompilation(predicate, filter, cancellationToken); if (trees != null) { return ConvertTreesToDocuments(id, trees); } // it looks like declaration compilation doesn't exist yet. we have to build full compilation var compilation = await GetCompilationAsync(id, cancellationToken).ConfigureAwait(false); if (compilation == null) { // some projects don't support compilations (e.g., TypeScript) so there's nothing to check return ImmutableArray<DocumentState>.Empty; } return ConvertTreesToDocuments( id, compilation.GetSymbolsWithName(predicate, filter, cancellationToken).SelectMany(s => s.DeclaringSyntaxReferences.Select(r => r.SyntaxTree))); } private ImmutableArray<DocumentState> ConvertTreesToDocuments(ProjectId id, IEnumerable<SyntaxTree> trees) { var result = ArrayBuilder<DocumentState>.GetInstance(); foreach (var tree in trees) { var document = GetDocumentState(tree, id); if (document == null) { // ignore trees that are not known to solution such as VB synthesized trees made by compilation. continue; } result.Add(document); } return result.ToImmutableAndFree(); } /// <summary> /// Gets a <see cref="ProjectDependencyGraph"/> that details the dependencies between projects for this solution. /// </summary> public ProjectDependencyGraph GetProjectDependencyGraph() => _dependencyGraph; private void CheckNotContainsProject(ProjectId projectId) { if (this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_already_contains_the_specified_project); } } private void CheckContainsProject(ProjectId projectId) { if (!this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_does_not_contain_the_specified_project); } } internal bool ContainsProjectReference(ProjectId projectId, ProjectReference projectReference) => GetRequiredProjectState(projectId).ProjectReferences.Contains(projectReference); internal bool ContainsMetadataReference(ProjectId projectId, MetadataReference metadataReference) => GetRequiredProjectState(projectId).MetadataReferences.Contains(metadataReference); internal bool ContainsAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) => GetRequiredProjectState(projectId).AnalyzerReferences.Contains(analyzerReference); internal bool ContainsTransitiveReference(ProjectId fromProjectId, ProjectId toProjectId) => _dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(fromProjectId).Contains(toProjectId); internal ImmutableHashSet<string> GetRemoteSupportedProjectLanguages() => _remoteSupportedLanguages; private static ImmutableHashSet<string> GetRemoteSupportedProjectLanguages(ImmutableDictionary<ProjectId, ProjectState> projectStates) { var builder = ImmutableHashSet.CreateBuilder<string>(); foreach (var projectState in projectStates) { if (RemoteSupportedLanguages.IsSupported(projectState.Value.Language)) { builder.Add(projectState.Value.Language); } } return builder.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a set of projects and their source code documents. /// /// this is a green node of Solution like ProjectState/DocumentState are for /// Project and Document. /// </summary> internal partial class SolutionState { // branch id for this solution private readonly BranchId _branchId; // the version of the workspace this solution is from private readonly int _workspaceVersion; private readonly SolutionInfo.SolutionAttributes _solutionAttributes; private readonly SolutionServices _solutionServices; private readonly ImmutableDictionary<ProjectId, ProjectState> _projectIdToProjectStateMap; private readonly ImmutableHashSet<string> _remoteSupportedLanguages; private readonly ImmutableDictionary<string, ImmutableArray<DocumentId>> _filePathToDocumentIdsMap; private readonly ProjectDependencyGraph _dependencyGraph; public readonly IReadOnlyList<AnalyzerReference> AnalyzerReferences; // Values for all these are created on demand. private ImmutableDictionary<ProjectId, ICompilationTracker> _projectIdToTrackerMap; // Checksums for this solution state private readonly ValueSource<SolutionStateChecksums> _lazyChecksums; /// <summary> /// Mapping from project-id to the options and checksums needed to synchronize it (and the projects it depends on) over /// to an OOP host. Options are stored as well so that when we are attempting to match a request for a particular project-subset /// we can return the options specific to that project-subset (which may be different from the <see cref="Options"/> defined /// for the entire solution). Lock this specific field before reading/writing to it. /// </summary> private readonly Dictionary<ProjectId, (SerializableOptionSet options, ValueSource<SolutionStateChecksums> checksums)> _lazyProjectChecksums = new(); // holds on data calculated based on the AnalyzerReferences list private readonly Lazy<HostDiagnosticAnalyzers> _lazyAnalyzers; /// <summary> /// Cache we use to map between unrooted symbols (i.e. assembly, module and dynamic symbols) and the project /// they came from. That way if we are asked about many symbols from the same assembly/module we can answer the /// question quickly after computing for the first one. Created on demand. /// </summary> private ConditionalWeakTable<ISymbol, ProjectId?>? _unrootedSymbolToProjectId; private static readonly Func<ConditionalWeakTable<ISymbol, ProjectId?>> s_createTable = () => new ConditionalWeakTable<ISymbol, ProjectId?>(); private readonly SourceGeneratedDocumentState? _frozenSourceGeneratedDocumentState; private SolutionState( BranchId branchId, int workspaceVersion, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, IReadOnlyList<ProjectId> projectIds, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences, ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap, ImmutableHashSet<string> remoteSupportedLanguages, ImmutableDictionary<ProjectId, ICompilationTracker> projectIdToTrackerMap, ImmutableDictionary<string, ImmutableArray<DocumentId>> filePathToDocumentIdsMap, ProjectDependencyGraph dependencyGraph, Lazy<HostDiagnosticAnalyzers>? lazyAnalyzers, SourceGeneratedDocumentState? frozenSourceGeneratedDocument) { _branchId = branchId; _workspaceVersion = workspaceVersion; _solutionAttributes = solutionAttributes; _solutionServices = solutionServices; ProjectIds = projectIds; Options = options; AnalyzerReferences = analyzerReferences; _projectIdToProjectStateMap = idToProjectStateMap; _remoteSupportedLanguages = remoteSupportedLanguages; _projectIdToTrackerMap = projectIdToTrackerMap; _filePathToDocumentIdsMap = filePathToDocumentIdsMap; _dependencyGraph = dependencyGraph; _lazyAnalyzers = lazyAnalyzers ?? CreateLazyHostDiagnosticAnalyzers(analyzerReferences); _frozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument; // when solution state is changed, we recalculate its checksum _lazyChecksums = new AsyncLazy<SolutionStateChecksums>( c => ComputeChecksumsAsync(projectsToInclude: null, Options, c), cacheResult: true); CheckInvariants(); // make sure we don't accidentally capture any state but the list of references: static Lazy<HostDiagnosticAnalyzers> CreateLazyHostDiagnosticAnalyzers(IReadOnlyList<AnalyzerReference> analyzerReferences) => new(() => new HostDiagnosticAnalyzers(analyzerReferences)); } public SolutionState( BranchId primaryBranchId, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences) : this( primaryBranchId, workspaceVersion: 0, solutionServices, solutionAttributes, projectIds: SpecializedCollections.EmptyBoxedImmutableArray<ProjectId>(), options, analyzerReferences, idToProjectStateMap: ImmutableDictionary<ProjectId, ProjectState>.Empty, remoteSupportedLanguages: ImmutableHashSet<string>.Empty, projectIdToTrackerMap: ImmutableDictionary<ProjectId, ICompilationTracker>.Empty, filePathToDocumentIdsMap: ImmutableDictionary.Create<string, ImmutableArray<DocumentId>>(StringComparer.OrdinalIgnoreCase), dependencyGraph: ProjectDependencyGraph.Empty, lazyAnalyzers: null, frozenSourceGeneratedDocument: null) { } public SolutionState WithNewWorkspace(Workspace workspace, int workspaceVersion) { var services = workspace != _solutionServices.Workspace ? new SolutionServices(workspace) : _solutionServices; // Note: this will potentially have problems if the workspace services are different, as some services // get locked-in by document states and project states when first constructed. return CreatePrimarySolution(branchId: workspace.PrimaryBranchId, workspaceVersion: workspaceVersion, services: services); } public HostDiagnosticAnalyzers Analyzers => _lazyAnalyzers.Value; public SolutionInfo.SolutionAttributes SolutionAttributes => _solutionAttributes; public SourceGeneratedDocumentState? FrozenSourceGeneratedDocumentState => _frozenSourceGeneratedDocumentState; public ImmutableDictionary<ProjectId, ProjectState> ProjectStates => _projectIdToProjectStateMap; public int WorkspaceVersion => _workspaceVersion; public SolutionServices Services => _solutionServices; public SerializableOptionSet Options { get; } /// <summary> /// branch id of this solution /// /// currently, it only supports one level of branching. there is a primary branch of a workspace and all other /// branches that are branched from the primary branch. /// /// one still can create multiple forked solutions from an already branched solution, but versions among those /// can't be reliably used and compared. /// /// version only has a meaning between primary solution and branched one or between solutions from same branch. /// </summary> public BranchId BranchId => _branchId; /// <summary> /// The Workspace this solution is associated with. /// </summary> public Workspace Workspace => _solutionServices.Workspace; /// <summary> /// The Id of the solution. Multiple solution instances may share the same Id. /// </summary> public SolutionId Id => _solutionAttributes.Id; /// <summary> /// The path to the solution file or null if there is no solution file. /// </summary> public string? FilePath => _solutionAttributes.FilePath; /// <summary> /// The solution version. This equates to the solution file's version. /// </summary> public VersionStamp Version => _solutionAttributes.Version; /// <summary> /// A list of all the ids for all the projects contained by the solution. /// </summary> public IReadOnlyList<ProjectId> ProjectIds { get; } // Only run this in debug builds; even the .Any() call across all projects can be expensive when there's a lot of them. [Conditional("DEBUG")] private void CheckInvariants() { Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == ProjectIds.Count); Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == _dependencyGraph.ProjectIds.Count); // An id shouldn't point at a tracker for a different project. Contract.ThrowIfTrue(_projectIdToTrackerMap.Any(kvp => kvp.Key != kvp.Value.ProjectState.Id)); // project ids must be the same: Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(ProjectIds)); Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(_dependencyGraph.ProjectIds)); Debug.Assert(_remoteSupportedLanguages.SetEquals(GetRemoteSupportedProjectLanguages(_projectIdToProjectStateMap))); } private SolutionState Branch( SolutionInfo.SolutionAttributes? solutionAttributes = null, IReadOnlyList<ProjectId>? projectIds = null, SerializableOptionSet? options = null, IReadOnlyList<AnalyzerReference>? analyzerReferences = null, ImmutableDictionary<ProjectId, ProjectState>? idToProjectStateMap = null, ImmutableHashSet<string>? remoteSupportedProjectLanguages = null, ImmutableDictionary<ProjectId, ICompilationTracker>? projectIdToTrackerMap = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? filePathToDocumentIdsMap = null, ProjectDependencyGraph? dependencyGraph = null, Optional<SourceGeneratedDocumentState?> frozenSourceGeneratedDocument = default) { var branchId = GetBranchId(); if (idToProjectStateMap is not null) { Contract.ThrowIfNull(remoteSupportedProjectLanguages); } solutionAttributes ??= _solutionAttributes; projectIds ??= ProjectIds; idToProjectStateMap ??= _projectIdToProjectStateMap; remoteSupportedProjectLanguages ??= _remoteSupportedLanguages; Debug.Assert(remoteSupportedProjectLanguages.SetEquals(GetRemoteSupportedProjectLanguages(idToProjectStateMap))); options ??= Options.WithLanguages(remoteSupportedProjectLanguages); analyzerReferences ??= AnalyzerReferences; projectIdToTrackerMap ??= _projectIdToTrackerMap; filePathToDocumentIdsMap ??= _filePathToDocumentIdsMap; dependencyGraph ??= _dependencyGraph; var newFrozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument.HasValue ? frozenSourceGeneratedDocument.Value : _frozenSourceGeneratedDocumentState; var analyzerReferencesEqual = AnalyzerReferences.SequenceEqual(analyzerReferences); if (branchId == _branchId && solutionAttributes == _solutionAttributes && projectIds == ProjectIds && options == Options && analyzerReferencesEqual && idToProjectStateMap == _projectIdToProjectStateMap && projectIdToTrackerMap == _projectIdToTrackerMap && filePathToDocumentIdsMap == _filePathToDocumentIdsMap && dependencyGraph == _dependencyGraph && newFrozenSourceGeneratedDocumentState == _frozenSourceGeneratedDocumentState) { return this; } return new SolutionState( branchId, _workspaceVersion, _solutionServices, solutionAttributes, projectIds, options, analyzerReferences, idToProjectStateMap, remoteSupportedProjectLanguages, projectIdToTrackerMap, filePathToDocumentIdsMap, dependencyGraph, analyzerReferencesEqual ? _lazyAnalyzers : null, newFrozenSourceGeneratedDocumentState); } private SolutionState CreatePrimarySolution( BranchId branchId, int workspaceVersion, SolutionServices services) { if (branchId == _branchId && workspaceVersion == _workspaceVersion && services == _solutionServices) { return this; } return new SolutionState( branchId, workspaceVersion, services, _solutionAttributes, ProjectIds, Options, AnalyzerReferences, _projectIdToProjectStateMap, _remoteSupportedLanguages, _projectIdToTrackerMap, _filePathToDocumentIdsMap, _dependencyGraph, _lazyAnalyzers, frozenSourceGeneratedDocument: null); } private BranchId GetBranchId() { // currently we only support one level branching. // my reasonings are // 1. it seems there is no-one who needs sub branches. // 2. this lets us to branch without explicit branch API return _branchId == Workspace.PrimaryBranchId ? BranchId.GetNextId() : _branchId; } /// <summary> /// The version of the most recently modified project. /// </summary> public VersionStamp GetLatestProjectVersion() { // this may produce a version that is out of sync with the actual Document versions. var latestVersion = VersionStamp.Default; foreach (var project in this.ProjectStates.Values) { latestVersion = project.Version.GetNewerVersion(latestVersion); } return latestVersion; } /// <summary> /// True if the solution contains a project with the specified project ID. /// </summary> public bool ContainsProject([NotNullWhen(returnValue: true)] ProjectId? projectId) => projectId != null && _projectIdToProjectStateMap.ContainsKey(projectId); /// <summary> /// True if the solution contains the document in one of its projects /// </summary> public bool ContainsDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.DocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the additional document in one of its projects /// </summary> public bool ContainsAdditionalDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AdditionalDocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the analyzer config document in one of its projects /// </summary> public bool ContainsAnalyzerConfigDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AnalyzerConfigDocumentStates.Contains(documentId); } private DocumentState GetRequiredDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).DocumentStates.GetRequiredState(documentId); private AdditionalDocumentState GetRequiredAdditionalDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AdditionalDocumentStates.GetRequiredState(documentId); private AnalyzerConfigDocumentState GetRequiredAnalyzerConfigDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AnalyzerConfigDocumentStates.GetRequiredState(documentId); internal DocumentState? GetDocumentState(SyntaxTree? syntaxTree, ProjectId? projectId) { if (syntaxTree != null) { // is this tree known to be associated with a document? var documentId = DocumentState.GetDocumentIdForTree(syntaxTree); if (documentId != null && (projectId == null || documentId.ProjectId == projectId)) { // does this solution even have the document? var projectState = GetProjectState(documentId.ProjectId); if (projectState != null) { var document = projectState.DocumentStates.GetState(documentId); if (document != null) { // does this document really have the syntax tree? if (document.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return document; } } else { var generatedDocument = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); if (generatedDocument != null) { // does this document really have the syntax tree? if (generatedDocument.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return generatedDocument; } } } } } } return null; } public Task<VersionStamp> GetDependentVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentVersionAsync(this, cancellationToken); public Task<VersionStamp> GetDependentSemanticVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentSemanticVersionAsync(this, cancellationToken); public ProjectState? GetProjectState(ProjectId projectId) { _projectIdToProjectStateMap.TryGetValue(projectId, out var state); return state; } public ProjectState GetRequiredProjectState(ProjectId projectId) { var result = GetProjectState(projectId); Contract.ThrowIfNull(result); return result; } /// <summary> /// Gets the <see cref="Project"/> associated with an assembly symbol. /// </summary> public ProjectState? GetProjectState(IAssemblySymbol? assemblySymbol) { if (assemblySymbol == null) return null; s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblySymbol, out var id); return id == null ? null : this.GetProjectState(id); } private bool TryGetCompilationTracker(ProjectId projectId, [NotNullWhen(returnValue: true)] out ICompilationTracker? tracker) => _projectIdToTrackerMap.TryGetValue(projectId, out tracker); private static readonly Func<ProjectId, SolutionState, CompilationTracker> s_createCompilationTrackerFunction = CreateCompilationTracker; private static CompilationTracker CreateCompilationTracker(ProjectId projectId, SolutionState solution) { var projectState = solution.GetProjectState(projectId); Contract.ThrowIfNull(projectState); return new CompilationTracker(projectState); } private ICompilationTracker GetCompilationTracker(ProjectId projectId) { if (!_projectIdToTrackerMap.TryGetValue(projectId, out var tracker)) { tracker = ImmutableInterlocked.GetOrAdd(ref _projectIdToTrackerMap, projectId, s_createCompilationTrackerFunction, this); } return tracker; } private SolutionState AddProject(ProjectId projectId, ProjectState projectState) { // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Add(projectId); var newStateMap = _projectIdToProjectStateMap.Add(projectId, projectState); var newLanguages = RemoteSupportedLanguages.IsSupported(projectState.Language) ? _remoteSupportedLanguages.Add(projectState.Language) : _remoteSupportedLanguages; var newDependencyGraph = _dependencyGraph .WithAdditionalProject(projectId) .WithAdditionalProjectReferences(projectId, projectState.ProjectReferences); // It's possible that another project already in newStateMap has a reference to this project that we're adding, since we allow // dangling references like that. If so, we'll need to link those in too. foreach (var newState in newStateMap) { foreach (var projectReference in newState.Value.ProjectReferences) { if (projectReference.ProjectId == projectId) { newDependencyGraph = newDependencyGraph.WithAdditionalProjectReferences( newState.Key, SpecializedCollections.SingletonReadOnlyList(projectReference)); break; } } } var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithAddedDocuments(GetDocumentStates(newStateMap[projectId])); return Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance that includes a project with the specified project information. /// </summary> public SolutionState AddProject(ProjectInfo projectInfo) { if (projectInfo == null) { throw new ArgumentNullException(nameof(projectInfo)); } var projectId = projectInfo.Id; var language = projectInfo.Language; if (language == null) { throw new ArgumentNullException(nameof(language)); } var displayName = projectInfo.Name; if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } CheckNotContainsProject(projectId); var languageServices = this.Workspace.Services.GetLanguageServices(language); if (languageServices == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_language_0_is_not_supported, language)); } var newProject = new ProjectState(projectInfo, languageServices, _solutionServices); return this.AddProject(newProject.Id, newProject); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithAddedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } builder.MultiAdd(filePath, documentState.Id); } return builder.ToImmutable(); } private static IEnumerable<TextDocumentState> GetDocumentStates(ProjectState projectState) => projectState.DocumentStates.States.Values .Concat<TextDocumentState>(projectState.AdditionalDocumentStates.States.Values) .Concat(projectState.AnalyzerConfigDocumentStates.States.Values); /// <summary> /// Create a new solution instance without the project specified. /// </summary> public SolutionState RemoveProject(ProjectId projectId) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } CheckContainsProject(projectId); // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: this.Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Remove(projectId); var newStateMap = _projectIdToProjectStateMap.Remove(projectId); // Remote supported languages only changes if the removed project is the last project of a supported language. var newLanguages = _remoteSupportedLanguages; if (_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) && RemoteSupportedLanguages.IsSupported(projectState.Language)) { var stillSupportsLanguage = false; foreach (var (id, state) in _projectIdToProjectStateMap) { if (id == projectId) continue; if (state.Language == projectState.Language) { stillSupportsLanguage = true; break; } } if (!stillSupportsLanguage) { newLanguages = newLanguages.Remove(projectState.Language); } } var newDependencyGraph = _dependencyGraph.WithProjectRemoved(projectId); var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithRemovedDocuments(GetDocumentStates(_projectIdToProjectStateMap[projectId])); return this.Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap.Remove(projectId), filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithRemovedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } if (!builder.TryGetValue(filePath, out var documentIdsWithPath) || !documentIdsWithPath.Contains(documentState.Id)) { throw new ArgumentException($"The given documentId was not found in '{nameof(_filePathToDocumentIdsMap)}'."); } builder.MultiRemove(filePath, documentState.Id); } return builder.ToImmutable(); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithFilePath(DocumentId documentId, string? oldFilePath, string? newFilePath) { if (oldFilePath == newFilePath) { return _filePathToDocumentIdsMap; } var builder = _filePathToDocumentIdsMap.ToBuilder(); if (!RoslynString.IsNullOrEmpty(oldFilePath)) { builder.MultiRemove(oldFilePath, documentId); } if (!RoslynString.IsNullOrEmpty(newFilePath)) { builder.MultiAdd(newFilePath, documentId); } return builder.ToImmutable(); } /// <summary> /// Creates a new solution instance with the project specified updated to have the new /// assembly name. /// </summary> public SolutionState WithProjectAssemblyName(ProjectId projectId, string assemblyName) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAssemblyName(assemblyName); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectAssemblyNameAction(assemblyName)); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputFilePath(ProjectId projectId, string? outputFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputFilePath(outputFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputRefFilePath(ProjectId projectId, string? outputRefFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputRefFilePath(outputRefFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the compiler output file path. /// </summary> public SolutionState WithProjectCompilationOutputInfo(ProjectId projectId, in CompilationOutputInfo info) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOutputInfo(info); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the default namespace. /// </summary> public SolutionState WithProjectDefaultNamespace(ProjectId projectId, string? defaultNamespace) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithDefaultNamespace(defaultNamespace); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the name. /// </summary> public SolutionState WithProjectName(ProjectId projectId, string name) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithName(name); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the project file path. /// </summary> public SolutionState WithProjectFilePath(ProjectId projectId, string? filePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithFilePath(filePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified compilation options. /// </summary> public SolutionState WithProjectCompilationOptions(ProjectId projectId, CompilationOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOptions(options); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified parse options. /// </summary> public SolutionState WithProjectParseOptions(ProjectId projectId, ParseOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithParseOptions(options); if (oldProject == newProject) { return this; } if (Workspace.PartialSemanticsEnabled) { // don't fork tracker with queued action since access via partial semantics can become inconsistent (throw). // Since changing options is rare event, it is okay to start compilation building from scratch. return ForkProject(newProject, forkTracker: false); } else { return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: true)); } } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified hasAllInformation. /// </summary> public SolutionState WithHasAllInformation(ProjectId projectId, bool hasAllInformation) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithHasAllInformation(hasAllInformation); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified runAnalyzers. /// </summary> public SolutionState WithRunAnalyzers(ProjectId projectId, bool runAnalyzers) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithRunAnalyzers(runAnalyzers); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include /// the specified project references. /// </summary> public SolutionState AddProjectReferences(ProjectId projectId, IReadOnlyCollection<ProjectReference> projectReferences) { if (projectReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(projectReferences); var newProject = oldProject.WithProjectReferences(newReferences); var newDependencyGraph = _dependencyGraph.WithAdditionalProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to no longer /// include the specified project reference. /// </summary> public SolutionState RemoveProjectReference(ProjectId projectId, ProjectReference projectReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); // Note: uses ProjectReference equality to compare references. var newReferences = oldReferences.Remove(projectReference); if (oldReferences == newReferences) { return this; } var newProject = oldProject.WithProjectReferences(newReferences); ProjectDependencyGraph newDependencyGraph; if (newProject.ContainsReferenceToProject(projectReference.ProjectId) || !_projectIdToProjectStateMap.ContainsKey(projectReference.ProjectId)) { // Two cases: // 1) The project contained multiple non-equivalent references to the project, // and not all of them were removed. The dependency graph doesn't change. // Note that there might be two references to the same project, one with // extern alias and the other without. These are not considered duplicates. // 2) The referenced project is not part of the solution and hence not included // in the dependency graph. newDependencyGraph = _dependencyGraph; } else { newDependencyGraph = _dependencyGraph.WithProjectReferenceRemoved(projectId, projectReference.ProjectId); } return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to contain /// the specified list of project references. /// </summary> public SolutionState WithProjectReferences(ProjectId projectId, IReadOnlyList<ProjectReference> projectReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithProjectReferences(projectReferences); if (oldProject == newProject) { return this; } var newDependencyGraph = _dependencyGraph.WithProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Creates a new solution instance with the project documents in the order by the specified document ids. /// The specified document ids must be the same as what is already in the project; no adding or removing is allowed. /// </summary> public SolutionState WithProjectDocumentsOrder(ProjectId projectId, ImmutableList<DocumentId> documentIds) { var oldProject = GetRequiredProjectState(projectId); if (documentIds.Count != oldProject.DocumentStates.Count) { throw new ArgumentException($"The specified documents do not equal the project document count.", nameof(documentIds)); } foreach (var id in documentIds) { if (!oldProject.DocumentStates.Contains(id)) { throw new InvalidOperationException($"The document '{id}' does not exist in the project."); } } var newProject = oldProject.UpdateDocumentsOrder(documentIds); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified metadata references. /// </summary> public SolutionState AddMetadataReferences(ProjectId projectId, IReadOnlyCollection<MetadataReference> metadataReferences) { if (metadataReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(metadataReferences); return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified metadata reference. /// </summary> public SolutionState RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(metadataReference); if (oldReferences == newReferences) { return this; } return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified metadata references. /// </summary> public SolutionState WithProjectMetadataReferences(ProjectId projectId, IReadOnlyList<MetadataReference> metadataReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithMetadataReferences(metadataReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified analyzer references. /// </summary> public SolutionState AddAnalyzerReferences(ProjectId projectId, ImmutableArray<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Length == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.AddAnalyzerReferencesAction(analyzerReferences, oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified analyzer reference. /// </summary> public SolutionState RemoveAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.RemoveAnalyzerReferencesAction(ImmutableArray.Create(analyzerReference), oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified analyzer references. /// </summary> public SolutionState WithProjectAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAnalyzerReferences(analyzerReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the corresponding projects updated to include new /// documents defined by the document info. /// </summary> public SolutionState AddDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => project.CreateDocument(documentInfo, project.ParseOptions), (oldProject, documents) => (oldProject.AddDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddDocumentsAction(documents))); } /// <summary> /// Core helper that takes a set of <see cref="DocumentInfo" />s and does the application of the appropriate documents to each project. /// </summary> /// <param name="documentInfos">The set of documents to add.</param> /// <param name="addDocumentsToProjectState">Returns the new <see cref="ProjectState"/> with the documents added, and the <see cref="CompilationAndGeneratorDriverTranslationAction"/> needed as well.</param> /// <returns></returns> private SolutionState AddDocumentsToMultipleProjects<T>( ImmutableArray<DocumentInfo> documentInfos, Func<DocumentInfo, ProjectState, T> createDocumentState, Func<ProjectState, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> addDocumentsToProjectState) where T : TextDocumentState { if (documentInfos.IsDefault) { throw new ArgumentNullException(nameof(documentInfos)); } if (documentInfos.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentInfosByProjectId = documentInfos.ToLookup(d => d.Id.ProjectId); var newSolutionState = this; foreach (var documentInfosInProject in documentInfosByProjectId) { CheckContainsProject(documentInfosInProject.Key); var oldProjectState = this.GetProjectState(documentInfosInProject.Key)!; var newDocumentStatesForProjectBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentInfo in documentInfosInProject) { newDocumentStatesForProjectBuilder.Add(createDocumentState(documentInfo, oldProjectState)); } var newDocumentStatesForProject = newDocumentStatesForProjectBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = addDocumentsToProjectState(oldProjectState, newDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithAddedDocuments(newDocumentStatesForProject)); } return newSolutionState; } public SolutionState AddAdditionalDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AdditionalDocumentState(documentInfo, _solutionServices), (projectState, documents) => (projectState.AddAdditionalDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddAdditionalDocumentsAction(documents))); } public SolutionState AddAnalyzerConfigDocuments(ImmutableArray<DocumentInfo> documentInfos) { // Adding a new analyzer config potentially modifies the compilation options return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AnalyzerConfigDocumentState(documentInfo, _solutionServices), (oldProject, documents) => { var newProject = oldProject.AddAnalyzerConfigDocuments(documents); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } public SolutionState RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AnalyzerConfigDocumentStates.GetRequiredState(documentId), (oldProject, documentIds, _) => { var newProject = oldProject.RemoveAnalyzerConfigDocuments(documentIds); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } /// <summary> /// Creates a new solution instance that no longer includes the specified document. /// </summary> public SolutionState RemoveDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.DocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveDocumentsAction(documentStates))); } private SolutionState RemoveDocumentsFromMultipleProjects<T>( ImmutableArray<DocumentId> documentIds, Func<ProjectState, DocumentId, T> getExistingTextDocumentState, Func<ProjectState, ImmutableArray<DocumentId>, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> removeDocumentsFromProjectState) where T : TextDocumentState { if (documentIds.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentIdsByProjectId = documentIds.ToLookup(id => id.ProjectId); var newSolutionState = this; foreach (var documentIdsInProject in documentIdsByProjectId) { var oldProjectState = this.GetProjectState(documentIdsInProject.Key); if (oldProjectState == null) { throw new InvalidOperationException(string.Format(WorkspacesResources._0_is_not_part_of_the_workspace, documentIdsInProject.Key)); } var removedDocumentStatesBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentId in documentIdsInProject) { removedDocumentStatesBuilder.Add(getExistingTextDocumentState(oldProjectState, documentId)); } var removedDocumentStatesForProject = removedDocumentStatesBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = removeDocumentsFromProjectState(oldProjectState, documentIdsInProject.ToImmutableArray(), removedDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithRemovedDocuments(removedDocumentStatesForProject)); } return newSolutionState; } /// <summary> /// Creates a new solution instance that no longer includes the specified additional documents. /// </summary> public SolutionState RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AdditionalDocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveAdditionalDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveAdditionalDocumentsAction(documentStates))); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified name. /// </summary> public SolutionState WithDocumentName(DocumentId documentId, string name) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Attributes.Name == name) { return this; } return UpdateDocumentState(oldDocument.UpdateName(name)); } /// <summary> /// Creates a new solution instance with the document specified updated to be contained in /// the sequence of logical folders. /// </summary> public SolutionState WithDocumentFolders(DocumentId documentId, IReadOnlyList<string> folders) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Folders.SequenceEqual(folders)) { return this; } return UpdateDocumentState(oldDocument.UpdateFolders(folders)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified file path. /// </summary> public SolutionState WithDocumentFilePath(DocumentId documentId, string? filePath) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.FilePath == filePath) { return this; } return UpdateDocumentState(oldDocument.UpdateFilePath(filePath)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(text, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(textAndVersion, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have a syntax tree /// rooted by the specified syntax node. /// </summary> public SolutionState WithDocumentSyntaxRoot(DocumentId documentId, SyntaxNode root, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetSyntaxTree(out var oldTree) && oldTree.TryGetRoot(out var oldRoot) && oldRoot == root) { return this; } return UpdateDocumentState(oldDocument.UpdateTree(root, mode), textChanged: true); } private static async Task<Compilation> UpdateDocumentInCompilationAsync( Compilation compilation, DocumentState oldDocument, DocumentState newDocument, CancellationToken cancellationToken) { return compilation.ReplaceSyntaxTree( await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false), await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the source /// code kind specified. /// </summary> public SolutionState WithDocumentSourceCodeKind(DocumentId documentId, SourceCodeKind sourceCodeKind) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.SourceCodeKind == sourceCodeKind) { return this; } return UpdateDocumentState(oldDocument.UpdateSourceCodeKind(sourceCodeKind), textChanged: true); } public SolutionState UpdateDocumentTextLoader(DocumentId documentId, TextLoader loader, SourceText? text, PreservationMode mode) { var oldDocument = GetRequiredDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateDocumentState(oldDocument.UpdateText(loader, text, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAdditionalDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAdditionalDocumentState(oldDocument.UpdateText(loader, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAnalyzerConfigDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(loader, mode)); } private SolutionState UpdateDocumentState(DocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.DocumentStates.GetRequiredState(newDocument.Id); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithFilePath(newDocument.Id, oldDocument.FilePath, newDocument.FilePath); return ForkProject( newProject, new CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction(oldDocument, newDocument), newFilePathToDocumentIdsMap: newFilePathToDocumentIdsMap); } private SolutionState UpdateAdditionalDocumentState(AdditionalDocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAdditionalDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.AdditionalDocumentStates.GetRequiredState(newDocument.Id); return ForkProject( newProject, translate: new CompilationAndGeneratorDriverTranslationAction.TouchAdditionalDocumentAction(oldDocument, newDocument)); } private SolutionState UpdateAnalyzerConfigDocumentState(AnalyzerConfigDocumentState newDocument) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAnalyzerConfigDocument(newDocument); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); return ForkProject(newProject, newProject.CompilationOptions != null ? new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true) : null); } /// <summary> /// Creates a new snapshot with an updated project and an action that will produce a new /// compilation matching the new project out of an old compilation. All dependent projects /// are fixed-up if the change to the new project affects its public metadata, and old /// dependent compilations are forgotten. /// </summary> private SolutionState ForkProject( ProjectState newProjectState, CompilationAndGeneratorDriverTranslationAction? translate = null, ProjectDependencyGraph? newDependencyGraph = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? newFilePathToDocumentIdsMap = null, bool forkTracker = true) { var projectId = newProjectState.Id; var newStateMap = _projectIdToProjectStateMap.SetItem(projectId, newProjectState); // Remote supported languages can only change if the project changes language. This is an unexpected edge // case, so it's not optimized for incremental updates. var newLanguages = !_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) || projectState.Language != newProjectState.Language ? GetRemoteSupportedProjectLanguages(newStateMap) : _remoteSupportedLanguages; newDependencyGraph ??= _dependencyGraph; var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); // If we have a tracker for this project, then fork it as well (along with the // translation action and store it in the tracker map. if (newTrackerMap.TryGetValue(projectId, out var tracker)) { newTrackerMap = newTrackerMap.Remove(projectId); if (forkTracker) { newTrackerMap = newTrackerMap.Add(projectId, tracker.Fork(newProjectState, translate)); } } return this.Branch( idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, dependencyGraph: newDependencyGraph, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap ?? _filePathToDocumentIdsMap); } /// <summary> /// Gets the set of <see cref="DocumentId"/>s in this <see cref="Solution"/> with a /// <see cref="TextDocument.FilePath"/> that matches the given file path. /// </summary> public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string? filePath) { if (string.IsNullOrEmpty(filePath)) { return ImmutableArray<DocumentId>.Empty; } return _filePathToDocumentIdsMap.TryGetValue(filePath!, out var documentIds) ? documentIds : ImmutableArray<DocumentId>.Empty; } private static ProjectDependencyGraph CreateDependencyGraph( IReadOnlyList<ProjectId> projectIds, ImmutableDictionary<ProjectId, ProjectState> projectStates) { var map = projectStates.Values.Select(state => new KeyValuePair<ProjectId, ImmutableHashSet<ProjectId>>( state.Id, state.ProjectReferences.Where(pr => projectStates.ContainsKey(pr.ProjectId)).Select(pr => pr.ProjectId).ToImmutableHashSet())) .ToImmutableDictionary(); return new ProjectDependencyGraph(projectIds.ToImmutableHashSet(), map); } private ImmutableDictionary<ProjectId, ICompilationTracker> CreateCompilationTrackerMap(ProjectId changedProjectId, ProjectDependencyGraph dependencyGraph) { var builder = ImmutableDictionary.CreateBuilder<ProjectId, ICompilationTracker>(); IEnumerable<ProjectId>? dependencies = null; foreach (var (id, tracker) in _projectIdToTrackerMap) { if (!tracker.HasCompilation) { continue; } builder.Add(id, CanReuse(id) ? tracker : tracker.Fork(tracker.ProjectState)); } return builder.ToImmutable(); // Returns true if 'tracker' can be reused for project 'id' bool CanReuse(ProjectId id) { if (id == changedProjectId) { return true; } // Check the dependency graph to see if project 'id' directly or transitively depends on 'projectId'. // If the information is not available, do not compute it. var forwardDependencies = dependencyGraph.TryGetProjectsThatThisProjectTransitivelyDependsOn(id); if (forwardDependencies is object && !forwardDependencies.Contains(changedProjectId)) { return true; } // Compute the set of all projects that depend on 'projectId'. This information answers the same // question as the previous check, but involves at most one transitive computation within the // dependency graph. dependencies ??= dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(changedProjectId); return !dependencies.Contains(id); } } /// <summary> /// Gets a copy of the solution isolated from the original so that they do not share computed state. /// /// Use isolated solutions when doing operations that are likely to access a lot of text, /// syntax trees or compilations that are unlikely to be needed again after the operation is done. /// When the isolated solution is reclaimed so will the computed state. /// </summary> public SolutionState GetIsolatedSolution() { var forkedMap = ImmutableDictionary.CreateRange( _projectIdToTrackerMap.Where(kvp => kvp.Value.HasCompilation) .Select(kvp => KeyValuePairUtil.Create(kvp.Key, kvp.Value.Clone()))); return this.Branch(projectIdToTrackerMap: forkedMap); } public SolutionState WithOptions(SerializableOptionSet options) => Branch(options: options); public SolutionState AddAnalyzerReferences(IReadOnlyCollection<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Count == 0) { return this; } var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return Branch(analyzerReferences: newReferences); } public SolutionState RemoveAnalyzerReference(AnalyzerReference analyzerReference) { var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return Branch(analyzerReferences: newReferences); } public SolutionState WithAnalyzerReferences(IReadOnlyList<AnalyzerReference> analyzerReferences) { if (analyzerReferences == AnalyzerReferences) { return this; } return Branch(analyzerReferences: analyzerReferences); } // this lock guards all the mutable fields (do not share lock with derived classes) private NonReentrantLock? _stateLockBackingField; private NonReentrantLock StateLock { get { // TODO: why did I need to do a nullable suppression here? return LazyInitializer.EnsureInitialized(ref _stateLockBackingField, NonReentrantLock.Factory)!; } } private WeakReference<SolutionState>? _latestSolutionWithPartialCompilation; private DateTime _timeOfLatestSolutionWithPartialCompilation; private DocumentId? _documentIdOfLatestSolutionWithPartialCompilation; /// <summary> /// Creates a branch of the solution that has its compilations frozen in whatever state they are in at the time, assuming a background compiler is /// busy building this compilations. /// /// A compilation for the project containing the specified document id will be guaranteed to exist with at least the syntax tree for the document. /// /// This not intended to be the public API, use Document.WithFrozenPartialSemantics() instead. /// </summary> public SolutionState WithFrozenPartialCompilationIncludingSpecificDocument(DocumentId documentId, CancellationToken cancellationToken) { try { var doc = this.GetRequiredDocumentState(documentId); var tree = doc.GetSyntaxTree(cancellationToken); using (this.StateLock.DisposableWait(cancellationToken)) { // in progress solutions are disabled for some testing if (this.Workspace is Workspace ws && ws.TestHookPartialSolutionsDisabled) { return this; } SolutionState? currentPartialSolution = null; if (_latestSolutionWithPartialCompilation != null) { _latestSolutionWithPartialCompilation.TryGetTarget(out currentPartialSolution); } var reuseExistingPartialSolution = currentPartialSolution != null && (DateTime.UtcNow - _timeOfLatestSolutionWithPartialCompilation).TotalSeconds < 0.1 && _documentIdOfLatestSolutionWithPartialCompilation == documentId; if (reuseExistingPartialSolution) { SolutionLogger.UseExistingPartialSolution(); return currentPartialSolution!; } // if we don't have one or it is stale, create a new partial solution var tracker = this.GetCompilationTracker(documentId.ProjectId); var newTracker = tracker.FreezePartialStateWithTree(this, doc, tree, cancellationToken); var newIdToProjectStateMap = _projectIdToProjectStateMap.SetItem(documentId.ProjectId, newTracker.ProjectState); var newLanguages = _remoteSupportedLanguages; var newIdToTrackerMap = _projectIdToTrackerMap.SetItem(documentId.ProjectId, newTracker); currentPartialSolution = this.Branch( idToProjectStateMap: newIdToProjectStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newIdToTrackerMap, dependencyGraph: CreateDependencyGraph(ProjectIds, newIdToProjectStateMap)); _latestSolutionWithPartialCompilation = new WeakReference<SolutionState>(currentPartialSolution); _timeOfLatestSolutionWithPartialCompilation = DateTime.UtcNow; _documentIdOfLatestSolutionWithPartialCompilation = documentId; SolutionLogger.CreatePartialSolution(); return currentPartialSolution; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new solution instance with all the documents specified updated to have the same specified text. /// </summary> public SolutionState WithDocumentText(IEnumerable<DocumentId?> documentIds, SourceText text, PreservationMode mode) { var solution = this; foreach (var documentId in documentIds) { if (documentId == null) { continue; } var doc = GetProjectState(documentId.ProjectId)?.DocumentStates.GetState(documentId); if (doc != null) { if (!doc.TryGetText(out var existingText) || existingText != text) { solution = solution.WithDocumentText(documentId, text, mode); } } } return solution; } public bool TryGetCompilation(ProjectId projectId, [NotNullWhen(returnValue: true)] out Compilation? compilation) { CheckContainsProject(projectId); compilation = null; return this.TryGetCompilationTracker(projectId, out var tracker) && tracker.TryGetCompilation(out compilation); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectId"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> private Task<Compilation?> GetCompilationAsync(ProjectId projectId, CancellationToken cancellationToken) { // TODO: figure out where this is called and why the nullable suppression is required return GetCompilationAsync(GetProjectState(projectId)!, cancellationToken); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectState"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> public Task<Compilation?> GetCompilationAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetCompilationAsync(this, cancellationToken).AsNullable() : SpecializedTasks.Null<Compilation>(); } /// <summary> /// Return reference completeness for the given project and all projects this references. /// </summary> public Task<bool> HasSuccessfullyLoadedAsync(ProjectState project, CancellationToken cancellationToken) { // return HasAllInformation when compilation is not supported. // regardless whether project support compilation or not, if projectInfo is not complete, we can't guarantee its reference completeness return project.SupportsCompilation ? this.GetCompilationTracker(project.Id).HasSuccessfullyLoadedAsync(this, cancellationToken) : project.HasAllInformation ? SpecializedTasks.True : SpecializedTasks.False; } /// <summary> /// Returns the generated document states for source generated documents. /// </summary> public ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetSourceGeneratedDocumentStatesAsync(this, cancellationToken) : new(TextDocumentStates<SourceGeneratedDocumentState>.Empty); } /// <summary> /// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed. /// </summary> /// <remarks> /// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been /// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something /// similarly tricky like that. /// </remarks> public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { return GetCompilationTracker(documentId.ProjectId).TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); } /// <summary> /// Returns a new SolutionState that will always produce a specific output for a generated file. This is used only in the /// implementation of <see cref="TextExtensions.GetOpenDocumentInCurrentContextWithChanges"/> where if a user has a source /// generated file open, we need to make sure everything lines up. /// </summary> public SolutionState WithFrozenSourceGeneratedDocument(SourceGeneratedDocumentIdentity documentIdentity, SourceText sourceText) { // We won't support freezing multiple source generated documents at once. Although nothing in the implementation // of this method would have problems, this simplifies the handling of serializing this solution to out-of-proc. // Since we only produce these snapshots from an open document, there should be no way to observe this, so this assertion // also serves as a good check on the system. If down the road we need to support this, we can remove this check and // update the out-of-process serialization logic accordingly. Contract.ThrowIfTrue(_frozenSourceGeneratedDocumentState != null, "We shouldn't be calling WithFrozenSourceGeneratedDocument on a solution with a frozen source generated document."); var existingGeneratedState = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentIdentity.DocumentId); SourceGeneratedDocumentState newGeneratedState; if (existingGeneratedState != null) { newGeneratedState = existingGeneratedState.WithUpdatedGeneratedContent(sourceText, existingGeneratedState.ParseOptions); // If the content already matched, we can just reuse the existing state if (newGeneratedState == existingGeneratedState) { return this; } } else { var projectState = GetRequiredProjectState(documentIdentity.DocumentId.ProjectId); newGeneratedState = SourceGeneratedDocumentState.Create( documentIdentity, sourceText, projectState.ParseOptions!, projectState.LanguageServices, _solutionServices); } var projectId = documentIdentity.DocumentId.ProjectId; var newTrackerMap = CreateCompilationTrackerMap(projectId, _dependencyGraph); // We want to create a new snapshot with a new compilation tracker that will do this replacement. // If we already have an existing tracker we'll just wrap that (so we also are reusing any underlying // computations). If we don't have one, we'll create one and then wrap it. if (!newTrackerMap.TryGetValue(projectId, out var existingTracker)) { existingTracker = CreateCompilationTracker(projectId, this); } newTrackerMap = newTrackerMap.SetItem( projectId, new GeneratedFileReplacingCompilationTracker(existingTracker, newGeneratedState)); return this.Branch( projectIdToTrackerMap: newTrackerMap, frozenSourceGeneratedDocument: newGeneratedState); } /// <summary> /// Symbols need to be either <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/>. /// </summary> private static readonly ConditionalWeakTable<ISymbol, ProjectId> s_assemblyOrModuleSymbolToProjectMap = new(); /// <summary> /// Get a metadata reference for the project's compilation /// </summary> public Task<MetadataReference> GetMetadataReferenceAsync(ProjectReference projectReference, ProjectState fromProject, CancellationToken cancellationToken) { try { // Get the compilation state for this project. If it's not already created, then this // will create it. Then force that state to completion and get a metadata reference to it. var tracker = this.GetCompilationTracker(projectReference.ProjectId); return tracker.GetMetadataReferenceAsync(this, fromProject, projectReference, cancellationToken); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempt to get the best readily available compilation for the project. It may be a /// partially built compilation. /// </summary> private MetadataReference? GetPartialMetadataReference( ProjectReference projectReference, ProjectState fromProject) { // Try to get the compilation state for this project. If it doesn't exist, don't do any // more work. if (!_projectIdToTrackerMap.TryGetValue(projectReference.ProjectId, out var state)) { return null; } return state.GetPartialMetadataReference(fromProject, projectReference); } public async Task<bool> ContainsSymbolsWithNameAsync(ProjectId id, string name, SymbolFilter filter, CancellationToken cancellationToken) { var result = GetCompilationTracker(id).ContainsSymbolsWithNameFromDeclarationOnlyCompilation(name, filter, cancellationToken); if (result.HasValue) { return result.Value; } // it looks like declaration compilation doesn't exist yet. we have to build full compilation var compilation = await GetCompilationAsync(id, cancellationToken).ConfigureAwait(false); if (compilation == null) { // some projects don't support compilations (e.g., TypeScript) so there's nothing to check return false; } return compilation.ContainsSymbolsWithName(name, filter, cancellationToken); } public async Task<bool> ContainsSymbolsWithNameAsync(ProjectId id, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { var result = GetCompilationTracker(id).ContainsSymbolsWithNameFromDeclarationOnlyCompilation(predicate, filter, cancellationToken); if (result.HasValue) { return result.Value; } // it looks like declaration compilation doesn't exist yet. we have to build full compilation var compilation = await GetCompilationAsync(id, cancellationToken).ConfigureAwait(false); if (compilation == null) { // some projects don't support compilations (e.g., TypeScript) so there's nothing to check return false; } return compilation.ContainsSymbolsWithName(predicate, filter, cancellationToken); } public async Task<ImmutableArray<DocumentState>> GetDocumentsWithNameAsync( ProjectId id, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { // this will be used to find documents that contain declaration information in IDE cache such as DeclarationSyntaxTreeInfo for "NavigateTo" var trees = GetCompilationTracker(id).GetSyntaxTreesWithNameFromDeclarationOnlyCompilation(predicate, filter, cancellationToken); if (trees != null) { return ConvertTreesToDocuments(id, trees); } // it looks like declaration compilation doesn't exist yet. we have to build full compilation var compilation = await GetCompilationAsync(id, cancellationToken).ConfigureAwait(false); if (compilation == null) { // some projects don't support compilations (e.g., TypeScript) so there's nothing to check return ImmutableArray<DocumentState>.Empty; } return ConvertTreesToDocuments( id, compilation.GetSymbolsWithName(predicate, filter, cancellationToken).SelectMany(s => s.DeclaringSyntaxReferences.Select(r => r.SyntaxTree))); } private ImmutableArray<DocumentState> ConvertTreesToDocuments(ProjectId id, IEnumerable<SyntaxTree> trees) { var result = ArrayBuilder<DocumentState>.GetInstance(); foreach (var tree in trees) { var document = GetDocumentState(tree, id); if (document == null) { // ignore trees that are not known to solution such as VB synthesized trees made by compilation. continue; } result.Add(document); } return result.ToImmutableAndFree(); } /// <summary> /// Gets a <see cref="ProjectDependencyGraph"/> that details the dependencies between projects for this solution. /// </summary> public ProjectDependencyGraph GetProjectDependencyGraph() => _dependencyGraph; private void CheckNotContainsProject(ProjectId projectId) { if (this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_already_contains_the_specified_project); } } private void CheckContainsProject(ProjectId projectId) { if (!this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_does_not_contain_the_specified_project); } } internal bool ContainsProjectReference(ProjectId projectId, ProjectReference projectReference) => GetRequiredProjectState(projectId).ProjectReferences.Contains(projectReference); internal bool ContainsMetadataReference(ProjectId projectId, MetadataReference metadataReference) => GetRequiredProjectState(projectId).MetadataReferences.Contains(metadataReference); internal bool ContainsAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) => GetRequiredProjectState(projectId).AnalyzerReferences.Contains(analyzerReference); internal bool ContainsTransitiveReference(ProjectId fromProjectId, ProjectId toProjectId) => _dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(fromProjectId).Contains(toProjectId); internal ImmutableHashSet<string> GetRemoteSupportedProjectLanguages() => _remoteSupportedLanguages; private static ImmutableHashSet<string> GetRemoteSupportedProjectLanguages(ImmutableDictionary<ProjectId, ProjectState> projectStates) { var builder = ImmutableHashSet.CreateBuilder<string>(); foreach (var projectState in projectStates) { if (RemoteSupportedLanguages.IsSupported(projectState.Value.Language)) { builder.Add(projectState.Value.Language); } } return builder.ToImmutable(); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicClassification.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicClassification : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicClassification(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicClassification)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void Verify_Color_Of_Some_Tokens() { VisualStudio.Editor.SetText(@"Imports System Imports MathAlias = System.Math Namespace Acme ''' <summary>innertext ''' </summary> ''' <!--comment--> ''' <![CDATA[cdata]]> ''' <typeparam name=""attribute"" /> Public Class Program Public Shared Sub Main(args As String()) Console.WriteLine(""Hello World"") 'comment End Sub End Class End Namespace"); VisualStudio.Editor.PlaceCaret("MathAlias"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "identifier"); VisualStudio.Editor.PlaceCaret("Namespace"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "keyword"); VisualStudio.Editor.PlaceCaret("summary"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "xml doc comment - name"); VisualStudio.Editor.PlaceCaret("innertext"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "xml doc comment - text"); VisualStudio.Editor.PlaceCaret("!--"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "xml doc comment - delimiter"); VisualStudio.Editor.PlaceCaret("comment"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "xml doc comment - comment"); VisualStudio.Editor.PlaceCaret("CDATA"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "xml doc comment - delimiter"); VisualStudio.Editor.PlaceCaret("cdata"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "xml doc comment - cdata section"); VisualStudio.Editor.PlaceCaret("attribute"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "identifier"); VisualStudio.Editor.PlaceCaret("Class"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "keyword"); VisualStudio.Editor.PlaceCaret("Program"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "class name"); VisualStudio.Editor.PlaceCaret("Hello"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "string"); VisualStudio.Editor.PlaceCaret("comment"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "comment"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void Semantic_Classification() { VisualStudio.Editor.SetText(@" Imports System Class Goo Inherits Attribute End Class"); VisualStudio.Editor.PlaceCaret("Goo"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "class name"); VisualStudio.Editor.PlaceCaret("Attribute"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "class name"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicClassification : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicClassification(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicClassification)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void Verify_Color_Of_Some_Tokens() { VisualStudio.Editor.SetText(@"Imports System Imports MathAlias = System.Math Namespace Acme ''' <summary>innertext ''' </summary> ''' <!--comment--> ''' <![CDATA[cdata]]> ''' <typeparam name=""attribute"" /> Public Class Program Public Shared Sub Main(args As String()) Console.WriteLine(""Hello World"") 'comment End Sub End Class End Namespace"); VisualStudio.Editor.PlaceCaret("MathAlias"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "identifier"); VisualStudio.Editor.PlaceCaret("Namespace"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "keyword"); VisualStudio.Editor.PlaceCaret("summary"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "xml doc comment - name"); VisualStudio.Editor.PlaceCaret("innertext"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "xml doc comment - text"); VisualStudio.Editor.PlaceCaret("!--"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "xml doc comment - delimiter"); VisualStudio.Editor.PlaceCaret("comment"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "xml doc comment - comment"); VisualStudio.Editor.PlaceCaret("CDATA"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "xml doc comment - delimiter"); VisualStudio.Editor.PlaceCaret("cdata"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "xml doc comment - cdata section"); VisualStudio.Editor.PlaceCaret("attribute"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "identifier"); VisualStudio.Editor.PlaceCaret("Class"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "keyword"); VisualStudio.Editor.PlaceCaret("Program"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "class name"); VisualStudio.Editor.PlaceCaret("Hello"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "string"); VisualStudio.Editor.PlaceCaret("comment"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "comment"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void Semantic_Classification() { VisualStudio.Editor.SetText(@" Imports System Class Goo Inherits Attribute End Class"); VisualStudio.Editor.PlaceCaret("Goo"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "class name"); VisualStudio.Editor.PlaceCaret("Attribute"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "class name"); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Workspaces/CSharp/Portable/FindSymbols/CSharpDeclaredSymbolInfoFactoryService.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.Composition; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.FindSymbols { [ExportLanguageService(typeof(IDeclaredSymbolInfoFactoryService), LanguageNames.CSharp), Shared] internal class CSharpDeclaredSymbolInfoFactoryService : AbstractDeclaredSymbolInfoFactoryService< CompilationUnitSyntax, UsingDirectiveSyntax, BaseNamespaceDeclarationSyntax, TypeDeclarationSyntax, EnumDeclarationSyntax, MemberDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpDeclaredSymbolInfoFactoryService() { } private static ImmutableArray<string> GetInheritanceNames(StringTable stringTable, BaseListSyntax baseList) { if (baseList == null) { return ImmutableArray<string>.Empty; } var builder = ArrayBuilder<string>.GetInstance(baseList.Types.Count); // It's not sufficient to just store the textual names we see in the inheritance list // of a type. For example if we have: // // using Y = X; // ... // using Z = Y; // ... // class C : Z // // It's insufficient to just state that 'C' derives from 'Z'. If we search for derived // types from 'B' we won't examine 'C'. To solve this, we keep track of the aliasing // that occurs in containing scopes. Then, when we're adding an inheritance name we // walk the alias maps and we also add any names that these names alias to. In the // above example we'd put Z, Y, and X in the inheritance names list for 'C'. // Each dictionary in this list is a mapping from alias name to the name of the thing // it aliases. Then, each scope with alias mapping gets its own entry in this list. // For the above example, we would produce: [{Z => Y}, {Y => X}] var aliasMaps = AllocateAliasMapList(); try { AddAliasMaps(baseList, aliasMaps); foreach (var baseType in baseList.Types) { AddInheritanceName(builder, baseType.Type, aliasMaps); } Intern(stringTable, builder); return builder.ToImmutableAndFree(); } finally { FreeAliasMapList(aliasMaps); } } private static void AddAliasMaps(SyntaxNode node, List<Dictionary<string, string>> aliasMaps) { for (var current = node; current != null; current = current.Parent) { if (current is BaseNamespaceDeclarationSyntax nsDecl) { ProcessUsings(aliasMaps, nsDecl.Usings); } else if (current.IsKind(SyntaxKind.CompilationUnit, out CompilationUnitSyntax compilationUnit)) { ProcessUsings(aliasMaps, compilationUnit.Usings); } } } private static void ProcessUsings(List<Dictionary<string, string>> aliasMaps, SyntaxList<UsingDirectiveSyntax> usings) { Dictionary<string, string> aliasMap = null; foreach (var usingDecl in usings) { if (usingDecl.Alias != null) { var mappedName = GetTypeName(usingDecl.Name); if (mappedName != null) { aliasMap ??= AllocateAliasMap(); // If we have: using X = Goo, then we store a mapping from X -> Goo // here. That way if we see a class that inherits from X we also state // that it inherits from Goo as well. aliasMap[usingDecl.Alias.Name.Identifier.ValueText] = mappedName; } } } if (aliasMap != null) { aliasMaps.Add(aliasMap); } } private static void AddInheritanceName( ArrayBuilder<string> builder, TypeSyntax type, List<Dictionary<string, string>> aliasMaps) { var name = GetTypeName(type); if (name != null) { // First, add the name that the typename that the type directly says it inherits from. builder.Add(name); // Now, walk the alias chain and add any names this alias may eventually map to. var currentName = name; foreach (var aliasMap in aliasMaps) { if (aliasMap.TryGetValue(currentName, out var mappedName)) { // Looks like this could be an alias. Also include the name the alias points to builder.Add(mappedName); // Keep on searching. An alias in an inner namespcae can refer to an // alias in an outer namespace. currentName = mappedName; } } } } protected override void AddDeclaredSymbolInfosWorker( SyntaxNode container, MemberDeclarationSyntax node, StringTable stringTable, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken) { // If this is a part of partial type that only contains nested types, then we don't make an info type for // it. That's because we effectively think of this as just being a virtual container just to hold the nested // types, and not something someone would want to explicitly navigate to itself. Similar to how we think of // namespaces. if (node is TypeDeclarationSyntax typeDeclaration && typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword) && typeDeclaration.Members.Any() && typeDeclaration.Members.All(m => m is BaseTypeDeclarationSyntax)) { return; } switch (node.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: var typeDecl = (TypeDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, typeDecl.Identifier.ValueText, GetTypeParameterSuffix(typeDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, typeDecl.Modifiers.Any(SyntaxKind.PartialKeyword), node.Kind() switch { SyntaxKind.ClassDeclaration => DeclaredSymbolInfoKind.Class, SyntaxKind.RecordDeclaration => DeclaredSymbolInfoKind.Record, SyntaxKind.InterfaceDeclaration => DeclaredSymbolInfoKind.Interface, SyntaxKind.StructDeclaration => DeclaredSymbolInfoKind.Struct, SyntaxKind.RecordStructDeclaration => DeclaredSymbolInfoKind.RecordStruct, _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }, GetAccessibility(container, typeDecl.Modifiers), typeDecl.Identifier.Span, GetInheritanceNames(stringTable, typeDecl.BaseList), IsNestedType(typeDecl))); return; case SyntaxKind.EnumDeclaration: var enumDecl = (EnumDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumDecl.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, enumDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Enum, GetAccessibility(container, enumDecl.Modifiers), enumDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, isNestedType: IsNestedType(enumDecl))); return; case SyntaxKind.ConstructorDeclaration: var ctorDecl = (ConstructorDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, ctorDecl.Identifier.ValueText, GetConstructorSuffix(ctorDecl), containerDisplayName, fullyQualifiedContainerName, ctorDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Constructor, GetAccessibility(container, ctorDecl.Modifiers), ctorDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, parameterCount: ctorDecl.ParameterList?.Parameters.Count ?? 0)); return; case SyntaxKind.DelegateDeclaration: var delegateDecl = (DelegateDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, delegateDecl.Identifier.ValueText, GetTypeParameterSuffix(delegateDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, delegateDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Delegate, GetAccessibility(container, delegateDecl.Modifiers), delegateDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.EnumMemberDeclaration: var enumMember = (EnumMemberDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumMember.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, enumMember.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.EnumMember, Accessibility.Public, enumMember.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.EventDeclaration: var eventDecl = (EventDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, eventDecl.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, eventDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Event, GetAccessibility(container, eventDecl.Modifiers), eventDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.IndexerDeclaration: var indexerDecl = (IndexerDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, "this", GetIndexerSuffix(indexerDecl), containerDisplayName, fullyQualifiedContainerName, indexerDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Indexer, GetAccessibility(container, indexerDecl.Modifiers), indexerDecl.ThisKeyword.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)node; var isExtensionMethod = IsExtensionMethod(method); declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, method.Identifier.ValueText, GetMethodSuffix(method), containerDisplayName, fullyQualifiedContainerName, method.Modifiers.Any(SyntaxKind.PartialKeyword), isExtensionMethod ? DeclaredSymbolInfoKind.ExtensionMethod : DeclaredSymbolInfoKind.Method, GetAccessibility(container, method.Modifiers), method.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, parameterCount: method.ParameterList?.Parameters.Count ?? 0, typeParameterCount: method.TypeParameterList?.Parameters.Count ?? 0)); if (isExtensionMethod) AddExtensionMethodInfo(method, aliases, declaredSymbolInfos.Count - 1, extensionMethodInfo); return; case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, property.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, property.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Property, GetAccessibility(container, property.Modifiers), property.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: var fieldDeclaration = (BaseFieldDeclarationSyntax)node; foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) { var kind = fieldDeclaration is EventFieldDeclarationSyntax ? DeclaredSymbolInfoKind.Event : fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword) ? DeclaredSymbolInfoKind.Constant : DeclaredSymbolInfoKind.Field; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, variableDeclarator.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, fieldDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword), kind, GetAccessibility(container, fieldDeclaration.Modifiers), variableDeclarator.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); } return; } } protected override SyntaxList<MemberDeclarationSyntax> GetChildren(CompilationUnitSyntax node) => node.Members; protected override SyntaxList<MemberDeclarationSyntax> GetChildren(BaseNamespaceDeclarationSyntax node) => node.Members; protected override SyntaxList<MemberDeclarationSyntax> GetChildren(TypeDeclarationSyntax node) => node.Members; protected override IEnumerable<MemberDeclarationSyntax> GetChildren(EnumDeclarationSyntax node) => node.Members; protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(CompilationUnitSyntax node) => node.Usings; protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(BaseNamespaceDeclarationSyntax node) => node.Usings; private static bool IsNestedType(BaseTypeDeclarationSyntax typeDecl) => typeDecl.Parent is BaseTypeDeclarationSyntax; private static string GetConstructorSuffix(ConstructorDeclarationSyntax constructor) => constructor.Modifiers.Any(SyntaxKind.StaticKeyword) ? ".static " + constructor.Identifier + "()" : GetSuffix('(', ')', constructor.ParameterList.Parameters); private static string GetMethodSuffix(MethodDeclarationSyntax method) => GetTypeParameterSuffix(method.TypeParameterList) + GetSuffix('(', ')', method.ParameterList.Parameters); private static string GetIndexerSuffix(IndexerDeclarationSyntax indexer) => GetSuffix('[', ']', indexer.ParameterList.Parameters); private static string GetTypeParameterSuffix(TypeParameterListSyntax typeParameterList) { if (typeParameterList == null) { return null; } var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append('<'); var first = true; foreach (var parameter in typeParameterList.Parameters) { if (!first) { builder.Append(", "); } builder.Append(parameter.Identifier.Text); first = false; } builder.Append('>'); return pooledBuilder.ToStringAndFree(); } /// <summary> /// Builds up the suffix to show for something with parameters in navigate-to. /// While it would be nice to just use the compiler SymbolDisplay API for this, /// it would be too expensive as it requires going back to Symbols (which requires /// creating compilations, etc.) in a perf sensitive area. /// /// So, instead, we just build a reasonable suffix using the pure syntax that a /// user provided. That means that if they wrote "Method(System.Int32 i)" we'll /// show that as "Method(System.Int32)" not "Method(int)". Given that this is /// actually what the user wrote, and it saves us from ever having to go back to /// symbols/compilations, this is well worth it, even if it does mean we have to /// create our own 'symbol display' logic here. /// </summary> private static string GetSuffix( char openBrace, char closeBrace, SeparatedSyntaxList<ParameterSyntax> parameters) { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(openBrace); AppendParameters(parameters, builder); builder.Append(closeBrace); return pooledBuilder.ToStringAndFree(); } private static void AppendParameters(SeparatedSyntaxList<ParameterSyntax> parameters, StringBuilder builder) { var first = true; foreach (var parameter in parameters) { if (!first) { builder.Append(", "); } foreach (var modifier in parameter.Modifiers) { builder.Append(modifier.Text); builder.Append(' '); } if (parameter.Type != null) { AppendTokens(parameter.Type, builder); } else { builder.Append(parameter.Identifier.Text); } first = false; } } protected override string GetContainerDisplayName(MemberDeclarationSyntax node) => CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters); protected override string GetFullyQualifiedContainerName(MemberDeclarationSyntax node, string rootNamespace) => CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeNamespaces); private static Accessibility GetAccessibility(SyntaxNode container, SyntaxTokenList modifiers) { var sawInternal = false; foreach (var modifier in modifiers) { switch (modifier.Kind()) { case SyntaxKind.PublicKeyword: return Accessibility.Public; case SyntaxKind.PrivateKeyword: return Accessibility.Private; case SyntaxKind.ProtectedKeyword: return Accessibility.Protected; case SyntaxKind.InternalKeyword: sawInternal = true; continue; } } if (sawInternal) return Accessibility.Internal; // No accessibility modifiers: switch (container.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: // Anything without modifiers is private if it's in a class/struct declaration. return Accessibility.Private; case SyntaxKind.InterfaceDeclaration: // Anything without modifiers is public if it's in an interface declaration. return Accessibility.Public; case SyntaxKind.CompilationUnit: // Things are private by default in script if (((CSharpParseOptions)container.SyntaxTree.Options).Kind == SourceCodeKind.Script) return Accessibility.Private; return Accessibility.Internal; default: // Otherwise it's internal return Accessibility.Internal; } } private static string GetTypeName(TypeSyntax type) { if (type is SimpleNameSyntax simpleName) { return GetSimpleTypeName(simpleName); } else if (type is QualifiedNameSyntax qualifiedName) { return GetSimpleTypeName(qualifiedName.Right); } else if (type is AliasQualifiedNameSyntax aliasName) { return GetSimpleTypeName(aliasName.Name); } return null; } private static string GetSimpleTypeName(SimpleNameSyntax name) => name.Identifier.ValueText; private static bool IsExtensionMethod(MethodDeclarationSyntax method) => method.ParameterList.Parameters.Count > 0 && method.ParameterList.Parameters[0].Modifiers.Any(SyntaxKind.ThisKeyword); // Root namespace is a VB only concept, which basically means root namespace is always global in C#. protected override string GetRootNamespace(CompilationOptions compilationOptions) => string.Empty; protected override bool TryGetAliasesFromUsingDirective( UsingDirectiveSyntax usingDirectiveNode, out ImmutableArray<(string aliasName, string name)> aliases) { if (usingDirectiveNode.Alias != null) { if (TryGetSimpleTypeName(usingDirectiveNode.Alias.Name, typeParameterNames: null, out var aliasName, out _) && TryGetSimpleTypeName(usingDirectiveNode.Name, typeParameterNames: null, out var name, out _)) { aliases = ImmutableArray.Create<(string, string)>((aliasName, name)); return true; } } aliases = default; return false; } protected override string GetReceiverTypeName(MemberDeclarationSyntax node) { var methodDeclaration = (MethodDeclarationSyntax)node; Debug.Assert(IsExtensionMethod(methodDeclaration)); var typeParameterNames = methodDeclaration.TypeParameterList?.Parameters.SelectAsArray(p => p.Identifier.Text); TryGetSimpleTypeName(methodDeclaration.ParameterList.Parameters[0].Type, typeParameterNames, out var targetTypeName, out var isArray); return CreateReceiverTypeString(targetTypeName, isArray); } private static bool TryGetSimpleTypeName(SyntaxNode node, ImmutableArray<string>? typeParameterNames, out string simpleTypeName, out bool isArray) { isArray = false; if (node is TypeSyntax typeNode) { switch (typeNode) { case IdentifierNameSyntax identifierNameNode: // We consider it a complex method if the receiver type is a type parameter. var text = identifierNameNode.Identifier.Text; simpleTypeName = typeParameterNames?.Contains(text) == true ? null : text; return simpleTypeName != null; case ArrayTypeSyntax arrayTypeNode: isArray = true; return TryGetSimpleTypeName(arrayTypeNode.ElementType, typeParameterNames, out simpleTypeName, out _); case GenericNameSyntax genericNameNode: var name = genericNameNode.Identifier.Text; var arity = genericNameNode.Arity; simpleTypeName = arity == 0 ? name : name + ArityUtilities.GetMetadataAritySuffix(arity); return true; case PredefinedTypeSyntax predefinedTypeNode: simpleTypeName = GetSpecialTypeName(predefinedTypeNode); return simpleTypeName != null; case AliasQualifiedNameSyntax aliasQualifiedNameNode: return TryGetSimpleTypeName(aliasQualifiedNameNode.Name, typeParameterNames, out simpleTypeName, out _); case QualifiedNameSyntax qualifiedNameNode: // For an identifier to the right of a '.', it can't be a type parameter, // so we don't need to check for it further. return TryGetSimpleTypeName(qualifiedNameNode.Right, typeParameterNames: null, out simpleTypeName, out _); case NullableTypeSyntax nullableNode: // Ignore nullability, becase nullable reference type might not be enabled universally. // In the worst case we just include more methods to check in out filter. return TryGetSimpleTypeName(nullableNode.ElementType, typeParameterNames, out simpleTypeName, out isArray); case TupleTypeSyntax tupleType: simpleTypeName = CreateValueTupleTypeString(tupleType.Elements.Count); return true; } } simpleTypeName = null; return false; } private static string GetSpecialTypeName(PredefinedTypeSyntax predefinedTypeNode) { var kind = predefinedTypeNode.Keyword.Kind(); return kind switch { SyntaxKind.BoolKeyword => "Boolean", SyntaxKind.ByteKeyword => "Byte", SyntaxKind.SByteKeyword => "SByte", SyntaxKind.ShortKeyword => "Int16", SyntaxKind.UShortKeyword => "UInt16", SyntaxKind.IntKeyword => "Int32", SyntaxKind.UIntKeyword => "UInt32", SyntaxKind.LongKeyword => "Int64", SyntaxKind.ULongKeyword => "UInt64", SyntaxKind.DoubleKeyword => "Double", SyntaxKind.FloatKeyword => "Single", SyntaxKind.DecimalKeyword => "Decimal", SyntaxKind.StringKeyword => "String", SyntaxKind.CharKeyword => "Char", SyntaxKind.ObjectKeyword => "Object", _ => null, }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.FindSymbols { [ExportLanguageService(typeof(IDeclaredSymbolInfoFactoryService), LanguageNames.CSharp), Shared] internal class CSharpDeclaredSymbolInfoFactoryService : AbstractDeclaredSymbolInfoFactoryService< CompilationUnitSyntax, UsingDirectiveSyntax, BaseNamespaceDeclarationSyntax, TypeDeclarationSyntax, EnumDeclarationSyntax, MemberDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpDeclaredSymbolInfoFactoryService() { } private static ImmutableArray<string> GetInheritanceNames(StringTable stringTable, BaseListSyntax baseList) { if (baseList == null) { return ImmutableArray<string>.Empty; } var builder = ArrayBuilder<string>.GetInstance(baseList.Types.Count); // It's not sufficient to just store the textual names we see in the inheritance list // of a type. For example if we have: // // using Y = X; // ... // using Z = Y; // ... // class C : Z // // It's insufficient to just state that 'C' derives from 'Z'. If we search for derived // types from 'B' we won't examine 'C'. To solve this, we keep track of the aliasing // that occurs in containing scopes. Then, when we're adding an inheritance name we // walk the alias maps and we also add any names that these names alias to. In the // above example we'd put Z, Y, and X in the inheritance names list for 'C'. // Each dictionary in this list is a mapping from alias name to the name of the thing // it aliases. Then, each scope with alias mapping gets its own entry in this list. // For the above example, we would produce: [{Z => Y}, {Y => X}] var aliasMaps = AllocateAliasMapList(); try { AddAliasMaps(baseList, aliasMaps); foreach (var baseType in baseList.Types) { AddInheritanceName(builder, baseType.Type, aliasMaps); } Intern(stringTable, builder); return builder.ToImmutableAndFree(); } finally { FreeAliasMapList(aliasMaps); } } private static void AddAliasMaps(SyntaxNode node, List<Dictionary<string, string>> aliasMaps) { for (var current = node; current != null; current = current.Parent) { if (current is BaseNamespaceDeclarationSyntax nsDecl) { ProcessUsings(aliasMaps, nsDecl.Usings); } else if (current.IsKind(SyntaxKind.CompilationUnit, out CompilationUnitSyntax compilationUnit)) { ProcessUsings(aliasMaps, compilationUnit.Usings); } } } private static void ProcessUsings(List<Dictionary<string, string>> aliasMaps, SyntaxList<UsingDirectiveSyntax> usings) { Dictionary<string, string> aliasMap = null; foreach (var usingDecl in usings) { if (usingDecl.Alias != null) { var mappedName = GetTypeName(usingDecl.Name); if (mappedName != null) { aliasMap ??= AllocateAliasMap(); // If we have: using X = Goo, then we store a mapping from X -> Goo // here. That way if we see a class that inherits from X we also state // that it inherits from Goo as well. aliasMap[usingDecl.Alias.Name.Identifier.ValueText] = mappedName; } } } if (aliasMap != null) { aliasMaps.Add(aliasMap); } } private static void AddInheritanceName( ArrayBuilder<string> builder, TypeSyntax type, List<Dictionary<string, string>> aliasMaps) { var name = GetTypeName(type); if (name != null) { // First, add the name that the typename that the type directly says it inherits from. builder.Add(name); // Now, walk the alias chain and add any names this alias may eventually map to. var currentName = name; foreach (var aliasMap in aliasMaps) { if (aliasMap.TryGetValue(currentName, out var mappedName)) { // Looks like this could be an alias. Also include the name the alias points to builder.Add(mappedName); // Keep on searching. An alias in an inner namespcae can refer to an // alias in an outer namespace. currentName = mappedName; } } } } protected override void AddDeclaredSymbolInfosWorker( SyntaxNode container, MemberDeclarationSyntax node, StringTable stringTable, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken) { // If this is a part of partial type that only contains nested types, then we don't make an info type for // it. That's because we effectively think of this as just being a virtual container just to hold the nested // types, and not something someone would want to explicitly navigate to itself. Similar to how we think of // namespaces. if (node is TypeDeclarationSyntax typeDeclaration && typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword) && typeDeclaration.Members.Any() && typeDeclaration.Members.All(m => m is BaseTypeDeclarationSyntax)) { return; } switch (node.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: var typeDecl = (TypeDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, typeDecl.Identifier.ValueText, GetTypeParameterSuffix(typeDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, typeDecl.Modifiers.Any(SyntaxKind.PartialKeyword), node.Kind() switch { SyntaxKind.ClassDeclaration => DeclaredSymbolInfoKind.Class, SyntaxKind.RecordDeclaration => DeclaredSymbolInfoKind.Record, SyntaxKind.InterfaceDeclaration => DeclaredSymbolInfoKind.Interface, SyntaxKind.StructDeclaration => DeclaredSymbolInfoKind.Struct, SyntaxKind.RecordStructDeclaration => DeclaredSymbolInfoKind.RecordStruct, _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }, GetAccessibility(container, typeDecl.Modifiers), typeDecl.Identifier.Span, GetInheritanceNames(stringTable, typeDecl.BaseList), IsNestedType(typeDecl))); return; case SyntaxKind.EnumDeclaration: var enumDecl = (EnumDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumDecl.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, enumDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Enum, GetAccessibility(container, enumDecl.Modifiers), enumDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, isNestedType: IsNestedType(enumDecl))); return; case SyntaxKind.ConstructorDeclaration: var ctorDecl = (ConstructorDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, ctorDecl.Identifier.ValueText, GetConstructorSuffix(ctorDecl), containerDisplayName, fullyQualifiedContainerName, ctorDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Constructor, GetAccessibility(container, ctorDecl.Modifiers), ctorDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, parameterCount: ctorDecl.ParameterList?.Parameters.Count ?? 0)); return; case SyntaxKind.DelegateDeclaration: var delegateDecl = (DelegateDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, delegateDecl.Identifier.ValueText, GetTypeParameterSuffix(delegateDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, delegateDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Delegate, GetAccessibility(container, delegateDecl.Modifiers), delegateDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.EnumMemberDeclaration: var enumMember = (EnumMemberDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumMember.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, enumMember.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.EnumMember, Accessibility.Public, enumMember.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.EventDeclaration: var eventDecl = (EventDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, eventDecl.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, eventDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Event, GetAccessibility(container, eventDecl.Modifiers), eventDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.IndexerDeclaration: var indexerDecl = (IndexerDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, "this", GetIndexerSuffix(indexerDecl), containerDisplayName, fullyQualifiedContainerName, indexerDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Indexer, GetAccessibility(container, indexerDecl.Modifiers), indexerDecl.ThisKeyword.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)node; var isExtensionMethod = IsExtensionMethod(method); declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, method.Identifier.ValueText, GetMethodSuffix(method), containerDisplayName, fullyQualifiedContainerName, method.Modifiers.Any(SyntaxKind.PartialKeyword), isExtensionMethod ? DeclaredSymbolInfoKind.ExtensionMethod : DeclaredSymbolInfoKind.Method, GetAccessibility(container, method.Modifiers), method.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, parameterCount: method.ParameterList?.Parameters.Count ?? 0, typeParameterCount: method.TypeParameterList?.Parameters.Count ?? 0)); if (isExtensionMethod) AddExtensionMethodInfo(method, aliases, declaredSymbolInfos.Count - 1, extensionMethodInfo); return; case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, property.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, property.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Property, GetAccessibility(container, property.Modifiers), property.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: var fieldDeclaration = (BaseFieldDeclarationSyntax)node; foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) { var kind = fieldDeclaration is EventFieldDeclarationSyntax ? DeclaredSymbolInfoKind.Event : fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword) ? DeclaredSymbolInfoKind.Constant : DeclaredSymbolInfoKind.Field; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, variableDeclarator.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, fieldDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword), kind, GetAccessibility(container, fieldDeclaration.Modifiers), variableDeclarator.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); } return; } } protected override SyntaxList<MemberDeclarationSyntax> GetChildren(CompilationUnitSyntax node) => node.Members; protected override SyntaxList<MemberDeclarationSyntax> GetChildren(BaseNamespaceDeclarationSyntax node) => node.Members; protected override SyntaxList<MemberDeclarationSyntax> GetChildren(TypeDeclarationSyntax node) => node.Members; protected override IEnumerable<MemberDeclarationSyntax> GetChildren(EnumDeclarationSyntax node) => node.Members; protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(CompilationUnitSyntax node) => node.Usings; protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(BaseNamespaceDeclarationSyntax node) => node.Usings; private static bool IsNestedType(BaseTypeDeclarationSyntax typeDecl) => typeDecl.Parent is BaseTypeDeclarationSyntax; private static string GetConstructorSuffix(ConstructorDeclarationSyntax constructor) => constructor.Modifiers.Any(SyntaxKind.StaticKeyword) ? ".static " + constructor.Identifier + "()" : GetSuffix('(', ')', constructor.ParameterList.Parameters); private static string GetMethodSuffix(MethodDeclarationSyntax method) => GetTypeParameterSuffix(method.TypeParameterList) + GetSuffix('(', ')', method.ParameterList.Parameters); private static string GetIndexerSuffix(IndexerDeclarationSyntax indexer) => GetSuffix('[', ']', indexer.ParameterList.Parameters); private static string GetTypeParameterSuffix(TypeParameterListSyntax typeParameterList) { if (typeParameterList == null) { return null; } var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append('<'); var first = true; foreach (var parameter in typeParameterList.Parameters) { if (!first) { builder.Append(", "); } builder.Append(parameter.Identifier.Text); first = false; } builder.Append('>'); return pooledBuilder.ToStringAndFree(); } /// <summary> /// Builds up the suffix to show for something with parameters in navigate-to. /// While it would be nice to just use the compiler SymbolDisplay API for this, /// it would be too expensive as it requires going back to Symbols (which requires /// creating compilations, etc.) in a perf sensitive area. /// /// So, instead, we just build a reasonable suffix using the pure syntax that a /// user provided. That means that if they wrote "Method(System.Int32 i)" we'll /// show that as "Method(System.Int32)" not "Method(int)". Given that this is /// actually what the user wrote, and it saves us from ever having to go back to /// symbols/compilations, this is well worth it, even if it does mean we have to /// create our own 'symbol display' logic here. /// </summary> private static string GetSuffix( char openBrace, char closeBrace, SeparatedSyntaxList<ParameterSyntax> parameters) { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(openBrace); AppendParameters(parameters, builder); builder.Append(closeBrace); return pooledBuilder.ToStringAndFree(); } private static void AppendParameters(SeparatedSyntaxList<ParameterSyntax> parameters, StringBuilder builder) { var first = true; foreach (var parameter in parameters) { if (!first) { builder.Append(", "); } foreach (var modifier in parameter.Modifiers) { builder.Append(modifier.Text); builder.Append(' '); } if (parameter.Type != null) { AppendTokens(parameter.Type, builder); } else { builder.Append(parameter.Identifier.Text); } first = false; } } protected override string GetContainerDisplayName(MemberDeclarationSyntax node) => CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters); protected override string GetFullyQualifiedContainerName(MemberDeclarationSyntax node, string rootNamespace) => CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeNamespaces); private static Accessibility GetAccessibility(SyntaxNode container, SyntaxTokenList modifiers) { var sawInternal = false; foreach (var modifier in modifiers) { switch (modifier.Kind()) { case SyntaxKind.PublicKeyword: return Accessibility.Public; case SyntaxKind.PrivateKeyword: return Accessibility.Private; case SyntaxKind.ProtectedKeyword: return Accessibility.Protected; case SyntaxKind.InternalKeyword: sawInternal = true; continue; } } if (sawInternal) return Accessibility.Internal; // No accessibility modifiers: switch (container.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: // Anything without modifiers is private if it's in a class/struct declaration. return Accessibility.Private; case SyntaxKind.InterfaceDeclaration: // Anything without modifiers is public if it's in an interface declaration. return Accessibility.Public; case SyntaxKind.CompilationUnit: // Things are private by default in script if (((CSharpParseOptions)container.SyntaxTree.Options).Kind == SourceCodeKind.Script) return Accessibility.Private; return Accessibility.Internal; default: // Otherwise it's internal return Accessibility.Internal; } } private static string GetTypeName(TypeSyntax type) { if (type is SimpleNameSyntax simpleName) { return GetSimpleTypeName(simpleName); } else if (type is QualifiedNameSyntax qualifiedName) { return GetSimpleTypeName(qualifiedName.Right); } else if (type is AliasQualifiedNameSyntax aliasName) { return GetSimpleTypeName(aliasName.Name); } return null; } private static string GetSimpleTypeName(SimpleNameSyntax name) => name.Identifier.ValueText; private static bool IsExtensionMethod(MethodDeclarationSyntax method) => method.ParameterList.Parameters.Count > 0 && method.ParameterList.Parameters[0].Modifiers.Any(SyntaxKind.ThisKeyword); // Root namespace is a VB only concept, which basically means root namespace is always global in C#. protected override string GetRootNamespace(CompilationOptions compilationOptions) => string.Empty; protected override bool TryGetAliasesFromUsingDirective( UsingDirectiveSyntax usingDirectiveNode, out ImmutableArray<(string aliasName, string name)> aliases) { if (usingDirectiveNode.Alias != null) { if (TryGetSimpleTypeName(usingDirectiveNode.Alias.Name, typeParameterNames: null, out var aliasName, out _) && TryGetSimpleTypeName(usingDirectiveNode.Name, typeParameterNames: null, out var name, out _)) { aliases = ImmutableArray.Create<(string, string)>((aliasName, name)); return true; } } aliases = default; return false; } protected override string GetReceiverTypeName(MemberDeclarationSyntax node) { var methodDeclaration = (MethodDeclarationSyntax)node; Debug.Assert(IsExtensionMethod(methodDeclaration)); var typeParameterNames = methodDeclaration.TypeParameterList?.Parameters.SelectAsArray(p => p.Identifier.Text); TryGetSimpleTypeName(methodDeclaration.ParameterList.Parameters[0].Type, typeParameterNames, out var targetTypeName, out var isArray); return CreateReceiverTypeString(targetTypeName, isArray); } private static bool TryGetSimpleTypeName(SyntaxNode node, ImmutableArray<string>? typeParameterNames, out string simpleTypeName, out bool isArray) { isArray = false; if (node is TypeSyntax typeNode) { switch (typeNode) { case IdentifierNameSyntax identifierNameNode: // We consider it a complex method if the receiver type is a type parameter. var text = identifierNameNode.Identifier.Text; simpleTypeName = typeParameterNames?.Contains(text) == true ? null : text; return simpleTypeName != null; case ArrayTypeSyntax arrayTypeNode: isArray = true; return TryGetSimpleTypeName(arrayTypeNode.ElementType, typeParameterNames, out simpleTypeName, out _); case GenericNameSyntax genericNameNode: var name = genericNameNode.Identifier.Text; var arity = genericNameNode.Arity; simpleTypeName = arity == 0 ? name : name + ArityUtilities.GetMetadataAritySuffix(arity); return true; case PredefinedTypeSyntax predefinedTypeNode: simpleTypeName = GetSpecialTypeName(predefinedTypeNode); return simpleTypeName != null; case AliasQualifiedNameSyntax aliasQualifiedNameNode: return TryGetSimpleTypeName(aliasQualifiedNameNode.Name, typeParameterNames, out simpleTypeName, out _); case QualifiedNameSyntax qualifiedNameNode: // For an identifier to the right of a '.', it can't be a type parameter, // so we don't need to check for it further. return TryGetSimpleTypeName(qualifiedNameNode.Right, typeParameterNames: null, out simpleTypeName, out _); case NullableTypeSyntax nullableNode: // Ignore nullability, becase nullable reference type might not be enabled universally. // In the worst case we just include more methods to check in out filter. return TryGetSimpleTypeName(nullableNode.ElementType, typeParameterNames, out simpleTypeName, out isArray); case TupleTypeSyntax tupleType: simpleTypeName = CreateValueTupleTypeString(tupleType.Elements.Count); return true; } } simpleTypeName = null; return false; } private static string GetSpecialTypeName(PredefinedTypeSyntax predefinedTypeNode) { var kind = predefinedTypeNode.Keyword.Kind(); return kind switch { SyntaxKind.BoolKeyword => "Boolean", SyntaxKind.ByteKeyword => "Byte", SyntaxKind.SByteKeyword => "SByte", SyntaxKind.ShortKeyword => "Int16", SyntaxKind.UShortKeyword => "UInt16", SyntaxKind.IntKeyword => "Int32", SyntaxKind.UIntKeyword => "UInt32", SyntaxKind.LongKeyword => "Int64", SyntaxKind.ULongKeyword => "UInt64", SyntaxKind.DoubleKeyword => "Double", SyntaxKind.FloatKeyword => "Single", SyntaxKind.DecimalKeyword => "Decimal", SyntaxKind.StringKeyword => "String", SyntaxKind.CharKeyword => "Char", SyntaxKind.ObjectKeyword => "Object", _ => null, }; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Tools/ExternalAccess/Razor/Remote/RazorRemoteServiceCallbackDispatcher.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.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal abstract class RazorRemoteServiceCallbackDispatcher : IRemoteServiceCallbackDispatcher { private readonly RemoteServiceCallbackDispatcher _dispatcher = new(); public object GetCallback(RazorRemoteServiceCallbackIdWrapper callbackId) => _dispatcher.GetCallback(callbackId.UnderlyingObject); RemoteServiceCallbackDispatcher.Handle IRemoteServiceCallbackDispatcher.CreateHandle(object? instance) => _dispatcher.CreateHandle(instance); } }
// Licensed to the .NET Foundation under one or more 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.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal abstract class RazorRemoteServiceCallbackDispatcher : IRemoteServiceCallbackDispatcher { private readonly RemoteServiceCallbackDispatcher _dispatcher = new(); public object GetCallback(RazorRemoteServiceCallbackIdWrapper callbackId) => _dispatcher.GetCallback(callbackId.UnderlyingObject); RemoteServiceCallbackDispatcher.Handle IRemoteServiceCallbackDispatcher.CreateHandle(object? instance) => _dispatcher.CreateHandle(instance); } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.Editor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType { internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> { /// <summary> /// An abstract class for different edits performed by the Move Type Code Action. /// </summary> private abstract class Editor { public Editor( TService service, State state, string fileName, CancellationToken cancellationToken) { State = state; Service = service; FileName = fileName; CancellationToken = cancellationToken; } protected State State { get; } protected TService Service { get; } protected string FileName { get; } protected CancellationToken CancellationToken { get; } protected SemanticDocument SemanticDocument => State.SemanticDocument; /// <summary> /// Operations performed by CodeAction. /// </summary> public virtual async Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync() { var solution = await GetModifiedSolutionAsync().ConfigureAwait(false); if (solution == null) { return ImmutableArray<CodeActionOperation>.Empty; } return ImmutableArray.Create<CodeActionOperation>(new ApplyChangesOperation(solution)); } /// <summary> /// Incremental solution edits that correlate to code operations /// </summary> public abstract Task<Solution> GetModifiedSolutionAsync(); public static Editor GetEditor(MoveTypeOperationKind operationKind, TService service, State state, string fileName, CancellationToken cancellationToken) => operationKind switch { MoveTypeOperationKind.MoveType => new MoveTypeEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.RenameType => new RenameTypeEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.RenameFile => new RenameFileEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.MoveTypeNamespaceScope => new MoveTypeNamespaceScopeEditor(service, state, fileName, cancellationToken), _ => throw ExceptionUtilities.UnexpectedValue(operationKind), }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType { internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> { /// <summary> /// An abstract class for different edits performed by the Move Type Code Action. /// </summary> private abstract class Editor { public Editor( TService service, State state, string fileName, CancellationToken cancellationToken) { State = state; Service = service; FileName = fileName; CancellationToken = cancellationToken; } protected State State { get; } protected TService Service { get; } protected string FileName { get; } protected CancellationToken CancellationToken { get; } protected SemanticDocument SemanticDocument => State.SemanticDocument; /// <summary> /// Operations performed by CodeAction. /// </summary> public virtual async Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync() { var solution = await GetModifiedSolutionAsync().ConfigureAwait(false); if (solution == null) { return ImmutableArray<CodeActionOperation>.Empty; } return ImmutableArray.Create<CodeActionOperation>(new ApplyChangesOperation(solution)); } /// <summary> /// Incremental solution edits that correlate to code operations /// </summary> public abstract Task<Solution> GetModifiedSolutionAsync(); public static Editor GetEditor(MoveTypeOperationKind operationKind, TService service, State state, string fileName, CancellationToken cancellationToken) => operationKind switch { MoveTypeOperationKind.MoveType => new MoveTypeEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.RenameType => new RenameTypeEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.RenameFile => new RenameFileEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.MoveTypeNamespaceScope => new MoveTypeNamespaceScopeEditor(service, state, fileName, cancellationToken), _ => throw ExceptionUtilities.UnexpectedValue(operationKind), }; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/VisualStudio/Core/Def/xlf/ServicesVSResources.ru.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="ru" original="../ServicesVSResources.resx"> <body> <trans-unit id="A_new_namespace_will_be_created"> <source>A new namespace will be created</source> <target state="translated">Будет создано пространство имен</target> <note /> </trans-unit> <trans-unit id="A_type_and_name_must_be_provided"> <source>A type and name must be provided.</source> <target state="translated">Следует указать тип и имя.</target> <note /> </trans-unit> <trans-unit id="Action"> <source>Action</source> <target state="translated">Действие</target> <note>Action to perform on an unused reference, such as remove or keep</note> </trans-unit> <trans-unit id="Add"> <source>_Add</source> <target state="translated">Д_обавить</target> <note>Adding an element to a list</note> </trans-unit> <trans-unit id="Add_Parameter"> <source>Add Parameter</source> <target state="translated">Добавить параметр</target> <note /> </trans-unit> <trans-unit id="Add_to_current_file"> <source>Add to _current file</source> <target state="translated">Добавить в _текущий файл</target> <note /> </trans-unit> <trans-unit id="Added_Parameter"> <source>Added parameter.</source> <target state="translated">Добавлен параметр.</target> <note /> </trans-unit> <trans-unit id="Additional_changes_are_needed_to_complete_the_refactoring_Review_changes_below"> <source>Additional changes are needed to complete the refactoring. Review changes below.</source> <target state="translated">Для завершения рефакторинга требуется внести дополнительные изменения. Просмотрите их ниже.</target> <note /> </trans-unit> <trans-unit id="All_methods"> <source>All methods</source> <target state="translated">Все методы</target> <note /> </trans-unit> <trans-unit id="All_sources"> <source>All sources</source> <target state="translated">Все источники</target> <note /> </trans-unit> <trans-unit id="Allow_colon"> <source>Allow:</source> <target state="translated">Разрешить:</target> <note /> </trans-unit> <trans-unit id="Allow_multiple_blank_lines"> <source>Allow multiple blank lines</source> <target state="translated">Разрешать несколько пустых строк</target> <note /> </trans-unit> <trans-unit id="Allow_statement_immediately_after_block"> <source>Allow statement immediately after block</source> <target state="translated">Разрешать помещать оператор сразу же после блока</target> <note /> </trans-unit> <trans-unit id="Always_for_clarity"> <source>Always for clarity</source> <target state="translated">Всегда использовать для ясности</target> <note /> </trans-unit> <trans-unit id="Analyzer_Defaults"> <source>Analyzer Defaults</source> <target state="new">Analyzer Defaults</target> <note /> </trans-unit> <trans-unit id="Analyzers"> <source>Analyzers</source> <target state="translated">Анализаторы</target> <note /> </trans-unit> <trans-unit id="Analyzing_project_references"> <source>Analyzing project references...</source> <target state="translated">Анализ ссылок проекта…</target> <note /> </trans-unit> <trans-unit id="Apply"> <source>Apply</source> <target state="translated">Применить</target> <note /> </trans-unit> <trans-unit id="Apply_0_keymapping_scheme"> <source>Apply '{0}' keymapping scheme</source> <target state="translated">Применить схему назначения клавиш "{0}"</target> <note /> </trans-unit> <trans-unit id="Assemblies"> <source>Assemblies</source> <target state="translated">Сборки</target> <note /> </trans-unit> <trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value"> <source>Avoid expression statements that implicitly ignore value</source> <target state="translated">Избегайте операторов-выражений, неявно игнорирующих значение.</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_parameters"> <source>Avoid unused parameters</source> <target state="translated">Избегайте неиспользуемых параметров.</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_value_assignments"> <source>Avoid unused value assignments</source> <target state="translated">Избегайте присваивания неиспользуемых значений.</target> <note /> </trans-unit> <trans-unit id="Back"> <source>Back</source> <target state="translated">Назад</target> <note /> </trans-unit> <trans-unit id="Background_analysis_scope_colon"> <source>Background analysis scope:</source> <target state="translated">Область фонового анализа:</target> <note /> </trans-unit> <trans-unit id="Bitness32"> <source>32-bit</source> <target state="translated">32-разрядный</target> <note /> </trans-unit> <trans-unit id="Bitness64"> <source>64-bit</source> <target state="translated">64-разрядный</target> <note /> </trans-unit> <trans-unit id="Build_plus_live_analysis_NuGet_package"> <source>Build + live analysis (NuGet package)</source> <target state="translated">Сборка и динамический анализ (пакет NuGet)</target> <note /> </trans-unit> <trans-unit id="CSharp_Visual_Basic_Diagnostics_Language_Client"> <source>C#/Visual Basic Diagnostics Language Client</source> <target state="translated">Языковой клиент диагностики C#/Visual Basic</target> <note /> </trans-unit> <trans-unit id="Calculating"> <source>Calculating...</source> <target state="new">Calculating...</target> <note>Used in UI to represent progress in the context of loading items. </note> </trans-unit> <trans-unit id="Calculating_dependents"> <source>Calculating dependents...</source> <target state="translated">Вычисление зависимостей…</target> <note /> </trans-unit> <trans-unit id="Call_site_value"> <source>Call site value:</source> <target state="translated">Значение места вызова:</target> <note /> </trans-unit> <trans-unit id="Callsite"> <source>Call site</source> <target state="translated">Место вызова</target> <note /> </trans-unit> <trans-unit id="Carriage_Return_Newline_rn"> <source>Carriage Return + Newline (\r\n)</source> <target state="translated">Возврат каретки + символ новой строки (\r\n)</target> <note /> </trans-unit> <trans-unit id="Carriage_Return_r"> <source>Carriage Return (\r)</source> <target state="translated">Возврат каретки (\r)</target> <note /> </trans-unit> <trans-unit id="Category"> <source>Category</source> <target state="translated">Категория</target> <note /> </trans-unit> <trans-unit id="Choose_which_action_you_would_like_to_perform_on_the_unused_references"> <source>Choose which action you would like to perform on the unused references.</source> <target state="translated">Выберите действие, которое необходимо выполнить для неиспользуемых ссылок.</target> <note /> </trans-unit> <trans-unit id="Code_Style"> <source>Code Style</source> <target state="translated">Стиль кода</target> <note /> </trans-unit> <trans-unit id="Code_analysis_completed_for_0"> <source>Code analysis completed for '{0}'.</source> <target state="translated">Анализ кода для "{0}" выполнен.</target> <note /> </trans-unit> <trans-unit id="Code_analysis_completed_for_Solution"> <source>Code analysis completed for Solution.</source> <target state="translated">Анализ кода для решения выполнен.</target> <note /> </trans-unit> <trans-unit id="Code_analysis_terminated_before_completion_for_0"> <source>Code analysis terminated before completion for '{0}'.</source> <target state="translated">Анализ кода прерван до завершения "{0}".</target> <note /> </trans-unit> <trans-unit id="Code_analysis_terminated_before_completion_for_Solution"> <source>Code analysis terminated before completion for Solution.</source> <target state="translated">Анализ кода прерван до завершения решения.</target> <note /> </trans-unit> <trans-unit id="Color_hints"> <source>Color hints</source> <target state="translated">Цветовые подсказки</target> <note /> </trans-unit> <trans-unit id="Colorize_regular_expressions"> <source>Colorize regular expressions</source> <target state="translated">Выделить регулярные выражения цветом</target> <note /> </trans-unit> <trans-unit id="Comments"> <source>Comments</source> <target state="translated">Комментарии</target> <note /> </trans-unit> <trans-unit id="Compute_Quick_Actions_asynchronously_experimental"> <source>Compute Quick Actions asynchronously (experimental, requires restart)</source> <target state="new">Compute Quick Actions asynchronously (experimental, requires restart)</target> <note /> </trans-unit> <trans-unit id="Containing_member"> <source>Containing Member</source> <target state="translated">Содержащий член</target> <note /> </trans-unit> <trans-unit id="Containing_type"> <source>Containing Type</source> <target state="translated">Содержащий тип</target> <note /> </trans-unit> <trans-unit id="Current_document"> <source>Current document</source> <target state="translated">Текущий документ</target> <note /> </trans-unit> <trans-unit id="Current_parameter"> <source>Current parameter</source> <target state="translated">Текущий параметр</target> <note /> </trans-unit> <trans-unit id="Default_Current_Document"> <source>Default (Current Document)</source> <target state="new">Default (Current Document)</target> <note>This text is a menu command</note> </trans-unit> <trans-unit id="Default_Entire_Solution"> <source>Default (Entire Solution)</source> <target state="new">Default (Entire Solution)</target> <note>This text is a menu command</note> </trans-unit> <trans-unit id="Default_Open_Documents"> <source>Default (Open Documents)</source> <target state="new">Default (Open Documents)</target> <note>This text is a menu command</note> </trans-unit> <trans-unit id="Derived_types"> <source>Derived types</source> <target state="new">Derived types</target> <note /> </trans-unit> <trans-unit id="Disabled"> <source>Disabled</source> <target state="translated">Отключено</target> <note /> </trans-unit> <trans-unit id="Display_all_hints_while_pressing_Alt_F1"> <source>Display all hints while pressing Alt+F1</source> <target state="translated">Отображать все подсказки при нажатии клавиш ALT+F1</target> <note /> </trans-unit> <trans-unit id="Display_inline_parameter_name_hints"> <source>Disp_lay inline parameter name hints</source> <target state="translated">Отображать п_одсказки для имен встроенных параметров</target> <note /> </trans-unit> <trans-unit id="Display_inline_type_hints"> <source>Display inline type hints</source> <target state="translated">Отображать подсказки для встроенных типов</target> <note /> </trans-unit> <trans-unit id="Edit"> <source>_Edit</source> <target state="translated">_Изменить</target> <note /> </trans-unit> <trans-unit id="Edit_0"> <source>Edit {0}</source> <target state="translated">Изменить {0}</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Editor_Color_Scheme"> <source>Editor Color Scheme</source> <target state="translated">Цветовая схема редактора</target> <note /> </trans-unit> <trans-unit id="Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page"> <source>Editor color scheme options are only available when using a color theme bundled with Visual Studio. The color theme can be configured from the Environment &gt; General options page.</source> <target state="translated">Параметры цветовой схемы редактора доступны только при использовании цветовой темы, поставляемой вместе с Visual Studio. Цветовую тему можно настроить на странице "Среда" &gt; "Общие параметры".</target> <note /> </trans-unit> <trans-unit id="Element_is_not_valid"> <source>Element is not valid.</source> <target state="translated">Элемент недопустим.</target> <note /> </trans-unit> <trans-unit id="Enable_Razor_pull_diagnostics_experimental_requires_restart"> <source>Enable Razor 'pull' diagnostics (experimental, requires restart)</source> <target state="translated">Включить диагностику "pull" Razor (экспериментальная функция, требуется перезапуск)</target> <note /> </trans-unit> <trans-unit id="Enable_all_features_in_opened_files_from_source_generators_experimental"> <source>Enable all features in opened files from source generators (experimental)</source> <target state="translated">Включить все функции в открытых файлах из генераторов источника (экспериментальная версия)</target> <note /> </trans-unit> <trans-unit id="Enable_file_logging_for_diagnostics"> <source>Enable file logging for diagnostics (logged in '%Temp%\Roslyn' folder)</source> <target state="translated">Включить ведение журнала файлов для диагностики (в папке "%Temp%\Roslyn")</target> <note /> </trans-unit> <trans-unit id="Enable_pull_diagnostics_experimental_requires_restart"> <source>Enable 'pull' diagnostics (experimental, requires restart)</source> <target state="translated">Включить диагностику "pull" (экспериментальная функция, требуется перезапуск)</target> <note /> </trans-unit> <trans-unit id="Enabled"> <source>Enabled</source> <target state="translated">Включено</target> <note /> </trans-unit> <trans-unit id="Enter_a_call_site_value_or_choose_a_different_value_injection_kind"> <source>Enter a call site value or choose a different value injection kind</source> <target state="translated">Введите значение места вызова или выберите другой тип введения значения</target> <note /> </trans-unit> <trans-unit id="Entire_repository"> <source>Entire repository</source> <target state="translated">Весь репозиторий</target> <note /> </trans-unit> <trans-unit id="Entire_solution"> <source>Entire solution</source> <target state="translated">Все решение</target> <note /> </trans-unit> <trans-unit id="Error"> <source>Error</source> <target state="translated">Ошибка</target> <note /> </trans-unit> <trans-unit id="Error_updating_suppressions_0"> <source>Error updating suppressions: {0}</source> <target state="translated">Ошибка при обновлении подавлений: {0}</target> <note /> </trans-unit> <trans-unit id="Evaluating_0_tasks_in_queue"> <source>Evaluating ({0} tasks in queue)</source> <target state="translated">Оценка (задач в очереди: {0})</target> <note /> </trans-unit> <trans-unit id="Extract_Base_Class"> <source>Extract Base Class</source> <target state="translated">Извлечь базовый класс</target> <note /> </trans-unit> <trans-unit id="Finish"> <source>Finish</source> <target state="translated">Готово</target> <note /> </trans-unit> <trans-unit id="Format_document"> <source>Format document</source> <target state="translated">Форматировать документ</target> <note /> </trans-unit> <trans-unit id="Generate_dot_editorconfig_file_from_settings"> <source>Generate .editorconfig file from settings</source> <target state="translated">Создать файл EDITORCONFIG на основе параметров</target> <note /> </trans-unit> <trans-unit id="Highlight_related_components_under_cursor"> <source>Highlight related components under cursor</source> <target state="translated">Выделить связанные компоненты под курсором</target> <note /> </trans-unit> <trans-unit id="Id"> <source>Id</source> <target state="translated">ИД</target> <note /> </trans-unit> <trans-unit id="Implemented_interfaces"> <source>Implemented interfaces</source> <target state="new">Implemented interfaces</target> <note /> </trans-unit> <trans-unit id="Implemented_members"> <source>Implemented members</source> <target state="translated">Реализованные элементы</target> <note /> </trans-unit> <trans-unit id="Implementing_members"> <source>Implementing members</source> <target state="translated">Реализация элементов</target> <note /> </trans-unit> <trans-unit id="Implementing_types"> <source>Implementing types</source> <target state="new">Implementing types</target> <note /> </trans-unit> <trans-unit id="In_other_operators"> <source>In other operators</source> <target state="translated">В других операторах</target> <note /> </trans-unit> <trans-unit id="Index"> <source>Index</source> <target state="translated">Индекс</target> <note>Index of parameter in original signature</note> </trans-unit> <trans-unit id="Infer_from_context"> <source>Infer from context</source> <target state="translated">Вывести из контекста</target> <note /> </trans-unit> <trans-unit id="Indexed_in_organization"> <source>Indexed in organization</source> <target state="translated">Индексированный в организации</target> <note /> </trans-unit> <trans-unit id="Indexed_in_repo"> <source>Indexed in repo</source> <target state="translated">Индексированный в репозитории</target> <note /> </trans-unit> <trans-unit id="Inheritance_Margin_experimental"> <source>Inheritance Margin (experimental)</source> <target state="translated">Граница наследования (экспериментальная)</target> <note /> </trans-unit> <trans-unit id="Inherited_interfaces"> <source>Inherited interfaces</source> <target state="new">Inherited interfaces</target> <note /> </trans-unit> <trans-unit id="Inline_Hints_experimental"> <source>Inline Hints (experimental)</source> <target state="translated">Встроенные подсказки (экспериментальная функция)</target> <note /> </trans-unit> <trans-unit id="Inserting_call_site_value_0"> <source>Inserting call site value '{0}'</source> <target state="translated">Вставка значения "{0}" места вызова</target> <note /> </trans-unit> <trans-unit id="Install_Microsoft_recommended_Roslyn_analyzers_which_provide_additional_diagnostics_and_fixes_for_common_API_design_security_performance_and_reliability_issues"> <source>Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues</source> <target state="translated">Установите рекомендуемые корпорацией Майкрософт анализаторы Roslyn, которые предоставляют дополнительные средства диагностики и исправления для распространенных проблем, связанных с разработкой, безопасностью, производительностью и надежностью API.</target> <note /> </trans-unit> <trans-unit id="Interface_cannot_have_field"> <source>Interface cannot have field.</source> <target state="translated">Интерфейс не может содержать поле.</target> <note /> </trans-unit> <trans-unit id="IntroduceUndefinedTodoVariables"> <source>Introduce undefined TODO variables</source> <target state="translated">Ввести неопределенные переменные TODO</target> <note>"TODO" is an indicator that more work should be done at the location where the TODO is inserted</note> </trans-unit> <trans-unit id="Item_origin"> <source>Item origin</source> <target state="translated">Источник элемента</target> <note /> </trans-unit> <trans-unit id="Keep"> <source>Keep</source> <target state="translated">Сохранить</target> <note /> </trans-unit> <trans-unit id="Keep_all_parentheses_in_colon"> <source>Keep all parentheses in:</source> <target state="translated">Сохранять все круглые скобки в:</target> <note /> </trans-unit> <trans-unit id="Kind"> <source>Kind</source> <target state="translated">Вид</target> <note /> </trans-unit> <trans-unit id="Language_client_initialization_failed"> <source>{0} failed to initialize. Status = {1}. Exception = {2}</source> <target state="new">{0} failed to initialize. Status = {1}. Exception = {2}</target> <note>{0} is the language server name. Status is the status of the initialization. Exception is the exception encountered during initialization.</note> </trans-unit> <trans-unit id="Live_analysis_VSIX_extension"> <source>Live analysis (VSIX extension)</source> <target state="translated">Динамический анализ (расширение VSIX)</target> <note /> </trans-unit> <trans-unit id="Loaded_items"> <source>Loaded items</source> <target state="translated">Загруженные элементы</target> <note /> </trans-unit> <trans-unit id="Loaded_solution"> <source>Loaded solution</source> <target state="translated">Загруженное решение</target> <note /> </trans-unit> <trans-unit id="Local"> <source>Local</source> <target state="translated">Локальное</target> <note /> </trans-unit> <trans-unit id="Local_metadata"> <source>Local metadata</source> <target state="translated">Локальные метаданные</target> <note /> </trans-unit> <trans-unit id="Location"> <source>Location</source> <target state="new">Location</target> <note /> </trans-unit> <trans-unit id="Make_0_abstract"> <source>Make '{0}' abstract</source> <target state="translated">Сделать "{0}" абстрактным</target> <note /> </trans-unit> <trans-unit id="Make_abstract"> <source>Make abstract</source> <target state="translated">Сделать абстрактным</target> <note /> </trans-unit> <trans-unit id="Members"> <source>Members</source> <target state="translated">Члены</target> <note /> </trans-unit> <trans-unit id="Modifier_preferences_colon"> <source>Modifier preferences:</source> <target state="translated">Предпочтения модификатора:</target> <note /> </trans-unit> <trans-unit id="Move_to_namespace"> <source>Move to Namespace</source> <target state="translated">Переместить в пространство имен</target> <note /> </trans-unit> <trans-unit id="Multiple_members_are_inherited"> <source>Multiple members are inherited</source> <target state="translated">Несколько элементов наследуются</target> <note /> </trans-unit> <trans-unit id="Multiple_members_are_inherited_on_line_0"> <source>Multiple members are inherited on line {0}</source> <target state="translated">Несколько элементов наследуются в строке {0}</target> <note>Line number info is needed for accessibility purpose.</note> </trans-unit> <trans-unit id="Name_conflicts_with_an_existing_type_name"> <source>Name conflicts with an existing type name.</source> <target state="translated">Имя конфликтует с существующим именем типа.</target> <note /> </trans-unit> <trans-unit id="Name_is_not_a_valid_0_identifier"> <source>Name is not a valid {0} identifier.</source> <target state="translated">Имя не является допустимым идентификатором {0}.</target> <note /> </trans-unit> <trans-unit id="Namespace"> <source>Namespace</source> <target state="translated">Пространство имен</target> <note /> </trans-unit> <trans-unit id="Namespace_0"> <source>Namespace: '{0}'</source> <target state="translated">Пространство имен: "{0}"</target> <note /> </trans-unit> <trans-unit id="Namespace_declarations"> <source>Namespace declarations</source> <target state="new">Namespace declarations</target> <note /> </trans-unit> <trans-unit id="Namespaces_have_been_updated"> <source>Namespaces have been updated.</source> <target state="new">Namespaces have been updated.</target> <note>"Namespaces" is the programming language concept</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Class"> <source>class</source> <target state="new">class</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Delegate"> <source>delegate</source> <target state="new">delegate</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Enum"> <source>enum</source> <target state="new">enum</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Event"> <source>event</source> <target state="new">event</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Field"> <source>field</source> <target state="translated">Поле</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Interface"> <source>interface</source> <target state="new">interface</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Local"> <source>local</source> <target state="translated">локальный</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable".</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_LocalFunction"> <source>local function</source> <target state="translated">локальная функция</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Method"> <source>method</source> <target state="translated">метод</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Namespace"> <source>namespace</source> <target state="new">namespace</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Parameter"> <source>parameter</source> <target state="translated">параметр</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Property"> <source>property</source> <target state="translated">свойство</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Struct"> <source>struct</source> <target state="new">struct</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_TypeParameter"> <source>type parameter</source> <target state="translated">параметр типа</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Class"> <source>Class</source> <target state="new">Class</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Delegate"> <source>Delegate</source> <target state="new">Delegate</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Enum"> <source>Enum</source> <target state="new">Enum</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Event"> <source>Event</source> <target state="new">Event</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Field"> <source>Field</source> <target state="translated">Поле</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Interface"> <source>Interface</source> <target state="new">Interface</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Local"> <source>Local</source> <target state="translated">Локальные</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Method"> <source>Method</source> <target state="translated">метод</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Module"> <source>Module</source> <target state="new">Module</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Namespace"> <source>Namespace</source> <target state="new">Namespace</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Parameter"> <source>Parameter</source> <target state="translated">Параметр</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method.</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Property"> <source>Property</source> <target state="new">Property</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Structure"> <source>Structure</source> <target state="new">Structure</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_TypeParameter"> <source>Type Parameter</source> <target state="translated">Параметр типа</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter".</note> </trans-unit> <trans-unit id="Naming_rules"> <source>Naming rules</source> <target state="translated">Правила именования</target> <note /> </trans-unit> <trans-unit id="Navigate_to_0"> <source>Navigate to '{0}'</source> <target state="translated">Перейти к {0}</target> <note /> </trans-unit> <trans-unit id="Never_if_unnecessary"> <source>Never if unnecessary</source> <target state="translated">Никогда, если не требуется</target> <note /> </trans-unit> <trans-unit id="New_Type_Name_colon"> <source>New Type Name:</source> <target state="translated">Новое имя типа:</target> <note /> </trans-unit> <trans-unit id="New_line_preferences_experimental_colon"> <source>New line preferences (experimental):</source> <target state="translated">Предпочтения для новых строк (экспериментальная функция):</target> <note /> </trans-unit> <trans-unit id="Newline_n"> <source>Newline (\\n)</source> <target state="translated">Новая строка (\\n)</target> <note /> </trans-unit> <trans-unit id="No_namespaces_needed_updating"> <source>No namespaces needed updating.</source> <target state="new">No namespaces needed updating.</target> <note>"Namespaces" is the programming language concept</note> </trans-unit> <trans-unit id="No_unused_references_were_found"> <source>No unused references were found.</source> <target state="translated">Неиспользуемые ссылки не найдены.</target> <note /> </trans-unit> <trans-unit id="Non_public_methods"> <source>Non-public methods</source> <target state="translated">Методы, не являющиеся открытыми</target> <note /> </trans-unit> <trans-unit id="None"> <source>None</source> <target state="translated">NONE</target> <note /> </trans-unit> <trans-unit id="Omit_only_for_optional_parameters"> <source>Omit (only for optional parameters)</source> <target state="translated">Опустить (только для необязательных параметров)</target> <note /> </trans-unit> <trans-unit id="Open_documents"> <source>Open documents</source> <target state="translated">Открыть документы</target> <note /> </trans-unit> <trans-unit id="Optional_parameters_must_provide_a_default_value"> <source>Optional parameters must provide a default value</source> <target state="translated">Для необязательных параметров необходимо указать значение по умолчанию.</target> <note /> </trans-unit> <trans-unit id="Optional_with_default_value_colon"> <source>Optional with default value:</source> <target state="translated">Необязательный параметр со значением по умолчанию:</target> <note /> </trans-unit> <trans-unit id="Other"> <source>Others</source> <target state="translated">Другие</target> <note /> </trans-unit> <trans-unit id="Overridden_members"> <source>Overridden members</source> <target state="translated">Переопределенные элементы</target> <note /> </trans-unit> <trans-unit id="Overriding_members"> <source>Overriding members</source> <target state="translated">Идет переопределение элементов</target> <note /> </trans-unit> <trans-unit id="Package_install_canceled"> <source>Package install canceled</source> <target state="new">Package install canceled</target> <note /> </trans-unit> <trans-unit id="Package_uninstall_canceled"> <source>Package uninstall canceled</source> <target state="new">Package uninstall canceled</target> <note /> </trans-unit> <trans-unit id="Packages"> <source>Packages</source> <target state="translated">Пакеты</target> <note /> </trans-unit> <trans-unit id="Parameter_Details"> <source>Parameter Details</source> <target state="translated">Дополнительные сведения о параметрах</target> <note /> </trans-unit> <trans-unit id="Parameter_Name"> <source>Parameter name:</source> <target state="translated">Имя параметра:</target> <note /> </trans-unit> <trans-unit id="Parameter_information"> <source>Parameter information</source> <target state="translated">Сведения о параметре</target> <note /> </trans-unit> <trans-unit id="Parameter_kind"> <source>Parameter kind</source> <target state="translated">Тип параметра</target> <note /> </trans-unit> <trans-unit id="Parameter_name_contains_invalid_characters"> <source>Parameter name contains invalid character(s).</source> <target state="translated">Имя параметра содержит недопустимые знаки.</target> <note /> </trans-unit> <trans-unit id="Parameter_preferences_colon"> <source>Parameter preferences:</source> <target state="translated">Предпочтения для параметров:</target> <note /> </trans-unit> <trans-unit id="Parameter_type_contains_invalid_characters"> <source>Parameter type contains invalid character(s).</source> <target state="translated">Тип параметра содержит недопустимые знаки.</target> <note /> </trans-unit> <trans-unit id="Parentheses_preferences_colon"> <source>Parentheses preferences:</source> <target state="translated">Параметры круглых скобок:</target> <note /> </trans-unit> <trans-unit id="Paused_0_tasks_in_queue"> <source>Paused ({0} tasks in queue)</source> <target state="translated">Приостановлено (задач в очереди: {0})</target> <note /> </trans-unit> <trans-unit id="Please_enter_a_type_name"> <source>Please enter a type name</source> <target state="translated">Введите имя типа</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Prefer_System_HashCode_in_GetHashCode"> <source>Prefer 'System.HashCode' in 'GetHashCode'</source> <target state="translated">Предпочитать "System.HashCode" в "GetHashCode"</target> <note /> </trans-unit> <trans-unit id="Prefer_compound_assignments"> <source>Prefer compound assignments</source> <target state="translated">Предпочитать составные назначения</target> <note /> </trans-unit> <trans-unit id="Prefer_index_operator"> <source>Prefer index operator</source> <target state="translated">Предпочитать оператор index</target> <note /> </trans-unit> <trans-unit id="Prefer_range_operator"> <source>Prefer range operator</source> <target state="translated">Предпочитать оператор range</target> <note /> </trans-unit> <trans-unit id="Prefer_readonly_fields"> <source>Prefer readonly fields</source> <target state="translated">Предпочитать поля только для чтения</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_using_statement"> <source>Prefer simple 'using' statement</source> <target state="translated">Предпочитать простой оператор using</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_boolean_expressions"> <source>Prefer simplified boolean expressions</source> <target state="translated">Предпочитать упрощенные логические выражения</target> <note /> </trans-unit> <trans-unit id="Prefer_static_local_functions"> <source>Prefer static local functions</source> <target state="translated">Предпочитать статические локальные функции</target> <note /> </trans-unit> <trans-unit id="Projects"> <source>Projects</source> <target state="translated">Проекты</target> <note /> </trans-unit> <trans-unit id="Pull_Members_Up"> <source>Pull Members Up</source> <target state="translated">Повышение элементов</target> <note /> </trans-unit> <trans-unit id="Quick_Actions"> <source>Quick Actions</source> <target state="new">Quick Actions</target> <note /> </trans-unit> <trans-unit id="Refactoring_Only"> <source>Refactoring Only</source> <target state="translated">Только рефакторинг</target> <note /> </trans-unit> <trans-unit id="Reference"> <source>Reference</source> <target state="translated">Ссылка</target> <note /> </trans-unit> <trans-unit id="Regular_Expressions"> <source>Regular Expressions</source> <target state="translated">Регулярные выражения</target> <note /> </trans-unit> <trans-unit id="Remove_All"> <source>Remove All</source> <target state="translated">Удалить все</target> <note /> </trans-unit> <trans-unit id="Remove_Unused_References"> <source>Remove Unused References</source> <target state="translated">Удалить неиспользуемые ссылки</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1"> <source>Rename {0} to {1}</source> <target state="translated">Переименовать {0} в {1}</target> <note /> </trans-unit> <trans-unit id="Report_invalid_regular_expressions"> <source>Report invalid regular expressions</source> <target state="translated">Сообщать о недопустимых регулярных выражениях</target> <note /> </trans-unit> <trans-unit id="Repository"> <source>Repository</source> <target state="translated">Репозиторий</target> <note /> </trans-unit> <trans-unit id="Require_colon"> <source>Require:</source> <target state="translated">Обязательно:</target> <note /> </trans-unit> <trans-unit id="Required"> <source>Required</source> <target state="translated">Обязательный параметр</target> <note /> </trans-unit> <trans-unit id="Requires_System_HashCode_be_present_in_project"> <source>Requires 'System.HashCode' be present in project</source> <target state="translated">Требуется наличие "System.HashCode" в проекте.</target> <note /> </trans-unit> <trans-unit id="Reset_Visual_Studio_default_keymapping"> <source>Reset Visual Studio default keymapping</source> <target state="translated">Сброс схемы назначения клавиш Visual Studio по умолчанию</target> <note /> </trans-unit> <trans-unit id="Review_Changes"> <source>Review Changes</source> <target state="translated">Проверить изменения</target> <note /> </trans-unit> <trans-unit id="Run_Code_Analysis_on_0"> <source>Run Code Analysis on {0}</source> <target state="translated">Запустить Code Analysis для {0}</target> <note /> </trans-unit> <trans-unit id="Run_code_analysis_in_separate_process_requires_restart"> <source>Run code analysis in separate process (requires restart)</source> <target state="new">Run code analysis in separate process (requires restart)</target> <note /> </trans-unit> <trans-unit id="Running_code_analysis_for_0"> <source>Running code analysis for '{0}'...</source> <target state="translated">Выполняется анализ кода для "{0}"…</target> <note /> </trans-unit> <trans-unit id="Running_code_analysis_for_Solution"> <source>Running code analysis for Solution...</source> <target state="translated">Выполняется анализ кода для решения…</target> <note /> </trans-unit> <trans-unit id="Running_low_priority_background_processes"> <source>Running low priority background processes</source> <target state="translated">Запуск фоновых процессов с низким приоритетом</target> <note /> </trans-unit> <trans-unit id="Save_dot_editorconfig_file"> <source>Save .editorconfig file</source> <target state="translated">Сохранить файл EDITORCONFIG</target> <note /> </trans-unit> <trans-unit id="Search_Settings"> <source>Search Settings</source> <target state="translated">Параметры поиска</target> <note /> </trans-unit> <trans-unit id="Select_an_appropriate_symbol_to_start_value_tracking"> <source>Select an appropriate symbol to start value tracking</source> <target state="new">Select an appropriate symbol to start value tracking</target> <note /> </trans-unit> <trans-unit id="Select_destination"> <source>Select destination</source> <target state="translated">Выбрать место назначения</target> <note /> </trans-unit> <trans-unit id="Select_Dependents"> <source>Select _Dependents</source> <target state="translated">Выбрать _зависимости</target> <note /> </trans-unit> <trans-unit id="Select_Public"> <source>Select _Public</source> <target state="translated">Выбрать _открытые</target> <note /> </trans-unit> <trans-unit id="Select_destination_and_members_to_pull_up"> <source>Select destination and members to pull up.</source> <target state="translated">Выбрать место назначения и повышаемые в иерархии элементы.</target> <note /> </trans-unit> <trans-unit id="Select_destination_colon"> <source>Select destination:</source> <target state="translated">Выбрать место назначения:</target> <note /> </trans-unit> <trans-unit id="Select_member"> <source>Select member</source> <target state="translated">Выбрать элемент</target> <note /> </trans-unit> <trans-unit id="Select_members_colon"> <source>Select members:</source> <target state="translated">Выбрать элементы:</target> <note /> </trans-unit> <trans-unit id="Show_Remove_Unused_References_command_in_Solution_Explorer_experimental"> <source>Show "Remove Unused References" command in Solution Explorer (experimental)</source> <target state="translated">Показать команду "Удалить неиспользуемые ссылки" в Обозревателе решений (экспериментальная версия)</target> <note /> </trans-unit> <trans-unit id="Show_completion_list"> <source>Show completion list</source> <target state="translated">Показать список завершения</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_everything_else"> <source>Show hints for everything else</source> <target state="translated">Отображать подсказки для всех остальных элементов</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_implicit_object_creation"> <source>Show hints for implicit object creation</source> <target state="translated">Показать указания для неявного создания объекта</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_indexers"> <source>Show hints for indexers</source> <target state="new">Show hints for indexers</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_lambda_parameter_types"> <source>Show hints for lambda parameter types</source> <target state="translated">Отображать подсказки для типов лямбда-параметров</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_literals"> <source>Show hints for literals</source> <target state="translated">Отображать подсказки для литералов</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_variables_with_inferred_types"> <source>Show hints for variables with inferred types</source> <target state="translated">Отображать подсказки для переменных с выводимыми типами</target> <note /> </trans-unit> <trans-unit id="Show_inheritance_margin"> <source>Show inheritance margin</source> <target state="translated">Показать границу наследования</target> <note /> </trans-unit> <trans-unit id="Skip_analyzers_for_implicitly_triggered_builds"> <source>Skip analyzers for implicitly triggered builds</source> <target state="new">Skip analyzers for implicitly triggered builds</target> <note /> </trans-unit> <trans-unit id="Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations"> <source>Some color scheme colors are being overridden by changes made in the Environment &gt; Fonts and Colors options page. Choose `Use Defaults` in the Fonts and Colors page to revert all customizations.</source> <target state="translated">Некоторые цвета цветовой схемы переопределяются изменениями, сделанными на странице "Среда" &gt; "Шрифты и цвета". Выберите "Использовать значения по умолчанию" на странице "Шрифты и цвета", чтобы отменить все настройки.</target> <note /> </trans-unit> <trans-unit id="Suggestion"> <source>Suggestion</source> <target state="translated">Рекомендация</target> <note /> </trans-unit> <trans-unit id="Suppress_hints_when_parameter_name_matches_the_method_s_intent"> <source>Suppress hints when parameter name matches the method's intent</source> <target state="translated">Скрывать подсказки, если имя параметра соответствует намерению метода.</target> <note /> </trans-unit> <trans-unit id="Suppress_hints_when_parameter_names_differ_only_by_suffix"> <source>Suppress hints when parameter names differ only by suffix</source> <target state="translated">Скрывать подсказки, если имена параметров различаются только суффиксом.</target> <note /> </trans-unit> <trans-unit id="Symbols_without_references"> <source>Symbols without references</source> <target state="translated">Символы без ссылок</target> <note /> </trans-unit> <trans-unit id="Sync_Namespaces"> <source>Sync Namespaces</source> <target state="new">Sync Namespaces</target> <note>"Namespaces" is the programming language concept</note> </trans-unit> <trans-unit id="Tab_twice_to_insert_arguments"> <source>Tab twice to insert arguments (experimental)</source> <target state="translated">Дважды нажмите клавишу TAB, чтобы вставить аргументы (экспериментальная функция)</target> <note /> </trans-unit> <trans-unit id="Target_Namespace_colon"> <source>Target Namespace:</source> <target state="translated">Целевое пространство имен:</target> <note /> </trans-unit> <trans-unit id="The_generator_0_that_generated_this_file_has_been_removed_from_the_project"> <source>The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project.</source> <target state="translated">Генератор "{0}", создавший этот файл, был удален из проекта; этот файл больше не включен в проект.</target> <note /> </trans-unit> <trans-unit id="The_generator_0_that_generated_this_file_has_stopped_generating_this_file"> <source>The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project.</source> <target state="translated">Генератор "{0}", создавший этот файл, остановил создание этого файла; этот файл больше не включен в проект.</target> <note /> </trans-unit> <trans-unit id="This_action_cannot_be_undone_Do_you_wish_to_continue"> <source>This action cannot be undone. Do you wish to continue?</source> <target state="translated">Это действие не может быть отменено. Вы хотите продолжить?</target> <note /> </trans-unit> <trans-unit id="This_file_is_autogenerated_by_0_and_cannot_be_edited"> <source>This file is auto-generated by the generator '{0}' and cannot be edited.</source> <target state="translated">Этот файл создан автоматически генератором "{0}" и не может быть изменен.</target> <note /> </trans-unit> <trans-unit id="This_is_an_invalid_namespace"> <source>This is an invalid namespace</source> <target state="translated">Это недопустимое пространство имен.</target> <note /> </trans-unit> <trans-unit id="Title"> <source>Title</source> <target state="translated">Название</target> <note /> </trans-unit> <trans-unit id="Type_Name"> <source>Type name:</source> <target state="translated">Имя типа:</target> <note /> </trans-unit> <trans-unit id="Type_name_has_a_syntax_error"> <source>Type name has a syntax error</source> <target state="translated">Имя типа содержит синтаксическую ошибку.</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Type_name_is_not_recognized"> <source>Type name is not recognized</source> <target state="translated">Не удалось распознать имя типа.</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Type_name_is_recognized"> <source>Type name is recognized</source> <target state="translated">Имя типа распознано.</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Underline_reassigned_variables"> <source>Underline reassigned variables</source> <target state="new">Underline reassigned variables</target> <note /> </trans-unit> <trans-unit id="Unused_value_is_explicitly_assigned_to_an_unused_local"> <source>Unused value is explicitly assigned to an unused local</source> <target state="translated">Неиспользуемое значение явным образом задано неиспользуемой локальной переменной.</target> <note /> </trans-unit> <trans-unit id="Unused_value_is_explicitly_assigned_to_discard"> <source>Unused value is explicitly assigned to discard</source> <target state="translated">Неиспользуемое значение явным образом задано пустой переменной.</target> <note /> </trans-unit> <trans-unit id="Updating_namspaces"> <source>Updating namespaces...</source> <target state="new">Updating namespaces...</target> <note>"namespaces" is the programming language concept</note> </trans-unit> <trans-unit id="Updating_project_references"> <source>Updating project references...</source> <target state="translated">Обновление ссылок проекта…</target> <note /> </trans-unit> <trans-unit id="Updating_severity"> <source>Updating severity</source> <target state="translated">Обновление уровня серьезности</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_lambdas"> <source>Use expression body for lambdas</source> <target state="translated">Использовать тело выражения для лямбда-выражений</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Использовать тело выражения для локальных функций</target> <note /> </trans-unit> <trans-unit id="Use_named_argument"> <source>Use named argument</source> <target state="translated">Использовать именованный аргумент</target> <note>"argument" is a programming term for a value passed to a function</note> </trans-unit> <trans-unit id="Value"> <source>Value</source> <target state="translated">Значение</target> <note /> </trans-unit> <trans-unit id="Value_Tracking"> <source>Value Tracking</source> <target state="new">Value Tracking</target> <note>Title of the "Value Tracking" tool window. "Value" is the variable/symbol and "Tracking" is the action the tool is doing to follow where the value can originate from.</note> </trans-unit> <trans-unit id="Value_assigned_here_is_never_used"> <source>Value assigned here is never used</source> <target state="translated">Заданное здесь значение не используется.</target> <note /> </trans-unit> <trans-unit id="Value_colon"> <source>Value:</source> <target state="translated">Значение:</target> <note /> </trans-unit> <trans-unit id="Value_returned_by_invocation_is_implicitly_ignored"> <source>Value returned by invocation is implicitly ignored</source> <target state="translated">Значение, возвращаемое вызовом, неявным образом игнорируется.</target> <note /> </trans-unit> <trans-unit id="Value_to_inject_at_call_sites"> <source>Value to inject at call sites</source> <target state="translated">Значение, которое необходимо вставить во все точки вызова</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_2017"> <source>Visual Studio 2017</source> <target state="translated">Visual Studio 2017</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_2019"> <source>Visual Studio 2019</source> <target state="translated">Visual Studio 2019</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_Settings"> <source>Visual Studio Settings</source> <target state="new">Visual Studio Settings</target> <note /> </trans-unit> <trans-unit id="Warning"> <source>Warning</source> <target state="translated">Предупреждение</target> <note /> </trans-unit> <trans-unit id="Warning_colon_duplicate_parameter_name"> <source>Warning: duplicate parameter name</source> <target state="translated">Предупреждение: повторяющееся имя параметра.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_type_does_not_bind"> <source>Warning: type does not bind</source> <target state="translated">Предупреждение: привязка типа невозможна.</target> <note /> </trans-unit> <trans-unit id="We_notice_you_suspended_0_Reset_keymappings_to_continue_to_navigate_and_refactor"> <source>We notice you suspended '{0}'. Reset keymappings to continue to navigate and refactor.</source> <target state="translated">Вы приостановили действие "{0}". Сбросьте назначения клавиш, чтобы продолжить работу и рефакторинг.</target> <note /> </trans-unit> <trans-unit id="This_workspace_does_not_support_updating_Visual_Basic_compilation_options"> <source>This workspace does not support updating Visual Basic compilation options.</source> <target state="translated">Эта рабочая область не поддерживает обновление параметров компиляции Visual Basic.</target> <note /> </trans-unit> <trans-unit id="Whitespace"> <source>Whitespace</source> <target state="new">Whitespace</target> <note /> </trans-unit> <trans-unit id="You_must_change_the_signature"> <source>You must change the signature</source> <target state="translated">Необходимо изменить подпись</target> <note>"signature" here means the definition of a method</note> </trans-unit> <trans-unit id="You_must_select_at_least_one_member"> <source>You must select at least one member.</source> <target state="translated">Необходимо выбрать по крайней мере один элемент.</target> <note /> </trans-unit> <trans-unit id="Illegal_characters_in_path"> <source>Illegal characters in path.</source> <target state="translated">Недопустимые символы в пути.</target> <note /> </trans-unit> <trans-unit id="File_name_must_have_the_0_extension"> <source>File name must have the "{0}" extension.</source> <target state="translated">Файл должен иметь расширение "{0}".</target> <note /> </trans-unit> <trans-unit id="Debugger"> <source>Debugger</source> <target state="translated">Отладчик</target> <note /> </trans-unit> <trans-unit id="Determining_breakpoint_location"> <source>Determining breakpoint location...</source> <target state="translated">Определение положения точки останова...</target> <note /> </trans-unit> <trans-unit id="Determining_autos"> <source>Determining autos...</source> <target state="translated">Определение видимых переменных...</target> <note /> </trans-unit> <trans-unit id="Resolving_breakpoint_location"> <source>Resolving breakpoint location...</source> <target state="translated">Разрешение положения точки останова...</target> <note /> </trans-unit> <trans-unit id="Validating_breakpoint_location"> <source>Validating breakpoint location...</source> <target state="translated">Проверка положения точки останова...</target> <note /> </trans-unit> <trans-unit id="Getting_DataTip_text"> <source>Getting DataTip text...</source> <target state="translated">Получение текста подсказки (DataTip) по данным...</target> <note /> </trans-unit> <trans-unit id="Preview_unavailable"> <source>Preview unavailable</source> <target state="translated">Предпросмотр недоступен.</target> <note /> </trans-unit> <trans-unit id="Overrides_"> <source>Overrides</source> <target state="translated">Переопределяет</target> <note /> </trans-unit> <trans-unit id="Overridden_By"> <source>Overridden By</source> <target state="translated">Переопределяется</target> <note /> </trans-unit> <trans-unit id="Inherits_"> <source>Inherits</source> <target state="translated">Наследует</target> <note /> </trans-unit> <trans-unit id="Inherited_By"> <source>Inherited By</source> <target state="translated">Наследуется</target> <note /> </trans-unit> <trans-unit id="Implements_"> <source>Implements</source> <target state="translated">Реализует</target> <note /> </trans-unit> <trans-unit id="Implemented_By"> <source>Implemented By</source> <target state="translated">Реализуется</target> <note /> </trans-unit> <trans-unit id="Maximum_number_of_documents_are_open"> <source>Maximum number of documents are open.</source> <target state="translated">Открыто предельное число документов.</target> <note /> </trans-unit> <trans-unit id="Failed_to_create_document_in_miscellaneous_files_project"> <source>Failed to create document in miscellaneous files project.</source> <target state="translated">Не удалось создать документ в списке прочих файлов.</target> <note /> </trans-unit> <trans-unit id="Invalid_access"> <source>Invalid access.</source> <target state="translated">Недопустимый доступ.</target> <note /> </trans-unit> <trans-unit id="The_following_references_were_not_found_0_Please_locate_and_add_them_manually"> <source>The following references were not found. {0}Please locate and add them manually.</source> <target state="translated">Не найдены следующие ссылки. {0} Найдите и добавьте их вручную.</target> <note /> </trans-unit> <trans-unit id="End_position_must_be_start_position"> <source>End position must be &gt;= start position</source> <target state="translated">Конечное положение не должно быть меньше начального.</target> <note /> </trans-unit> <trans-unit id="Not_a_valid_value"> <source>Not a valid value</source> <target state="translated">Недопустимое значение</target> <note /> </trans-unit> <trans-unit id="_0_is_inherited"> <source>'{0}' is inherited</source> <target state="translated">"{0}" наследуется</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_abstract"> <source>'{0}' will be changed to abstract.</source> <target state="translated">Элемент "{0}" будет изменен на абстрактный.</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_non_static"> <source>'{0}' will be changed to non-static.</source> <target state="translated">Элемент "{0}" будет изменен на нестатический.</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_public"> <source>'{0}' will be changed to public.</source> <target state="translated">Элемент "{0}" будет изменен на открытый.</target> <note /> </trans-unit> <trans-unit id="generated_by_0_suffix"> <source>[generated by {0}]</source> <target state="translated">[создан генератором {0}]</target> <note>{0} is the name of a generator.</note> </trans-unit> <trans-unit id="generated_suffix"> <source>[generated]</source> <target state="translated">[создан генератором]</target> <note /> </trans-unit> <trans-unit id="given_workspace_doesn_t_support_undo"> <source>given workspace doesn't support undo</source> <target state="translated">заданная рабочая область не поддерживает отмену.</target> <note /> </trans-unit> <trans-unit id="Add_a_reference_to_0"> <source>Add a reference to '{0}'</source> <target state="translated">Добавить ссылку на "{0}"</target> <note /> </trans-unit> <trans-unit id="Event_type_is_invalid"> <source>Event type is invalid</source> <target state="translated">Тип события недопустим.</target> <note /> </trans-unit> <trans-unit id="Can_t_find_where_to_insert_member"> <source>Can't find where to insert member</source> <target state="translated">Не удается найти место вставки элемента.</target> <note /> </trans-unit> <trans-unit id="Can_t_rename_other_elements"> <source>Can't rename 'other' elements</source> <target state="translated">Не удается переименовать элементы "other".</target> <note /> </trans-unit> <trans-unit id="Unknown_rename_type"> <source>Unknown rename type</source> <target state="translated">Неизвестный тип переименования</target> <note /> </trans-unit> <trans-unit id="IDs_are_not_supported_for_this_symbol_type"> <source>IDs are not supported for this symbol type.</source> <target state="translated">Идентификаторы не поддерживаются для данного типа символов.</target> <note /> </trans-unit> <trans-unit id="Can_t_create_a_node_id_for_this_symbol_kind_colon_0"> <source>Can't create a node id for this symbol kind: '{0}'</source> <target state="translated">Не удается создать идентификатор узла для этого вида символов: "{0}".</target> <note /> </trans-unit> <trans-unit id="Project_References"> <source>Project References</source> <target state="translated">Ссылки проекта</target> <note /> </trans-unit> <trans-unit id="Base_Types"> <source>Base Types</source> <target state="translated">Базовые типы</target> <note /> </trans-unit> <trans-unit id="Miscellaneous_Files"> <source>Miscellaneous Files</source> <target state="translated">Прочие файлы</target> <note /> </trans-unit> <trans-unit id="Could_not_find_project_0"> <source>Could not find project '{0}'</source> <target state="translated">Не удалось найти проект "{0}".</target> <note /> </trans-unit> <trans-unit id="Could_not_find_location_of_folder_on_disk"> <source>Could not find location of folder on disk</source> <target state="translated">Не удалось найти путь к папке на диске.</target> <note /> </trans-unit> <trans-unit id="Assembly"> <source>Assembly </source> <target state="translated">Сборка </target> <note /> </trans-unit> <trans-unit id="Exceptions_colon"> <source>Exceptions:</source> <target state="translated">Исключения:</target> <note /> </trans-unit> <trans-unit id="Member_of_0"> <source>Member of {0}</source> <target state="translated">Элемент объекта {0}</target> <note /> </trans-unit> <trans-unit id="Parameters_colon1"> <source>Parameters:</source> <target state="translated">Параметры:</target> <note /> </trans-unit> <trans-unit id="Project"> <source>Project </source> <target state="translated">Проект </target> <note /> </trans-unit> <trans-unit id="Remarks_colon"> <source>Remarks:</source> <target state="translated">Примечания.</target> <note /> </trans-unit> <trans-unit id="Returns_colon"> <source>Returns:</source> <target state="translated">Возврат:</target> <note /> </trans-unit> <trans-unit id="Summary_colon"> <source>Summary:</source> <target state="translated">Сводка:</target> <note /> </trans-unit> <trans-unit id="Type_Parameters_colon"> <source>Type Parameters:</source> <target state="translated">Параметры типа:</target> <note /> </trans-unit> <trans-unit id="File_already_exists"> <source>File already exists</source> <target state="translated">Файл уже существует.</target> <note /> </trans-unit> <trans-unit id="File_path_cannot_use_reserved_keywords"> <source>File path cannot use reserved keywords</source> <target state="translated">В пути к файлу нельзя использовать зарезервированные ключевые слова.</target> <note /> </trans-unit> <trans-unit id="DocumentPath_is_illegal"> <source>DocumentPath is illegal</source> <target state="translated">Параметр DocumentPath недопустим.</target> <note /> </trans-unit> <trans-unit id="Project_Path_is_illegal"> <source>Project Path is illegal</source> <target state="translated">Путь проекта недопустим.</target> <note /> </trans-unit> <trans-unit id="Path_cannot_have_empty_filename"> <source>Path cannot have empty filename</source> <target state="translated">Имя файла в пути не может быть пустым.</target> <note /> </trans-unit> <trans-unit id="The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace"> <source>The given DocumentId did not come from the Visual Studio workspace.</source> <target state="translated">Указанный идентификатор документа DocumentId получен не из рабочей области Visual Studio.</target> <note /> </trans-unit> <trans-unit id="Project_colon_0_1_Use_the_dropdown_to_view_and_switch_to_other_projects_this_file_may_belong_to"> <source>Project: {0} ({1}) Use the dropdown to view and switch to other projects this file may belong to.</source> <target state="translated">Проект: {0} ({1}) Используйте раскрывающийся список для просмотра других проектов, к которым может относиться этот файл, и перехода к ним.</target> <note /> </trans-unit> <trans-unit id="_0_Use_the_dropdown_to_view_and_navigate_to_other_items_in_this_file"> <source>{0} Use the dropdown to view and navigate to other items in this file.</source> <target state="translated">{0} Для просмотра других элементов в этом файле используйте раскрывающийся список.</target> <note /> </trans-unit> <trans-unit id="Project_colon_0_Use_the_dropdown_to_view_and_switch_to_other_projects_this_file_may_belong_to"> <source>Project: {0} Use the dropdown to view and switch to other projects this file may belong to.</source> <target state="translated">Проект: {0} Используйте раскрывающийся список для просмотра других проектов, к которым может относиться этот файл, и перехода к ним.</target> <note /> </trans-unit> <trans-unit id="AnalyzerChangedOnDisk"> <source>AnalyzerChangedOnDisk</source> <target state="translated">AnalyzerChangedOnDisk</target> <note /> </trans-unit> <trans-unit id="The_analyzer_assembly_0_has_changed_Diagnostics_may_be_incorrect_until_Visual_Studio_is_restarted"> <source>The analyzer assembly '{0}' has changed. Diagnostics may be incorrect until Visual Studio is restarted.</source> <target state="translated">Сборка анализатора "{0}" была изменена. Перезапустите Visual Studio, в противном случае диагностика может быть неправильной.</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Diagnostics_Table_Data_Source"> <source>C#/VB Diagnostics Table Data Source</source> <target state="translated">Источник данных для таблицы диагностики C#/VB</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Todo_List_Table_Data_Source"> <source>C#/VB Todo List Table Data Source</source> <target state="translated">Источник данных для таблицы списка задач C#/VB</target> <note /> </trans-unit> <trans-unit id="Cancel"> <source>Cancel</source> <target state="translated">Отмена</target> <note /> </trans-unit> <trans-unit id="Deselect_All"> <source>_Deselect All</source> <target state="translated">_Отменить все</target> <note /> </trans-unit> <trans-unit id="Extract_Interface"> <source>Extract Interface</source> <target state="translated">Извлечь интерфейс</target> <note /> </trans-unit> <trans-unit id="Generated_name_colon"> <source>Generated name:</source> <target state="translated">Созданное название:</target> <note /> </trans-unit> <trans-unit id="New_file_name_colon"> <source>New _file name:</source> <target state="translated">Новое им_я файла:</target> <note /> </trans-unit> <trans-unit id="New_interface_name_colon"> <source>New _interface name:</source> <target state="translated">Новое название _интерфейса:</target> <note /> </trans-unit> <trans-unit id="OK"> <source>OK</source> <target state="translated">ОК</target> <note /> </trans-unit> <trans-unit id="Select_All"> <source>_Select All</source> <target state="translated">В_ыбрать все</target> <note /> </trans-unit> <trans-unit id="Select_public_members_to_form_interface"> <source>Select public _members to form interface</source> <target state="translated">Выбрать открытые _элементы для создания интерфейса</target> <note /> </trans-unit> <trans-unit id="Access_colon"> <source>_Access:</source> <target state="translated">Д_оступ:</target> <note /> </trans-unit> <trans-unit id="Add_to_existing_file"> <source>Add to _existing file</source> <target state="translated">Добавить в _существующий файл</target> <note /> </trans-unit> <trans-unit id="Change_Signature"> <source>Change Signature</source> <target state="translated">Изменить сигнатуру</target> <note /> </trans-unit> <trans-unit id="Create_new_file"> <source>_Create new file</source> <target state="translated">_Создать файл</target> <note /> </trans-unit> <trans-unit id="Default_"> <source>Default</source> <target state="translated">По умолчанию</target> <note /> </trans-unit> <trans-unit id="File_Name_colon"> <source>File Name:</source> <target state="translated">Имя файла:</target> <note /> </trans-unit> <trans-unit id="Generate_Type"> <source>Generate Type</source> <target state="translated">Сформировать тип</target> <note /> </trans-unit> <trans-unit id="Kind_colon"> <source>_Kind:</source> <target state="translated">_Вид:</target> <note /> </trans-unit> <trans-unit id="Location_colon"> <source>Location:</source> <target state="translated">Расположение:</target> <note /> </trans-unit> <trans-unit id="Modifier"> <source>Modifier</source> <target state="translated">Модификатор</target> <note /> </trans-unit> <trans-unit id="Name_colon1"> <source>Name:</source> <target state="translated">Название:</target> <note /> </trans-unit> <trans-unit id="Parameter"> <source>Parameter</source> <target state="translated">Параметр</target> <note /> </trans-unit> <trans-unit id="Parameters_colon2"> <source>Parameters:</source> <target state="translated">Параметры:</target> <note /> </trans-unit> <trans-unit id="Preview_method_signature_colon"> <source>Preview method signature:</source> <target state="translated">Предпросмотр сигнатуры метода:</target> <note /> </trans-unit> <trans-unit id="Preview_reference_changes"> <source>Preview reference changes</source> <target state="translated">Предпросмотр изменений в ссылках</target> <note /> </trans-unit> <trans-unit id="Project_colon"> <source>_Project:</source> <target state="translated">_Проект:</target> <note /> </trans-unit> <trans-unit id="Type"> <source>Type</source> <target state="translated">Тип</target> <note /> </trans-unit> <trans-unit id="Type_Details_colon"> <source>Type Details:</source> <target state="translated">Подробности о типе:</target> <note /> </trans-unit> <trans-unit id="Re_move"> <source>Re_move</source> <target state="translated">Уд_алить</target> <note /> </trans-unit> <trans-unit id="Restore"> <source>_Restore</source> <target state="translated">_Восстановить</target> <note /> </trans-unit> <trans-unit id="More_about_0"> <source>More about {0}</source> <target state="translated">{0}: подробнее</target> <note /> </trans-unit> <trans-unit id="Navigation_must_be_performed_on_the_foreground_thread"> <source>Navigation must be performed on the foreground thread.</source> <target state="translated">Навигация должна осуществляться в потоке переднего плана.</target> <note /> </trans-unit> <trans-unit id="bracket_plus_bracket"> <source>[+] </source> <target state="translated">[+] </target> <note /> </trans-unit> <trans-unit id="bracket_bracket"> <source>[-] </source> <target state="translated">[-] </target> <note /> </trans-unit> <trans-unit id="Reference_to_0_in_project_1"> <source>Reference to '{0}' in project '{1}'</source> <target state="translated">Ссылка на "{0}" в проекте "{1}"</target> <note /> </trans-unit> <trans-unit id="Unknown1"> <source>&lt;Unknown&gt;</source> <target state="translated">&lt;нет данных&gt;</target> <note /> </trans-unit> <trans-unit id="Analyzer_reference_to_0_in_project_1"> <source>Analyzer reference to '{0}' in project '{1}'</source> <target state="translated">Ссылка анализатора на "{0}" в проекте "{1}"</target> <note /> </trans-unit> <trans-unit id="Project_reference_to_0_in_project_1"> <source>Project reference to '{0}' in project '{1}'</source> <target state="translated">Ссылка проекта на "{0}" в проекте "{1}"</target> <note /> </trans-unit> <trans-unit id="AnalyzerDependencyConflict"> <source>AnalyzerDependencyConflict</source> <target state="translated">AnalyzerDependencyConflict</target> <note /> </trans-unit> <trans-unit id="Analyzer_assemblies_0_and_1_both_have_identity_2_but_different_contents_Only_one_will_be_loaded_and_analyzers_using_these_assemblies_may_not_run_correctly"> <source>Analyzer assemblies '{0}' and '{1}' both have identity '{2}' but different contents. Only one will be loaded and analyzers using these assemblies may not run correctly.</source> <target state="translated">Сборки анализатора "{0}" и "{1}" имеют одно и то же удостоверение ("{2}"), но разное содержимое. Будет загружена только одна сборка, и анализаторы, использующие эти сборки, могут работать неправильно.</target> <note /> </trans-unit> <trans-unit id="_0_references"> <source>{0} references</source> <target state="translated">Ссылок: {0}</target> <note /> </trans-unit> <trans-unit id="_1_reference"> <source>1 reference</source> <target state="translated">1 ссылка</target> <note /> </trans-unit> <trans-unit id="_0_encountered_an_error_and_has_been_disabled"> <source>'{0}' encountered an error and has been disabled.</source> <target state="translated">'Произошла ошибка, и анализатор "{0}" отключен.</target> <note /> </trans-unit> <trans-unit id="Enable"> <source>Enable</source> <target state="translated">Включить</target> <note /> </trans-unit> <trans-unit id="Enable_and_ignore_future_errors"> <source>Enable and ignore future errors</source> <target state="translated">Включить и пропускать будущие ошибки</target> <note /> </trans-unit> <trans-unit id="No_Changes"> <source>No Changes</source> <target state="translated">Изменений нет</target> <note /> </trans-unit> <trans-unit id="Current_block"> <source>Current block</source> <target state="translated">Текущий блок</target> <note /> </trans-unit> <trans-unit id="Determining_current_block"> <source>Determining current block.</source> <target state="translated">Определение текущего блока.</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Build_Table_Data_Source"> <source>C#/VB Build Table Data Source</source> <target state="translated">Источник данных для таблицы сборки C#/VB</target> <note /> </trans-unit> <trans-unit id="MissingAnalyzerReference"> <source>MissingAnalyzerReference</source> <target state="translated">MissingAnalyzerReference</target> <note /> </trans-unit> <trans-unit id="Analyzer_assembly_0_depends_on_1_but_it_was_not_found_Analyzers_may_not_run_correctly_unless_the_missing_assembly_is_added_as_an_analyzer_reference_as_well"> <source>Analyzer assembly '{0}' depends on '{1}' but it was not found. Analyzers may not run correctly unless the missing assembly is added as an analyzer reference as well.</source> <target state="translated">Сборка анализатора "{0}" зависит от "{1}", но последняя не найдена. Анализаторы могут работать неправильно, если не добавить отсутствующую сборку в качестве ссылки анализатора.</target> <note /> </trans-unit> <trans-unit id="Suppress_diagnostics"> <source>Suppress diagnostics</source> <target state="translated">Подавление диагностики</target> <note /> </trans-unit> <trans-unit id="Computing_suppressions_fix"> <source>Computing suppressions fix...</source> <target state="translated">Вычисление исправления для подавлений...</target> <note /> </trans-unit> <trans-unit id="Applying_suppressions_fix"> <source>Applying suppressions fix...</source> <target state="translated">Применяется исправление для подавлений...</target> <note /> </trans-unit> <trans-unit id="Remove_suppressions"> <source>Remove suppressions</source> <target state="translated">Удалить подавления</target> <note /> </trans-unit> <trans-unit id="Computing_remove_suppressions_fix"> <source>Computing remove suppressions fix...</source> <target state="translated">Вычисление исправления для удаления подавлений...</target> <note /> </trans-unit> <trans-unit id="Applying_remove_suppressions_fix"> <source>Applying remove suppressions fix...</source> <target state="translated">Применяется исправление для удаления подавлений...</target> <note /> </trans-unit> <trans-unit id="This_workspace_only_supports_opening_documents_on_the_UI_thread"> <source>This workspace only supports opening documents on the UI thread.</source> <target state="translated">Эта рабочая область поддерживает открытие документов только в потоке пользовательского интерфейса.</target> <note /> </trans-unit> <trans-unit id="This_workspace_does_not_support_updating_Visual_Basic_parse_options"> <source>This workspace does not support updating Visual Basic parse options.</source> <target state="translated">Эта рабочая область не поддерживает обновление параметров синтаксического анализа Visual Basic.</target> <note /> </trans-unit> <trans-unit id="Synchronize_0"> <source>Synchronize {0}</source> <target state="translated">Синхронизировать {0}</target> <note /> </trans-unit> <trans-unit id="Synchronizing_with_0"> <source>Synchronizing with {0}...</source> <target state="translated">Синхронизация с {0}...</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_has_suspended_some_advanced_features_to_improve_performance"> <source>Visual Studio has suspended some advanced features to improve performance.</source> <target state="translated">Visual Studio временно отключила некоторые дополнительные возможности, чтобы повысить производительность.</target> <note /> </trans-unit> <trans-unit id="Installing_0"> <source>Installing '{0}'</source> <target state="translated">Идет установка "{0}"</target> <note /> </trans-unit> <trans-unit id="Installing_0_completed"> <source>Installing '{0}' completed</source> <target state="translated">Установка "{0}" завершена</target> <note /> </trans-unit> <trans-unit id="Package_install_failed_colon_0"> <source>Package install failed: {0}</source> <target state="translated">Сбой при установке пакета: {0}</target> <note /> </trans-unit> <trans-unit id="Unknown2"> <source>&lt;Unknown&gt;</source> <target state="translated">&lt;нет данных&gt;</target> <note /> </trans-unit> <trans-unit id="No"> <source>No</source> <target state="translated">Нет</target> <note /> </trans-unit> <trans-unit id="Yes"> <source>Yes</source> <target state="translated">Да</target> <note /> </trans-unit> <trans-unit id="Choose_a_Symbol_Specification_and_a_Naming_Style"> <source>Choose a Symbol Specification and a Naming Style.</source> <target state="translated">Выберите спецификацию символов и стиль именования.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Naming_Rule"> <source>Enter a title for this Naming Rule.</source> <target state="translated">Введите название для этого правила именования.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Naming_Style"> <source>Enter a title for this Naming Style.</source> <target state="translated">Введите название для этого стиля именования.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Symbol_Specification"> <source>Enter a title for this Symbol Specification.</source> <target state="translated">Введите название для этой спецификации символа.</target> <note /> </trans-unit> <trans-unit id="Accessibilities_can_match_any"> <source>Accessibilities (can match any)</source> <target state="translated">Модификаторы доступности (соответствие любому)</target> <note /> </trans-unit> <trans-unit id="Capitalization_colon"> <source>Capitalization:</source> <target state="translated">Написание прописными буквами:</target> <note /> </trans-unit> <trans-unit id="all_lower"> <source>all lower</source> <target state="translated">все строчные</target> <note /> </trans-unit> <trans-unit id="ALL_UPPER"> <source>ALL UPPER</source> <target state="translated">ВСЕ ПРОПИСНЫЕ</target> <note /> </trans-unit> <trans-unit id="camel_Case_Name"> <source>camel Case Name</source> <target state="translated">Название в "Верблюжьем" стиле c первой прописной буквой</target> <note /> </trans-unit> <trans-unit id="First_word_upper"> <source>First word upper</source> <target state="translated">Первое слово с прописной буквы</target> <note /> </trans-unit> <trans-unit id="Pascal_Case_Name"> <source>Pascal Case Name</source> <target state="translated">Название в регистре Pascal</target> <note /> </trans-unit> <trans-unit id="Severity_colon"> <source>Severity:</source> <target state="translated">Серьезность:</target> <note /> </trans-unit> <trans-unit id="Modifiers_must_match_all"> <source>Modifiers (must match all)</source> <target state="translated">Модификаторы (должны соответствовать всему)</target> <note /> </trans-unit> <trans-unit id="Name_colon2"> <source>Name:</source> <target state="translated">Название:</target> <note /> </trans-unit> <trans-unit id="Naming_Rule"> <source>Naming Rule</source> <target state="translated">Правило именования</target> <note /> </trans-unit> <trans-unit id="Naming_Style"> <source>Naming Style</source> <target state="translated">Стиль именования</target> <note /> </trans-unit> <trans-unit id="Naming_Style_colon"> <source>Naming Style:</source> <target state="translated">Стиль именования:</target> <note /> </trans-unit> <trans-unit id="Naming_Rules_allow_you_to_define_how_particular_sets_of_symbols_should_be_named_and_how_incorrectly_named_symbols_should_be_handled"> <source>Naming Rules allow you to define how particular sets of symbols should be named and how incorrectly-named symbols should be handled.</source> <target state="translated">Правила именования позволяют определить, как должны именоваться определенные наборы символов и как должны обрабатываться неправильно названные символы.</target> <note /> </trans-unit> <trans-unit id="The_first_matching_top_level_Naming_Rule_is_used_by_default_when_naming_a_symbol_while_any_special_cases_are_handled_by_a_matching_child_rule"> <source>The first matching top-level Naming Rule is used by default when naming a symbol, while any special cases are handled by a matching child rule.</source> <target state="translated">По умолчанию при именовании символа используется первое соответствующее правило именования верхнего уровня, а все особые случаи обрабатываются соответствующим дочерним правилом.</target> <note /> </trans-unit> <trans-unit id="Naming_Style_Title_colon"> <source>Naming Style Title:</source> <target state="translated">Название стиля именования:</target> <note /> </trans-unit> <trans-unit id="Parent_Rule_colon"> <source>Parent Rule:</source> <target state="translated">Родительское правило:</target> <note /> </trans-unit> <trans-unit id="Required_Prefix_colon"> <source>Required Prefix:</source> <target state="translated">Необходимый префикс:</target> <note /> </trans-unit> <trans-unit id="Required_Suffix_colon"> <source>Required Suffix:</source> <target state="translated">Необходимый суффикс:</target> <note /> </trans-unit> <trans-unit id="Sample_Identifier_colon"> <source>Sample Identifier:</source> <target state="translated">Пример идентификатора:</target> <note /> </trans-unit> <trans-unit id="Symbol_Kinds_can_match_any"> <source>Symbol Kinds (can match any)</source> <target state="translated">Виды символов (соответствие любому)</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification"> <source>Symbol Specification</source> <target state="translated">Спецификация символа</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification_colon"> <source>Symbol Specification:</source> <target state="translated">Спецификация символа:</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification_Title_colon"> <source>Symbol Specification Title:</source> <target state="translated">Название спецификации символа:</target> <note /> </trans-unit> <trans-unit id="Word_Separator_colon"> <source>Word Separator:</source> <target state="translated">Разделитель слов:</target> <note /> </trans-unit> <trans-unit id="example"> <source>example</source> <target state="translated">пример</target> <note>IdentifierWord_Example and IdentifierWord_Identifier are combined (with prefixes, suffixes, and word separators) into an example identifier name in the NamingStyle UI.</note> </trans-unit> <trans-unit id="identifier"> <source>identifier</source> <target state="translated">идентификатор</target> <note>IdentifierWord_Example and IdentifierWord_Identifier are combined (with prefixes, suffixes, and word separators) into an example identifier name in the NamingStyle UI.</note> </trans-unit> <trans-unit id="Install_0"> <source>Install '{0}'</source> <target state="translated">Установить "{0}"</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0"> <source>Uninstalling '{0}'</source> <target state="translated">Идет удаление "{0}"</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0_completed"> <source>Uninstalling '{0}' completed</source> <target state="translated">Удаление "{0}" завершено.</target> <note /> </trans-unit> <trans-unit id="Uninstall_0"> <source>Uninstall '{0}'</source> <target state="translated">Удалить "{0}"</target> <note /> </trans-unit> <trans-unit id="Package_uninstall_failed_colon_0"> <source>Package uninstall failed: {0}</source> <target state="translated">Сбой при удалении пакета: {0}</target> <note /> </trans-unit> <trans-unit id="Error_encountered_while_loading_the_project_Some_project_features_such_as_full_solution_analysis_for_the_failed_project_and_projects_that_depend_on_it_have_been_disabled"> <source>Error encountered while loading the project. Some project features, such as full solution analysis for the failed project and projects that depend on it, have been disabled.</source> <target state="translated">Произошла ошибка при загрузке проекта. Некоторые возможности проекта, например полный анализ решения для неработоспособного проекта и зависящих от него проектов, были отключены.</target> <note /> </trans-unit> <trans-unit id="Project_loading_failed"> <source>Project loading failed.</source> <target state="translated">Сбой при загрузке проекта.</target> <note /> </trans-unit> <trans-unit id="To_see_what_caused_the_issue_please_try_below_1_Close_Visual_Studio_long_paragraph_follows"> <source>To see what caused the issue, please try below. 1. Close Visual Studio 2. Open a Visual Studio Developer Command Prompt 3. Set environment variable “TraceDesignTime” to true (set TraceDesignTime=true) 4. Delete .vs directory/.suo file 5. Restart VS from the command prompt you set the environment variable (devenv) 6. Open the solution 7. Check '{0}' and look for the failed tasks (FAILED)</source> <target state="translated">Чтобы узнать, что вызвало проблему, попробуйте сделать следующее. 1. Закройте Visual Studio. 2. Откройте командную строку разработчика Visual Studio. 3. Присвойте переменной "TraceDesignTime" значение true (set TraceDesignTime=true). 4. Удалите файл ".vs directory/.suo". 5. Перезапустите VS из командной строки, в которой вы присвоили значение переменной среды (devenv). 6. Откройте решение. 7. Проверьте "{0}" и найдите задачи, которые завершились сбоем (FAILED).</target> <note /> </trans-unit> <trans-unit id="Additional_information_colon"> <source>Additional information:</source> <target state="translated">Дополнительная информация:</target> <note /> </trans-unit> <trans-unit id="Installing_0_failed_Additional_information_colon_1"> <source>Installing '{0}' failed. Additional information: {1}</source> <target state="translated">Сбой при установке "{0}". Дополнительная информация: {1}</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0_failed_Additional_information_colon_1"> <source>Uninstalling '{0}' failed. Additional information: {1}</source> <target state="translated">Сбой при удалении "{0}". Дополнительная информация: {1}</target> <note /> </trans-unit> <trans-unit id="Move_0_below_1"> <source>Move {0} below {1}</source> <target state="translated">Переместить {0} под {1}</target> <note>{0} and {1} are parameter descriptions</note> </trans-unit> <trans-unit id="Move_0_above_1"> <source>Move {0} above {1}</source> <target state="translated">Переместить {0} над {1}</target> <note>{0} and {1} are parameter descriptions</note> </trans-unit> <trans-unit id="Remove_0"> <source>Remove {0}</source> <target state="translated">Удалить {0}</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Restore_0"> <source>Restore {0}</source> <target state="translated">Восстановить {0}</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Re_enable"> <source>Re-enable</source> <target state="translated">Повторно включить</target> <note /> </trans-unit> <trans-unit id="Learn_more"> <source>Learn more</source> <target state="translated">Подробнее...</target> <note /> </trans-unit> <trans-unit id="Prefer_framework_type"> <source>Prefer framework type</source> <target state="translated">Предпочитать тип платформы</target> <note /> </trans-unit> <trans-unit id="Prefer_predefined_type"> <source>Prefer predefined type</source> <target state="translated">Предпочитать предопределенный тип</target> <note /> </trans-unit> <trans-unit id="Copy_to_Clipboard"> <source>Copy to Clipboard</source> <target state="translated">Копировать в буфер обмена</target> <note /> </trans-unit> <trans-unit id="Close"> <source>Close</source> <target state="translated">Закрыть</target> <note /> </trans-unit> <trans-unit id="Unknown_parameters"> <source>&lt;Unknown Parameters&gt;</source> <target state="translated">&lt;Неизвестные параметры&gt;</target> <note /> </trans-unit> <trans-unit id="End_of_inner_exception_stack"> <source>--- End of inner exception stack trace ---</source> <target state="translated">--- Конец трассировки внутреннего стека исключений ---</target> <note /> </trans-unit> <trans-unit id="For_locals_parameters_and_members"> <source>For locals, parameters and members</source> <target state="translated">Для локальных переменных, параметров и элементов</target> <note /> </trans-unit> <trans-unit id="For_member_access_expressions"> <source>For member access expressions</source> <target state="translated">Для выражений доступа к элементам</target> <note /> </trans-unit> <trans-unit id="Prefer_object_initializer"> <source>Prefer object initializer</source> <target state="translated">Предпочитать инициализатор объекта</target> <note /> </trans-unit> <trans-unit id="Expression_preferences_colon"> <source>Expression preferences:</source> <target state="translated">Предпочтения в отношении выражения:</target> <note /> </trans-unit> <trans-unit id="Block_Structure_Guides"> <source>Block Structure Guides</source> <target state="translated">Направляющие для структуры блоков</target> <note /> </trans-unit> <trans-unit id="Outlining"> <source>Outlining</source> <target state="translated">Структура</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_code_level_constructs"> <source>Show guides for code level constructs</source> <target state="translated">Показывать направляющие для конструкций уровня кода</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_comments_and_preprocessor_regions"> <source>Show guides for comments and preprocessor regions</source> <target state="translated">Показывать направляющие для комментариев и областей препроцессора</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_declaration_level_constructs"> <source>Show guides for declaration level constructs</source> <target state="translated">Показывать направляющие для конструкций уровня объявления</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_code_level_constructs"> <source>Show outlining for code level constructs</source> <target state="translated">Показывать структуру для конструкций уровня кода</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_comments_and_preprocessor_regions"> <source>Show outlining for comments and preprocessor regions</source> <target state="translated">Показывать структуру для комментариев и областей препроцессора</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_declaration_level_constructs"> <source>Show outlining for declaration level constructs</source> <target state="translated">Показывать структуру для конструкций уровня объявления</target> <note /> </trans-unit> <trans-unit id="Variable_preferences_colon"> <source>Variable preferences:</source> <target state="translated">Предпочтения в отношении переменных:</target> <note /> </trans-unit> <trans-unit id="Prefer_inlined_variable_declaration"> <source>Prefer inlined variable declaration</source> <target state="translated">Предпочитать встроенное объявление переменной</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Использовать тело выражения для методов</target> <note /> </trans-unit> <trans-unit id="Code_block_preferences_colon"> <source>Code block preferences:</source> <target state="translated">Предпочтения в отношении блока кода:</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Использовать тело выражения для методов доступа</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Использовать тело выражения для конструкторов</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Использовать тело выражения для индексаторов</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Использовать тело выражения для операторов</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Использовать тело выражения для свойств</target> <note /> </trans-unit> <trans-unit id="Some_naming_rules_are_incomplete_Please_complete_or_remove_them"> <source>Some naming rules are incomplete. Please complete or remove them.</source> <target state="translated">Некоторые правила именования являются неполными. Дополните или удалите их.</target> <note /> </trans-unit> <trans-unit id="Manage_specifications"> <source>Manage specifications</source> <target state="translated">Управление спецификациями</target> <note /> </trans-unit> <trans-unit id="Reorder"> <source>Reorder</source> <target state="translated">Переупорядочить</target> <note /> </trans-unit> <trans-unit id="Severity"> <source>Severity</source> <target state="translated">Серьезность</target> <note /> </trans-unit> <trans-unit id="Specification"> <source>Specification</source> <target state="translated">Спецификация</target> <note /> </trans-unit> <trans-unit id="Required_Style"> <source>Required Style</source> <target state="translated">Необходимый стиль</target> <note /> </trans-unit> <trans-unit id="This_item_cannot_be_deleted_because_it_is_used_by_an_existing_Naming_Rule"> <source>This item cannot be deleted because it is used by an existing Naming Rule.</source> <target state="translated">Невозможно удалить этот элемент, так как он используется существующим правилом именования.</target> <note /> </trans-unit> <trans-unit id="Prefer_collection_initializer"> <source>Prefer collection initializer</source> <target state="translated">Предпочитать инициализатор коллекции</target> <note /> </trans-unit> <trans-unit id="Prefer_coalesce_expression"> <source>Prefer coalesce expression</source> <target state="translated">Предпочитать объединенное выражение</target> <note /> </trans-unit> <trans-unit id="Collapse_regions_when_collapsing_to_definitions"> <source>Collapse #regions when collapsing to definitions</source> <target state="translated">Сворачивать #regions при сворачивании в определения</target> <note /> </trans-unit> <trans-unit id="Prefer_null_propagation"> <source>Prefer null propagation</source> <target state="translated">Предпочитать распространение значений NULL</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_tuple_name"> <source>Prefer explicit tuple name</source> <target state="translated">Предпочитать явное имя кортежа</target> <note /> </trans-unit> <trans-unit id="Description"> <source>Description</source> <target state="translated">Описание</target> <note /> </trans-unit> <trans-unit id="Preference"> <source>Preference</source> <target state="translated">Предпочтения</target> <note /> </trans-unit> <trans-unit id="Implement_Interface_or_Abstract_Class"> <source>Implement Interface or Abstract Class</source> <target state="translated">Реализовать интерфейс или абстрактный класс</target> <note /> </trans-unit> <trans-unit id="For_a_given_symbol_only_the_topmost_rule_with_a_matching_Specification_will_be_applied_Violation_of_that_rules_Required_Style_will_be_reported_at_the_chosen_Severity_level"> <source>For a given symbol, only the topmost rule with a matching 'Specification' will be applied. Violation of that rule's 'Required Style' will be reported at the chosen 'Severity' level.</source> <target state="translated">Для указанного символа будет применено только самое верхнее правило соответствующей спецификации. При нарушении требуемого стиля для этого правила будет создано оповещение указанного уровня серьезности.</target> <note /> </trans-unit> <trans-unit id="at_the_end"> <source>at the end</source> <target state="translated">в конец</target> <note /> </trans-unit> <trans-unit id="When_inserting_properties_events_and_methods_place_them"> <source>When inserting properties, events and methods, place them:</source> <target state="translated">При вставке свойств, методов и событий помещать их:</target> <note /> </trans-unit> <trans-unit id="with_other_members_of_the_same_kind"> <source>with other members of the same kind</source> <target state="translated">вместе с другими элементами того же типа</target> <note /> </trans-unit> <trans-unit id="Prefer_braces"> <source>Prefer braces</source> <target state="translated">Предпочитать фигурные скобки</target> <note /> </trans-unit> <trans-unit id="Over_colon"> <source>Over:</source> <target state="translated">А не:</target> <note /> </trans-unit> <trans-unit id="Prefer_colon"> <source>Prefer:</source> <target state="translated">Предпочтение:</target> <note /> </trans-unit> <trans-unit id="or"> <source>or</source> <target state="translated">или</target> <note /> </trans-unit> <trans-unit id="built_in_types"> <source>built-in types</source> <target state="translated">встроенные типы</target> <note /> </trans-unit> <trans-unit id="everywhere_else"> <source>everywhere else</source> <target state="translated">в любое другое место</target> <note /> </trans-unit> <trans-unit id="type_is_apparent_from_assignment_expression"> <source>type is apparent from assignment expression</source> <target state="translated">тип предполагается из выражения назначения</target> <note /> </trans-unit> <trans-unit id="Move_down"> <source>Move down</source> <target state="translated">Переместить вниз</target> <note /> </trans-unit> <trans-unit id="Move_up"> <source>Move up</source> <target state="translated">Переместить вверх</target> <note /> </trans-unit> <trans-unit id="Remove"> <source>Remove</source> <target state="translated">Удалить</target> <note /> </trans-unit> <trans-unit id="Pick_members"> <source>Pick members</source> <target state="translated">Выбрать члены</target> <note /> </trans-unit> <trans-unit id="Unfortunately_a_process_used_by_Visual_Studio_has_encountered_an_unrecoverable_error_We_recommend_saving_your_work_and_then_closing_and_restarting_Visual_Studio"> <source>Unfortunately, a process used by Visual Studio has encountered an unrecoverable error. We recommend saving your work, and then closing and restarting Visual Studio.</source> <target state="translated">В процессе, используемом Visual Studio, произошла неустранимая ошибка. Рекомендуется сохранить изменения, а затем закрыть и снова запустить Visual Studio.</target> <note /> </trans-unit> <trans-unit id="Add_a_symbol_specification"> <source>Add a symbol specification</source> <target state="translated">Добавить спецификацию символа</target> <note /> </trans-unit> <trans-unit id="Remove_symbol_specification"> <source>Remove symbol specification</source> <target state="translated">Удалить спецификацию символа</target> <note /> </trans-unit> <trans-unit id="Add_item"> <source>Add item</source> <target state="translated">Добавить элемент</target> <note /> </trans-unit> <trans-unit id="Edit_item"> <source>Edit item</source> <target state="translated">Изменить элемент</target> <note /> </trans-unit> <trans-unit id="Remove_item"> <source>Remove item</source> <target state="translated">Удалить элемент</target> <note /> </trans-unit> <trans-unit id="Add_a_naming_rule"> <source>Add a naming rule</source> <target state="translated">Добавить правило именования</target> <note /> </trans-unit> <trans-unit id="Remove_naming_rule"> <source>Remove naming rule</source> <target state="translated">Удалить правило именования</target> <note /> </trans-unit> <trans-unit id="VisualStudioWorkspace_TryApplyChanges_cannot_be_called_from_a_background_thread"> <source>VisualStudioWorkspace.TryApplyChanges cannot be called from a background thread.</source> <target state="translated">VisualStudioWorkspace.TryApplyChanges нельзя вызывать из фонового потока.</target> <note /> </trans-unit> <trans-unit id="prefer_throwing_properties"> <source>prefer throwing properties</source> <target state="translated">предпочитать свойства, создающие исключения</target> <note /> </trans-unit> <trans-unit id="When_generating_properties"> <source>When generating properties:</source> <target state="translated">При создании свойств:</target> <note /> </trans-unit> <trans-unit id="Options"> <source>Options</source> <target state="translated">Параметры</target> <note /> </trans-unit> <trans-unit id="Never_show_this_again"> <source>Never show this again</source> <target state="translated">Больше не показывать</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_default_expression"> <source>Prefer simple 'default' expression</source> <target state="translated">Предпочитать простое выражение default</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_tuple_names"> <source>Prefer inferred tuple element names</source> <target state="translated">Предпочитать выводимые имена элементов кортежа</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_anonymous_type_member_names"> <source>Prefer inferred anonymous type member names</source> <target state="translated">Предпочитать выводимые имена членов анонимного типа</target> <note /> </trans-unit> <trans-unit id="Preview_pane"> <source>Preview pane</source> <target state="translated">Область просмотра</target> <note /> </trans-unit> <trans-unit id="Analysis"> <source>Analysis</source> <target state="translated">Анализ</target> <note /> </trans-unit> <trans-unit id="Fade_out_unreachable_code"> <source>Fade out unreachable code</source> <target state="translated">Скрывать недостижимый код</target> <note /> </trans-unit> <trans-unit id="Fading"> <source>Fading</source> <target state="translated">Исчезание</target> <note /> </trans-unit> <trans-unit id="Prefer_local_function_over_anonymous_function"> <source>Prefer local function over anonymous function</source> <target state="translated">Предпочитать локальную функцию анонимной функции</target> <note /> </trans-unit> <trans-unit id="Prefer_deconstructed_variable_declaration"> <source>Prefer deconstructed variable declaration</source> <target state="translated">Предпочитать деконструированное объявление переменной</target> <note /> </trans-unit> <trans-unit id="External_reference_found"> <source>External reference found</source> <target state="translated">Найдена внешняя ссылка.</target> <note /> </trans-unit> <trans-unit id="No_references_found_to_0"> <source>No references found to '{0}'</source> <target state="translated">Ссылки не найдены в "{0}".</target> <note /> </trans-unit> <trans-unit id="Search_found_no_results"> <source>Search found no results</source> <target state="translated">Поиск не дал результатов.</target> <note /> </trans-unit> <trans-unit id="analyzer_Prefer_auto_properties"> <source>Prefer auto properties</source> <target state="translated">Предпочитать автосвойства</target> <note /> </trans-unit> <trans-unit id="codegen_prefer_auto_properties"> <source>prefer auto properties</source> <target state="translated">предпочитать автосвойства</target> <note /> </trans-unit> <trans-unit id="ModuleHasBeenUnloaded"> <source>Module has been unloaded.</source> <target state="translated">Модуль был выгружен.</target> <note /> </trans-unit> <trans-unit id="Enable_navigation_to_decompiled_sources"> <source>Enable navigation to decompiled sources</source> <target state="needs-review-translation">Включить переход к декомпилированным источникам (экспериментальная функция)</target> <note /> </trans-unit> <trans-unit id="Code_style_header_use_editor_config"> <source>Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info</source> <target state="translated">Файл EditorConfig может переопределять локальные параметры, настроенные на этой странице, только для этого компьютера. Чтобы эти параметры были привязаны к решению, используйте файлы EditorConfig. Дополнительные сведения.</target> <note /> </trans-unit> <trans-unit id="Sync_Class_View"> <source>Sync Class View</source> <target state="translated">Синхронизировать представление классов</target> <note /> </trans-unit> <trans-unit id="Analyzing_0"> <source>Analyzing '{0}'</source> <target state="translated">Выполняется анализ "{0}"</target> <note /> </trans-unit> <trans-unit id="Manage_naming_styles"> <source>Manage naming styles</source> <target state="translated">Управление стилями именования</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_assignments"> <source>Prefer conditional expression over 'if' with assignments</source> <target state="translated">Предпочитать условное выражение оператору if в назначениях</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_returns"> <source>Prefer conditional expression over 'if' with returns</source> <target state="translated">Предпочитать условное выражение оператору if в операторах return</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="ru" original="../ServicesVSResources.resx"> <body> <trans-unit id="A_new_namespace_will_be_created"> <source>A new namespace will be created</source> <target state="translated">Будет создано пространство имен</target> <note /> </trans-unit> <trans-unit id="A_type_and_name_must_be_provided"> <source>A type and name must be provided.</source> <target state="translated">Следует указать тип и имя.</target> <note /> </trans-unit> <trans-unit id="Action"> <source>Action</source> <target state="translated">Действие</target> <note>Action to perform on an unused reference, such as remove or keep</note> </trans-unit> <trans-unit id="Add"> <source>_Add</source> <target state="translated">Д_обавить</target> <note>Adding an element to a list</note> </trans-unit> <trans-unit id="Add_Parameter"> <source>Add Parameter</source> <target state="translated">Добавить параметр</target> <note /> </trans-unit> <trans-unit id="Add_to_current_file"> <source>Add to _current file</source> <target state="translated">Добавить в _текущий файл</target> <note /> </trans-unit> <trans-unit id="Added_Parameter"> <source>Added parameter.</source> <target state="translated">Добавлен параметр.</target> <note /> </trans-unit> <trans-unit id="Additional_changes_are_needed_to_complete_the_refactoring_Review_changes_below"> <source>Additional changes are needed to complete the refactoring. Review changes below.</source> <target state="translated">Для завершения рефакторинга требуется внести дополнительные изменения. Просмотрите их ниже.</target> <note /> </trans-unit> <trans-unit id="All_methods"> <source>All methods</source> <target state="translated">Все методы</target> <note /> </trans-unit> <trans-unit id="All_sources"> <source>All sources</source> <target state="translated">Все источники</target> <note /> </trans-unit> <trans-unit id="Allow_colon"> <source>Allow:</source> <target state="translated">Разрешить:</target> <note /> </trans-unit> <trans-unit id="Allow_multiple_blank_lines"> <source>Allow multiple blank lines</source> <target state="translated">Разрешать несколько пустых строк</target> <note /> </trans-unit> <trans-unit id="Allow_statement_immediately_after_block"> <source>Allow statement immediately after block</source> <target state="translated">Разрешать помещать оператор сразу же после блока</target> <note /> </trans-unit> <trans-unit id="Always_for_clarity"> <source>Always for clarity</source> <target state="translated">Всегда использовать для ясности</target> <note /> </trans-unit> <trans-unit id="Analyzer_Defaults"> <source>Analyzer Defaults</source> <target state="new">Analyzer Defaults</target> <note /> </trans-unit> <trans-unit id="Analyzers"> <source>Analyzers</source> <target state="translated">Анализаторы</target> <note /> </trans-unit> <trans-unit id="Analyzing_project_references"> <source>Analyzing project references...</source> <target state="translated">Анализ ссылок проекта…</target> <note /> </trans-unit> <trans-unit id="Apply"> <source>Apply</source> <target state="translated">Применить</target> <note /> </trans-unit> <trans-unit id="Apply_0_keymapping_scheme"> <source>Apply '{0}' keymapping scheme</source> <target state="translated">Применить схему назначения клавиш "{0}"</target> <note /> </trans-unit> <trans-unit id="Assemblies"> <source>Assemblies</source> <target state="translated">Сборки</target> <note /> </trans-unit> <trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value"> <source>Avoid expression statements that implicitly ignore value</source> <target state="translated">Избегайте операторов-выражений, неявно игнорирующих значение.</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_parameters"> <source>Avoid unused parameters</source> <target state="translated">Избегайте неиспользуемых параметров.</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_value_assignments"> <source>Avoid unused value assignments</source> <target state="translated">Избегайте присваивания неиспользуемых значений.</target> <note /> </trans-unit> <trans-unit id="Back"> <source>Back</source> <target state="translated">Назад</target> <note /> </trans-unit> <trans-unit id="Background_analysis_scope_colon"> <source>Background analysis scope:</source> <target state="translated">Область фонового анализа:</target> <note /> </trans-unit> <trans-unit id="Bitness32"> <source>32-bit</source> <target state="translated">32-разрядный</target> <note /> </trans-unit> <trans-unit id="Bitness64"> <source>64-bit</source> <target state="translated">64-разрядный</target> <note /> </trans-unit> <trans-unit id="Build_plus_live_analysis_NuGet_package"> <source>Build + live analysis (NuGet package)</source> <target state="translated">Сборка и динамический анализ (пакет NuGet)</target> <note /> </trans-unit> <trans-unit id="CSharp_Visual_Basic_Diagnostics_Language_Client"> <source>C#/Visual Basic Diagnostics Language Client</source> <target state="translated">Языковой клиент диагностики C#/Visual Basic</target> <note /> </trans-unit> <trans-unit id="Calculating"> <source>Calculating...</source> <target state="new">Calculating...</target> <note>Used in UI to represent progress in the context of loading items. </note> </trans-unit> <trans-unit id="Calculating_dependents"> <source>Calculating dependents...</source> <target state="translated">Вычисление зависимостей…</target> <note /> </trans-unit> <trans-unit id="Call_site_value"> <source>Call site value:</source> <target state="translated">Значение места вызова:</target> <note /> </trans-unit> <trans-unit id="Callsite"> <source>Call site</source> <target state="translated">Место вызова</target> <note /> </trans-unit> <trans-unit id="Carriage_Return_Newline_rn"> <source>Carriage Return + Newline (\r\n)</source> <target state="translated">Возврат каретки + символ новой строки (\r\n)</target> <note /> </trans-unit> <trans-unit id="Carriage_Return_r"> <source>Carriage Return (\r)</source> <target state="translated">Возврат каретки (\r)</target> <note /> </trans-unit> <trans-unit id="Category"> <source>Category</source> <target state="translated">Категория</target> <note /> </trans-unit> <trans-unit id="Choose_which_action_you_would_like_to_perform_on_the_unused_references"> <source>Choose which action you would like to perform on the unused references.</source> <target state="translated">Выберите действие, которое необходимо выполнить для неиспользуемых ссылок.</target> <note /> </trans-unit> <trans-unit id="Code_Style"> <source>Code Style</source> <target state="translated">Стиль кода</target> <note /> </trans-unit> <trans-unit id="Code_analysis_completed_for_0"> <source>Code analysis completed for '{0}'.</source> <target state="translated">Анализ кода для "{0}" выполнен.</target> <note /> </trans-unit> <trans-unit id="Code_analysis_completed_for_Solution"> <source>Code analysis completed for Solution.</source> <target state="translated">Анализ кода для решения выполнен.</target> <note /> </trans-unit> <trans-unit id="Code_analysis_terminated_before_completion_for_0"> <source>Code analysis terminated before completion for '{0}'.</source> <target state="translated">Анализ кода прерван до завершения "{0}".</target> <note /> </trans-unit> <trans-unit id="Code_analysis_terminated_before_completion_for_Solution"> <source>Code analysis terminated before completion for Solution.</source> <target state="translated">Анализ кода прерван до завершения решения.</target> <note /> </trans-unit> <trans-unit id="Color_hints"> <source>Color hints</source> <target state="translated">Цветовые подсказки</target> <note /> </trans-unit> <trans-unit id="Colorize_regular_expressions"> <source>Colorize regular expressions</source> <target state="translated">Выделить регулярные выражения цветом</target> <note /> </trans-unit> <trans-unit id="Comments"> <source>Comments</source> <target state="translated">Комментарии</target> <note /> </trans-unit> <trans-unit id="Compute_Quick_Actions_asynchronously_experimental"> <source>Compute Quick Actions asynchronously (experimental, requires restart)</source> <target state="new">Compute Quick Actions asynchronously (experimental, requires restart)</target> <note /> </trans-unit> <trans-unit id="Containing_member"> <source>Containing Member</source> <target state="translated">Содержащий член</target> <note /> </trans-unit> <trans-unit id="Containing_type"> <source>Containing Type</source> <target state="translated">Содержащий тип</target> <note /> </trans-unit> <trans-unit id="Current_document"> <source>Current document</source> <target state="translated">Текущий документ</target> <note /> </trans-unit> <trans-unit id="Current_parameter"> <source>Current parameter</source> <target state="translated">Текущий параметр</target> <note /> </trans-unit> <trans-unit id="Default_Current_Document"> <source>Default (Current Document)</source> <target state="new">Default (Current Document)</target> <note>This text is a menu command</note> </trans-unit> <trans-unit id="Default_Entire_Solution"> <source>Default (Entire Solution)</source> <target state="new">Default (Entire Solution)</target> <note>This text is a menu command</note> </trans-unit> <trans-unit id="Default_Open_Documents"> <source>Default (Open Documents)</source> <target state="new">Default (Open Documents)</target> <note>This text is a menu command</note> </trans-unit> <trans-unit id="Derived_types"> <source>Derived types</source> <target state="new">Derived types</target> <note /> </trans-unit> <trans-unit id="Disabled"> <source>Disabled</source> <target state="translated">Отключено</target> <note /> </trans-unit> <trans-unit id="Display_all_hints_while_pressing_Alt_F1"> <source>Display all hints while pressing Alt+F1</source> <target state="translated">Отображать все подсказки при нажатии клавиш ALT+F1</target> <note /> </trans-unit> <trans-unit id="Display_inline_parameter_name_hints"> <source>Disp_lay inline parameter name hints</source> <target state="translated">Отображать п_одсказки для имен встроенных параметров</target> <note /> </trans-unit> <trans-unit id="Display_inline_type_hints"> <source>Display inline type hints</source> <target state="translated">Отображать подсказки для встроенных типов</target> <note /> </trans-unit> <trans-unit id="Edit"> <source>_Edit</source> <target state="translated">_Изменить</target> <note /> </trans-unit> <trans-unit id="Edit_0"> <source>Edit {0}</source> <target state="translated">Изменить {0}</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Editor_Color_Scheme"> <source>Editor Color Scheme</source> <target state="translated">Цветовая схема редактора</target> <note /> </trans-unit> <trans-unit id="Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page"> <source>Editor color scheme options are only available when using a color theme bundled with Visual Studio. The color theme can be configured from the Environment &gt; General options page.</source> <target state="translated">Параметры цветовой схемы редактора доступны только при использовании цветовой темы, поставляемой вместе с Visual Studio. Цветовую тему можно настроить на странице "Среда" &gt; "Общие параметры".</target> <note /> </trans-unit> <trans-unit id="Element_is_not_valid"> <source>Element is not valid.</source> <target state="translated">Элемент недопустим.</target> <note /> </trans-unit> <trans-unit id="Enable_Razor_pull_diagnostics_experimental_requires_restart"> <source>Enable Razor 'pull' diagnostics (experimental, requires restart)</source> <target state="translated">Включить диагностику "pull" Razor (экспериментальная функция, требуется перезапуск)</target> <note /> </trans-unit> <trans-unit id="Enable_all_features_in_opened_files_from_source_generators_experimental"> <source>Enable all features in opened files from source generators (experimental)</source> <target state="translated">Включить все функции в открытых файлах из генераторов источника (экспериментальная версия)</target> <note /> </trans-unit> <trans-unit id="Enable_file_logging_for_diagnostics"> <source>Enable file logging for diagnostics (logged in '%Temp%\Roslyn' folder)</source> <target state="translated">Включить ведение журнала файлов для диагностики (в папке "%Temp%\Roslyn")</target> <note /> </trans-unit> <trans-unit id="Enable_pull_diagnostics_experimental_requires_restart"> <source>Enable 'pull' diagnostics (experimental, requires restart)</source> <target state="translated">Включить диагностику "pull" (экспериментальная функция, требуется перезапуск)</target> <note /> </trans-unit> <trans-unit id="Enabled"> <source>Enabled</source> <target state="translated">Включено</target> <note /> </trans-unit> <trans-unit id="Enter_a_call_site_value_or_choose_a_different_value_injection_kind"> <source>Enter a call site value or choose a different value injection kind</source> <target state="translated">Введите значение места вызова или выберите другой тип введения значения</target> <note /> </trans-unit> <trans-unit id="Entire_repository"> <source>Entire repository</source> <target state="translated">Весь репозиторий</target> <note /> </trans-unit> <trans-unit id="Entire_solution"> <source>Entire solution</source> <target state="translated">Все решение</target> <note /> </trans-unit> <trans-unit id="Error"> <source>Error</source> <target state="translated">Ошибка</target> <note /> </trans-unit> <trans-unit id="Error_updating_suppressions_0"> <source>Error updating suppressions: {0}</source> <target state="translated">Ошибка при обновлении подавлений: {0}</target> <note /> </trans-unit> <trans-unit id="Evaluating_0_tasks_in_queue"> <source>Evaluating ({0} tasks in queue)</source> <target state="translated">Оценка (задач в очереди: {0})</target> <note /> </trans-unit> <trans-unit id="Extract_Base_Class"> <source>Extract Base Class</source> <target state="translated">Извлечь базовый класс</target> <note /> </trans-unit> <trans-unit id="Finish"> <source>Finish</source> <target state="translated">Готово</target> <note /> </trans-unit> <trans-unit id="Format_document"> <source>Format document</source> <target state="translated">Форматировать документ</target> <note /> </trans-unit> <trans-unit id="Generate_dot_editorconfig_file_from_settings"> <source>Generate .editorconfig file from settings</source> <target state="translated">Создать файл EDITORCONFIG на основе параметров</target> <note /> </trans-unit> <trans-unit id="Highlight_related_components_under_cursor"> <source>Highlight related components under cursor</source> <target state="translated">Выделить связанные компоненты под курсором</target> <note /> </trans-unit> <trans-unit id="Id"> <source>Id</source> <target state="translated">ИД</target> <note /> </trans-unit> <trans-unit id="Implemented_interfaces"> <source>Implemented interfaces</source> <target state="new">Implemented interfaces</target> <note /> </trans-unit> <trans-unit id="Implemented_members"> <source>Implemented members</source> <target state="translated">Реализованные элементы</target> <note /> </trans-unit> <trans-unit id="Implementing_members"> <source>Implementing members</source> <target state="translated">Реализация элементов</target> <note /> </trans-unit> <trans-unit id="Implementing_types"> <source>Implementing types</source> <target state="new">Implementing types</target> <note /> </trans-unit> <trans-unit id="In_other_operators"> <source>In other operators</source> <target state="translated">В других операторах</target> <note /> </trans-unit> <trans-unit id="Index"> <source>Index</source> <target state="translated">Индекс</target> <note>Index of parameter in original signature</note> </trans-unit> <trans-unit id="Infer_from_context"> <source>Infer from context</source> <target state="translated">Вывести из контекста</target> <note /> </trans-unit> <trans-unit id="Indexed_in_organization"> <source>Indexed in organization</source> <target state="translated">Индексированный в организации</target> <note /> </trans-unit> <trans-unit id="Indexed_in_repo"> <source>Indexed in repo</source> <target state="translated">Индексированный в репозитории</target> <note /> </trans-unit> <trans-unit id="Inheritance_Margin_experimental"> <source>Inheritance Margin (experimental)</source> <target state="translated">Граница наследования (экспериментальная)</target> <note /> </trans-unit> <trans-unit id="Inherited_interfaces"> <source>Inherited interfaces</source> <target state="new">Inherited interfaces</target> <note /> </trans-unit> <trans-unit id="Inline_Hints_experimental"> <source>Inline Hints (experimental)</source> <target state="translated">Встроенные подсказки (экспериментальная функция)</target> <note /> </trans-unit> <trans-unit id="Inserting_call_site_value_0"> <source>Inserting call site value '{0}'</source> <target state="translated">Вставка значения "{0}" места вызова</target> <note /> </trans-unit> <trans-unit id="Install_Microsoft_recommended_Roslyn_analyzers_which_provide_additional_diagnostics_and_fixes_for_common_API_design_security_performance_and_reliability_issues"> <source>Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues</source> <target state="translated">Установите рекомендуемые корпорацией Майкрософт анализаторы Roslyn, которые предоставляют дополнительные средства диагностики и исправления для распространенных проблем, связанных с разработкой, безопасностью, производительностью и надежностью API.</target> <note /> </trans-unit> <trans-unit id="Interface_cannot_have_field"> <source>Interface cannot have field.</source> <target state="translated">Интерфейс не может содержать поле.</target> <note /> </trans-unit> <trans-unit id="IntroduceUndefinedTodoVariables"> <source>Introduce undefined TODO variables</source> <target state="translated">Ввести неопределенные переменные TODO</target> <note>"TODO" is an indicator that more work should be done at the location where the TODO is inserted</note> </trans-unit> <trans-unit id="Item_origin"> <source>Item origin</source> <target state="translated">Источник элемента</target> <note /> </trans-unit> <trans-unit id="Keep"> <source>Keep</source> <target state="translated">Сохранить</target> <note /> </trans-unit> <trans-unit id="Keep_all_parentheses_in_colon"> <source>Keep all parentheses in:</source> <target state="translated">Сохранять все круглые скобки в:</target> <note /> </trans-unit> <trans-unit id="Kind"> <source>Kind</source> <target state="translated">Вид</target> <note /> </trans-unit> <trans-unit id="Language_client_initialization_failed"> <source>{0} failed to initialize. Status = {1}. Exception = {2}</source> <target state="new">{0} failed to initialize. Status = {1}. Exception = {2}</target> <note>{0} is the language server name. Status is the status of the initialization. Exception is the exception encountered during initialization.</note> </trans-unit> <trans-unit id="Live_analysis_VSIX_extension"> <source>Live analysis (VSIX extension)</source> <target state="translated">Динамический анализ (расширение VSIX)</target> <note /> </trans-unit> <trans-unit id="Loaded_items"> <source>Loaded items</source> <target state="translated">Загруженные элементы</target> <note /> </trans-unit> <trans-unit id="Loaded_solution"> <source>Loaded solution</source> <target state="translated">Загруженное решение</target> <note /> </trans-unit> <trans-unit id="Local"> <source>Local</source> <target state="translated">Локальное</target> <note /> </trans-unit> <trans-unit id="Local_metadata"> <source>Local metadata</source> <target state="translated">Локальные метаданные</target> <note /> </trans-unit> <trans-unit id="Location"> <source>Location</source> <target state="new">Location</target> <note /> </trans-unit> <trans-unit id="Make_0_abstract"> <source>Make '{0}' abstract</source> <target state="translated">Сделать "{0}" абстрактным</target> <note /> </trans-unit> <trans-unit id="Make_abstract"> <source>Make abstract</source> <target state="translated">Сделать абстрактным</target> <note /> </trans-unit> <trans-unit id="Members"> <source>Members</source> <target state="translated">Члены</target> <note /> </trans-unit> <trans-unit id="Modifier_preferences_colon"> <source>Modifier preferences:</source> <target state="translated">Предпочтения модификатора:</target> <note /> </trans-unit> <trans-unit id="Move_to_namespace"> <source>Move to Namespace</source> <target state="translated">Переместить в пространство имен</target> <note /> </trans-unit> <trans-unit id="Multiple_members_are_inherited"> <source>Multiple members are inherited</source> <target state="translated">Несколько элементов наследуются</target> <note /> </trans-unit> <trans-unit id="Multiple_members_are_inherited_on_line_0"> <source>Multiple members are inherited on line {0}</source> <target state="translated">Несколько элементов наследуются в строке {0}</target> <note>Line number info is needed for accessibility purpose.</note> </trans-unit> <trans-unit id="Name_conflicts_with_an_existing_type_name"> <source>Name conflicts with an existing type name.</source> <target state="translated">Имя конфликтует с существующим именем типа.</target> <note /> </trans-unit> <trans-unit id="Name_is_not_a_valid_0_identifier"> <source>Name is not a valid {0} identifier.</source> <target state="translated">Имя не является допустимым идентификатором {0}.</target> <note /> </trans-unit> <trans-unit id="Namespace"> <source>Namespace</source> <target state="translated">Пространство имен</target> <note /> </trans-unit> <trans-unit id="Namespace_0"> <source>Namespace: '{0}'</source> <target state="translated">Пространство имен: "{0}"</target> <note /> </trans-unit> <trans-unit id="Namespace_declarations"> <source>Namespace declarations</source> <target state="new">Namespace declarations</target> <note /> </trans-unit> <trans-unit id="Namespaces_have_been_updated"> <source>Namespaces have been updated.</source> <target state="new">Namespaces have been updated.</target> <note>"Namespaces" is the programming language concept</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Class"> <source>class</source> <target state="new">class</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Delegate"> <source>delegate</source> <target state="new">delegate</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Enum"> <source>enum</source> <target state="new">enum</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Event"> <source>event</source> <target state="new">event</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Field"> <source>field</source> <target state="translated">Поле</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Interface"> <source>interface</source> <target state="new">interface</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Local"> <source>local</source> <target state="translated">локальный</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable".</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_LocalFunction"> <source>local function</source> <target state="translated">локальная функция</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Method"> <source>method</source> <target state="translated">метод</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Namespace"> <source>namespace</source> <target state="new">namespace</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Parameter"> <source>parameter</source> <target state="translated">параметр</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Property"> <source>property</source> <target state="translated">свойство</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Struct"> <source>struct</source> <target state="new">struct</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_TypeParameter"> <source>type parameter</source> <target state="translated">параметр типа</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Class"> <source>Class</source> <target state="new">Class</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Delegate"> <source>Delegate</source> <target state="new">Delegate</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Enum"> <source>Enum</source> <target state="new">Enum</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Event"> <source>Event</source> <target state="new">Event</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Field"> <source>Field</source> <target state="translated">Поле</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Interface"> <source>Interface</source> <target state="new">Interface</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Local"> <source>Local</source> <target state="translated">Локальные</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Method"> <source>Method</source> <target state="translated">метод</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Module"> <source>Module</source> <target state="new">Module</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Namespace"> <source>Namespace</source> <target state="new">Namespace</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Parameter"> <source>Parameter</source> <target state="translated">Параметр</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method.</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Property"> <source>Property</source> <target state="new">Property</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Structure"> <source>Structure</source> <target state="new">Structure</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_TypeParameter"> <source>Type Parameter</source> <target state="translated">Параметр типа</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter".</note> </trans-unit> <trans-unit id="Naming_rules"> <source>Naming rules</source> <target state="translated">Правила именования</target> <note /> </trans-unit> <trans-unit id="Navigate_to_0"> <source>Navigate to '{0}'</source> <target state="translated">Перейти к {0}</target> <note /> </trans-unit> <trans-unit id="Never_if_unnecessary"> <source>Never if unnecessary</source> <target state="translated">Никогда, если не требуется</target> <note /> </trans-unit> <trans-unit id="New_Type_Name_colon"> <source>New Type Name:</source> <target state="translated">Новое имя типа:</target> <note /> </trans-unit> <trans-unit id="New_line_preferences_experimental_colon"> <source>New line preferences (experimental):</source> <target state="translated">Предпочтения для новых строк (экспериментальная функция):</target> <note /> </trans-unit> <trans-unit id="Newline_n"> <source>Newline (\\n)</source> <target state="translated">Новая строка (\\n)</target> <note /> </trans-unit> <trans-unit id="No_namespaces_needed_updating"> <source>No namespaces needed updating.</source> <target state="new">No namespaces needed updating.</target> <note>"Namespaces" is the programming language concept</note> </trans-unit> <trans-unit id="No_unused_references_were_found"> <source>No unused references were found.</source> <target state="translated">Неиспользуемые ссылки не найдены.</target> <note /> </trans-unit> <trans-unit id="Non_public_methods"> <source>Non-public methods</source> <target state="translated">Методы, не являющиеся открытыми</target> <note /> </trans-unit> <trans-unit id="None"> <source>None</source> <target state="translated">NONE</target> <note /> </trans-unit> <trans-unit id="Omit_only_for_optional_parameters"> <source>Omit (only for optional parameters)</source> <target state="translated">Опустить (только для необязательных параметров)</target> <note /> </trans-unit> <trans-unit id="Open_documents"> <source>Open documents</source> <target state="translated">Открыть документы</target> <note /> </trans-unit> <trans-unit id="Optional_parameters_must_provide_a_default_value"> <source>Optional parameters must provide a default value</source> <target state="translated">Для необязательных параметров необходимо указать значение по умолчанию.</target> <note /> </trans-unit> <trans-unit id="Optional_with_default_value_colon"> <source>Optional with default value:</source> <target state="translated">Необязательный параметр со значением по умолчанию:</target> <note /> </trans-unit> <trans-unit id="Other"> <source>Others</source> <target state="translated">Другие</target> <note /> </trans-unit> <trans-unit id="Overridden_members"> <source>Overridden members</source> <target state="translated">Переопределенные элементы</target> <note /> </trans-unit> <trans-unit id="Overriding_members"> <source>Overriding members</source> <target state="translated">Идет переопределение элементов</target> <note /> </trans-unit> <trans-unit id="Package_install_canceled"> <source>Package install canceled</source> <target state="new">Package install canceled</target> <note /> </trans-unit> <trans-unit id="Package_uninstall_canceled"> <source>Package uninstall canceled</source> <target state="new">Package uninstall canceled</target> <note /> </trans-unit> <trans-unit id="Packages"> <source>Packages</source> <target state="translated">Пакеты</target> <note /> </trans-unit> <trans-unit id="Parameter_Details"> <source>Parameter Details</source> <target state="translated">Дополнительные сведения о параметрах</target> <note /> </trans-unit> <trans-unit id="Parameter_Name"> <source>Parameter name:</source> <target state="translated">Имя параметра:</target> <note /> </trans-unit> <trans-unit id="Parameter_information"> <source>Parameter information</source> <target state="translated">Сведения о параметре</target> <note /> </trans-unit> <trans-unit id="Parameter_kind"> <source>Parameter kind</source> <target state="translated">Тип параметра</target> <note /> </trans-unit> <trans-unit id="Parameter_name_contains_invalid_characters"> <source>Parameter name contains invalid character(s).</source> <target state="translated">Имя параметра содержит недопустимые знаки.</target> <note /> </trans-unit> <trans-unit id="Parameter_preferences_colon"> <source>Parameter preferences:</source> <target state="translated">Предпочтения для параметров:</target> <note /> </trans-unit> <trans-unit id="Parameter_type_contains_invalid_characters"> <source>Parameter type contains invalid character(s).</source> <target state="translated">Тип параметра содержит недопустимые знаки.</target> <note /> </trans-unit> <trans-unit id="Parentheses_preferences_colon"> <source>Parentheses preferences:</source> <target state="translated">Параметры круглых скобок:</target> <note /> </trans-unit> <trans-unit id="Paused_0_tasks_in_queue"> <source>Paused ({0} tasks in queue)</source> <target state="translated">Приостановлено (задач в очереди: {0})</target> <note /> </trans-unit> <trans-unit id="Please_enter_a_type_name"> <source>Please enter a type name</source> <target state="translated">Введите имя типа</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Prefer_System_HashCode_in_GetHashCode"> <source>Prefer 'System.HashCode' in 'GetHashCode'</source> <target state="translated">Предпочитать "System.HashCode" в "GetHashCode"</target> <note /> </trans-unit> <trans-unit id="Prefer_compound_assignments"> <source>Prefer compound assignments</source> <target state="translated">Предпочитать составные назначения</target> <note /> </trans-unit> <trans-unit id="Prefer_index_operator"> <source>Prefer index operator</source> <target state="translated">Предпочитать оператор index</target> <note /> </trans-unit> <trans-unit id="Prefer_range_operator"> <source>Prefer range operator</source> <target state="translated">Предпочитать оператор range</target> <note /> </trans-unit> <trans-unit id="Prefer_readonly_fields"> <source>Prefer readonly fields</source> <target state="translated">Предпочитать поля только для чтения</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_using_statement"> <source>Prefer simple 'using' statement</source> <target state="translated">Предпочитать простой оператор using</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_boolean_expressions"> <source>Prefer simplified boolean expressions</source> <target state="translated">Предпочитать упрощенные логические выражения</target> <note /> </trans-unit> <trans-unit id="Prefer_static_local_functions"> <source>Prefer static local functions</source> <target state="translated">Предпочитать статические локальные функции</target> <note /> </trans-unit> <trans-unit id="Projects"> <source>Projects</source> <target state="translated">Проекты</target> <note /> </trans-unit> <trans-unit id="Pull_Members_Up"> <source>Pull Members Up</source> <target state="translated">Повышение элементов</target> <note /> </trans-unit> <trans-unit id="Quick_Actions"> <source>Quick Actions</source> <target state="new">Quick Actions</target> <note /> </trans-unit> <trans-unit id="Refactoring_Only"> <source>Refactoring Only</source> <target state="translated">Только рефакторинг</target> <note /> </trans-unit> <trans-unit id="Reference"> <source>Reference</source> <target state="translated">Ссылка</target> <note /> </trans-unit> <trans-unit id="Regular_Expressions"> <source>Regular Expressions</source> <target state="translated">Регулярные выражения</target> <note /> </trans-unit> <trans-unit id="Remove_All"> <source>Remove All</source> <target state="translated">Удалить все</target> <note /> </trans-unit> <trans-unit id="Remove_Unused_References"> <source>Remove Unused References</source> <target state="translated">Удалить неиспользуемые ссылки</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1"> <source>Rename {0} to {1}</source> <target state="translated">Переименовать {0} в {1}</target> <note /> </trans-unit> <trans-unit id="Report_invalid_regular_expressions"> <source>Report invalid regular expressions</source> <target state="translated">Сообщать о недопустимых регулярных выражениях</target> <note /> </trans-unit> <trans-unit id="Repository"> <source>Repository</source> <target state="translated">Репозиторий</target> <note /> </trans-unit> <trans-unit id="Require_colon"> <source>Require:</source> <target state="translated">Обязательно:</target> <note /> </trans-unit> <trans-unit id="Required"> <source>Required</source> <target state="translated">Обязательный параметр</target> <note /> </trans-unit> <trans-unit id="Requires_System_HashCode_be_present_in_project"> <source>Requires 'System.HashCode' be present in project</source> <target state="translated">Требуется наличие "System.HashCode" в проекте.</target> <note /> </trans-unit> <trans-unit id="Reset_Visual_Studio_default_keymapping"> <source>Reset Visual Studio default keymapping</source> <target state="translated">Сброс схемы назначения клавиш Visual Studio по умолчанию</target> <note /> </trans-unit> <trans-unit id="Review_Changes"> <source>Review Changes</source> <target state="translated">Проверить изменения</target> <note /> </trans-unit> <trans-unit id="Run_Code_Analysis_on_0"> <source>Run Code Analysis on {0}</source> <target state="translated">Запустить Code Analysis для {0}</target> <note /> </trans-unit> <trans-unit id="Run_code_analysis_in_separate_process_requires_restart"> <source>Run code analysis in separate process (requires restart)</source> <target state="new">Run code analysis in separate process (requires restart)</target> <note /> </trans-unit> <trans-unit id="Running_code_analysis_for_0"> <source>Running code analysis for '{0}'...</source> <target state="translated">Выполняется анализ кода для "{0}"…</target> <note /> </trans-unit> <trans-unit id="Running_code_analysis_for_Solution"> <source>Running code analysis for Solution...</source> <target state="translated">Выполняется анализ кода для решения…</target> <note /> </trans-unit> <trans-unit id="Running_low_priority_background_processes"> <source>Running low priority background processes</source> <target state="translated">Запуск фоновых процессов с низким приоритетом</target> <note /> </trans-unit> <trans-unit id="Save_dot_editorconfig_file"> <source>Save .editorconfig file</source> <target state="translated">Сохранить файл EDITORCONFIG</target> <note /> </trans-unit> <trans-unit id="Search_Settings"> <source>Search Settings</source> <target state="translated">Параметры поиска</target> <note /> </trans-unit> <trans-unit id="Select_an_appropriate_symbol_to_start_value_tracking"> <source>Select an appropriate symbol to start value tracking</source> <target state="new">Select an appropriate symbol to start value tracking</target> <note /> </trans-unit> <trans-unit id="Select_destination"> <source>Select destination</source> <target state="translated">Выбрать место назначения</target> <note /> </trans-unit> <trans-unit id="Select_Dependents"> <source>Select _Dependents</source> <target state="translated">Выбрать _зависимости</target> <note /> </trans-unit> <trans-unit id="Select_Public"> <source>Select _Public</source> <target state="translated">Выбрать _открытые</target> <note /> </trans-unit> <trans-unit id="Select_destination_and_members_to_pull_up"> <source>Select destination and members to pull up.</source> <target state="translated">Выбрать место назначения и повышаемые в иерархии элементы.</target> <note /> </trans-unit> <trans-unit id="Select_destination_colon"> <source>Select destination:</source> <target state="translated">Выбрать место назначения:</target> <note /> </trans-unit> <trans-unit id="Select_member"> <source>Select member</source> <target state="translated">Выбрать элемент</target> <note /> </trans-unit> <trans-unit id="Select_members_colon"> <source>Select members:</source> <target state="translated">Выбрать элементы:</target> <note /> </trans-unit> <trans-unit id="Show_Remove_Unused_References_command_in_Solution_Explorer_experimental"> <source>Show "Remove Unused References" command in Solution Explorer (experimental)</source> <target state="translated">Показать команду "Удалить неиспользуемые ссылки" в Обозревателе решений (экспериментальная версия)</target> <note /> </trans-unit> <trans-unit id="Show_completion_list"> <source>Show completion list</source> <target state="translated">Показать список завершения</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_everything_else"> <source>Show hints for everything else</source> <target state="translated">Отображать подсказки для всех остальных элементов</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_implicit_object_creation"> <source>Show hints for implicit object creation</source> <target state="translated">Показать указания для неявного создания объекта</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_indexers"> <source>Show hints for indexers</source> <target state="new">Show hints for indexers</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_lambda_parameter_types"> <source>Show hints for lambda parameter types</source> <target state="translated">Отображать подсказки для типов лямбда-параметров</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_literals"> <source>Show hints for literals</source> <target state="translated">Отображать подсказки для литералов</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_variables_with_inferred_types"> <source>Show hints for variables with inferred types</source> <target state="translated">Отображать подсказки для переменных с выводимыми типами</target> <note /> </trans-unit> <trans-unit id="Show_inheritance_margin"> <source>Show inheritance margin</source> <target state="translated">Показать границу наследования</target> <note /> </trans-unit> <trans-unit id="Skip_analyzers_for_implicitly_triggered_builds"> <source>Skip analyzers for implicitly triggered builds</source> <target state="new">Skip analyzers for implicitly triggered builds</target> <note /> </trans-unit> <trans-unit id="Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations"> <source>Some color scheme colors are being overridden by changes made in the Environment &gt; Fonts and Colors options page. Choose `Use Defaults` in the Fonts and Colors page to revert all customizations.</source> <target state="translated">Некоторые цвета цветовой схемы переопределяются изменениями, сделанными на странице "Среда" &gt; "Шрифты и цвета". Выберите "Использовать значения по умолчанию" на странице "Шрифты и цвета", чтобы отменить все настройки.</target> <note /> </trans-unit> <trans-unit id="Suggestion"> <source>Suggestion</source> <target state="translated">Рекомендация</target> <note /> </trans-unit> <trans-unit id="Suppress_hints_when_parameter_name_matches_the_method_s_intent"> <source>Suppress hints when parameter name matches the method's intent</source> <target state="translated">Скрывать подсказки, если имя параметра соответствует намерению метода.</target> <note /> </trans-unit> <trans-unit id="Suppress_hints_when_parameter_names_differ_only_by_suffix"> <source>Suppress hints when parameter names differ only by suffix</source> <target state="translated">Скрывать подсказки, если имена параметров различаются только суффиксом.</target> <note /> </trans-unit> <trans-unit id="Symbols_without_references"> <source>Symbols without references</source> <target state="translated">Символы без ссылок</target> <note /> </trans-unit> <trans-unit id="Sync_Namespaces"> <source>Sync Namespaces</source> <target state="new">Sync Namespaces</target> <note>"Namespaces" is the programming language concept</note> </trans-unit> <trans-unit id="Tab_twice_to_insert_arguments"> <source>Tab twice to insert arguments (experimental)</source> <target state="translated">Дважды нажмите клавишу TAB, чтобы вставить аргументы (экспериментальная функция)</target> <note /> </trans-unit> <trans-unit id="Target_Namespace_colon"> <source>Target Namespace:</source> <target state="translated">Целевое пространство имен:</target> <note /> </trans-unit> <trans-unit id="The_generator_0_that_generated_this_file_has_been_removed_from_the_project"> <source>The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project.</source> <target state="translated">Генератор "{0}", создавший этот файл, был удален из проекта; этот файл больше не включен в проект.</target> <note /> </trans-unit> <trans-unit id="The_generator_0_that_generated_this_file_has_stopped_generating_this_file"> <source>The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project.</source> <target state="translated">Генератор "{0}", создавший этот файл, остановил создание этого файла; этот файл больше не включен в проект.</target> <note /> </trans-unit> <trans-unit id="This_action_cannot_be_undone_Do_you_wish_to_continue"> <source>This action cannot be undone. Do you wish to continue?</source> <target state="translated">Это действие не может быть отменено. Вы хотите продолжить?</target> <note /> </trans-unit> <trans-unit id="This_file_is_autogenerated_by_0_and_cannot_be_edited"> <source>This file is auto-generated by the generator '{0}' and cannot be edited.</source> <target state="translated">Этот файл создан автоматически генератором "{0}" и не может быть изменен.</target> <note /> </trans-unit> <trans-unit id="This_is_an_invalid_namespace"> <source>This is an invalid namespace</source> <target state="translated">Это недопустимое пространство имен.</target> <note /> </trans-unit> <trans-unit id="Title"> <source>Title</source> <target state="translated">Название</target> <note /> </trans-unit> <trans-unit id="Type_Name"> <source>Type name:</source> <target state="translated">Имя типа:</target> <note /> </trans-unit> <trans-unit id="Type_name_has_a_syntax_error"> <source>Type name has a syntax error</source> <target state="translated">Имя типа содержит синтаксическую ошибку.</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Type_name_is_not_recognized"> <source>Type name is not recognized</source> <target state="translated">Не удалось распознать имя типа.</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Type_name_is_recognized"> <source>Type name is recognized</source> <target state="translated">Имя типа распознано.</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Underline_reassigned_variables"> <source>Underline reassigned variables</source> <target state="new">Underline reassigned variables</target> <note /> </trans-unit> <trans-unit id="Unused_value_is_explicitly_assigned_to_an_unused_local"> <source>Unused value is explicitly assigned to an unused local</source> <target state="translated">Неиспользуемое значение явным образом задано неиспользуемой локальной переменной.</target> <note /> </trans-unit> <trans-unit id="Unused_value_is_explicitly_assigned_to_discard"> <source>Unused value is explicitly assigned to discard</source> <target state="translated">Неиспользуемое значение явным образом задано пустой переменной.</target> <note /> </trans-unit> <trans-unit id="Updating_namspaces"> <source>Updating namespaces...</source> <target state="new">Updating namespaces...</target> <note>"namespaces" is the programming language concept</note> </trans-unit> <trans-unit id="Updating_project_references"> <source>Updating project references...</source> <target state="translated">Обновление ссылок проекта…</target> <note /> </trans-unit> <trans-unit id="Updating_severity"> <source>Updating severity</source> <target state="translated">Обновление уровня серьезности</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_lambdas"> <source>Use expression body for lambdas</source> <target state="translated">Использовать тело выражения для лямбда-выражений</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Использовать тело выражения для локальных функций</target> <note /> </trans-unit> <trans-unit id="Use_named_argument"> <source>Use named argument</source> <target state="translated">Использовать именованный аргумент</target> <note>"argument" is a programming term for a value passed to a function</note> </trans-unit> <trans-unit id="Value"> <source>Value</source> <target state="translated">Значение</target> <note /> </trans-unit> <trans-unit id="Value_Tracking"> <source>Value Tracking</source> <target state="new">Value Tracking</target> <note>Title of the "Value Tracking" tool window. "Value" is the variable/symbol and "Tracking" is the action the tool is doing to follow where the value can originate from.</note> </trans-unit> <trans-unit id="Value_assigned_here_is_never_used"> <source>Value assigned here is never used</source> <target state="translated">Заданное здесь значение не используется.</target> <note /> </trans-unit> <trans-unit id="Value_colon"> <source>Value:</source> <target state="translated">Значение:</target> <note /> </trans-unit> <trans-unit id="Value_returned_by_invocation_is_implicitly_ignored"> <source>Value returned by invocation is implicitly ignored</source> <target state="translated">Значение, возвращаемое вызовом, неявным образом игнорируется.</target> <note /> </trans-unit> <trans-unit id="Value_to_inject_at_call_sites"> <source>Value to inject at call sites</source> <target state="translated">Значение, которое необходимо вставить во все точки вызова</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_2017"> <source>Visual Studio 2017</source> <target state="translated">Visual Studio 2017</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_2019"> <source>Visual Studio 2019</source> <target state="translated">Visual Studio 2019</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_Settings"> <source>Visual Studio Settings</source> <target state="new">Visual Studio Settings</target> <note /> </trans-unit> <trans-unit id="Warning"> <source>Warning</source> <target state="translated">Предупреждение</target> <note /> </trans-unit> <trans-unit id="Warning_colon_duplicate_parameter_name"> <source>Warning: duplicate parameter name</source> <target state="translated">Предупреждение: повторяющееся имя параметра.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_type_does_not_bind"> <source>Warning: type does not bind</source> <target state="translated">Предупреждение: привязка типа невозможна.</target> <note /> </trans-unit> <trans-unit id="We_notice_you_suspended_0_Reset_keymappings_to_continue_to_navigate_and_refactor"> <source>We notice you suspended '{0}'. Reset keymappings to continue to navigate and refactor.</source> <target state="translated">Вы приостановили действие "{0}". Сбросьте назначения клавиш, чтобы продолжить работу и рефакторинг.</target> <note /> </trans-unit> <trans-unit id="This_workspace_does_not_support_updating_Visual_Basic_compilation_options"> <source>This workspace does not support updating Visual Basic compilation options.</source> <target state="translated">Эта рабочая область не поддерживает обновление параметров компиляции Visual Basic.</target> <note /> </trans-unit> <trans-unit id="Whitespace"> <source>Whitespace</source> <target state="new">Whitespace</target> <note /> </trans-unit> <trans-unit id="You_must_change_the_signature"> <source>You must change the signature</source> <target state="translated">Необходимо изменить подпись</target> <note>"signature" here means the definition of a method</note> </trans-unit> <trans-unit id="You_must_select_at_least_one_member"> <source>You must select at least one member.</source> <target state="translated">Необходимо выбрать по крайней мере один элемент.</target> <note /> </trans-unit> <trans-unit id="Illegal_characters_in_path"> <source>Illegal characters in path.</source> <target state="translated">Недопустимые символы в пути.</target> <note /> </trans-unit> <trans-unit id="File_name_must_have_the_0_extension"> <source>File name must have the "{0}" extension.</source> <target state="translated">Файл должен иметь расширение "{0}".</target> <note /> </trans-unit> <trans-unit id="Debugger"> <source>Debugger</source> <target state="translated">Отладчик</target> <note /> </trans-unit> <trans-unit id="Determining_breakpoint_location"> <source>Determining breakpoint location...</source> <target state="translated">Определение положения точки останова...</target> <note /> </trans-unit> <trans-unit id="Determining_autos"> <source>Determining autos...</source> <target state="translated">Определение видимых переменных...</target> <note /> </trans-unit> <trans-unit id="Resolving_breakpoint_location"> <source>Resolving breakpoint location...</source> <target state="translated">Разрешение положения точки останова...</target> <note /> </trans-unit> <trans-unit id="Validating_breakpoint_location"> <source>Validating breakpoint location...</source> <target state="translated">Проверка положения точки останова...</target> <note /> </trans-unit> <trans-unit id="Getting_DataTip_text"> <source>Getting DataTip text...</source> <target state="translated">Получение текста подсказки (DataTip) по данным...</target> <note /> </trans-unit> <trans-unit id="Preview_unavailable"> <source>Preview unavailable</source> <target state="translated">Предпросмотр недоступен.</target> <note /> </trans-unit> <trans-unit id="Overrides_"> <source>Overrides</source> <target state="translated">Переопределяет</target> <note /> </trans-unit> <trans-unit id="Overridden_By"> <source>Overridden By</source> <target state="translated">Переопределяется</target> <note /> </trans-unit> <trans-unit id="Inherits_"> <source>Inherits</source> <target state="translated">Наследует</target> <note /> </trans-unit> <trans-unit id="Inherited_By"> <source>Inherited By</source> <target state="translated">Наследуется</target> <note /> </trans-unit> <trans-unit id="Implements_"> <source>Implements</source> <target state="translated">Реализует</target> <note /> </trans-unit> <trans-unit id="Implemented_By"> <source>Implemented By</source> <target state="translated">Реализуется</target> <note /> </trans-unit> <trans-unit id="Maximum_number_of_documents_are_open"> <source>Maximum number of documents are open.</source> <target state="translated">Открыто предельное число документов.</target> <note /> </trans-unit> <trans-unit id="Failed_to_create_document_in_miscellaneous_files_project"> <source>Failed to create document in miscellaneous files project.</source> <target state="translated">Не удалось создать документ в списке прочих файлов.</target> <note /> </trans-unit> <trans-unit id="Invalid_access"> <source>Invalid access.</source> <target state="translated">Недопустимый доступ.</target> <note /> </trans-unit> <trans-unit id="The_following_references_were_not_found_0_Please_locate_and_add_them_manually"> <source>The following references were not found. {0}Please locate and add them manually.</source> <target state="translated">Не найдены следующие ссылки. {0} Найдите и добавьте их вручную.</target> <note /> </trans-unit> <trans-unit id="End_position_must_be_start_position"> <source>End position must be &gt;= start position</source> <target state="translated">Конечное положение не должно быть меньше начального.</target> <note /> </trans-unit> <trans-unit id="Not_a_valid_value"> <source>Not a valid value</source> <target state="translated">Недопустимое значение</target> <note /> </trans-unit> <trans-unit id="_0_is_inherited"> <source>'{0}' is inherited</source> <target state="translated">"{0}" наследуется</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_abstract"> <source>'{0}' will be changed to abstract.</source> <target state="translated">Элемент "{0}" будет изменен на абстрактный.</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_non_static"> <source>'{0}' will be changed to non-static.</source> <target state="translated">Элемент "{0}" будет изменен на нестатический.</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_public"> <source>'{0}' will be changed to public.</source> <target state="translated">Элемент "{0}" будет изменен на открытый.</target> <note /> </trans-unit> <trans-unit id="generated_by_0_suffix"> <source>[generated by {0}]</source> <target state="translated">[создан генератором {0}]</target> <note>{0} is the name of a generator.</note> </trans-unit> <trans-unit id="generated_suffix"> <source>[generated]</source> <target state="translated">[создан генератором]</target> <note /> </trans-unit> <trans-unit id="given_workspace_doesn_t_support_undo"> <source>given workspace doesn't support undo</source> <target state="translated">заданная рабочая область не поддерживает отмену.</target> <note /> </trans-unit> <trans-unit id="Add_a_reference_to_0"> <source>Add a reference to '{0}'</source> <target state="translated">Добавить ссылку на "{0}"</target> <note /> </trans-unit> <trans-unit id="Event_type_is_invalid"> <source>Event type is invalid</source> <target state="translated">Тип события недопустим.</target> <note /> </trans-unit> <trans-unit id="Can_t_find_where_to_insert_member"> <source>Can't find where to insert member</source> <target state="translated">Не удается найти место вставки элемента.</target> <note /> </trans-unit> <trans-unit id="Can_t_rename_other_elements"> <source>Can't rename 'other' elements</source> <target state="translated">Не удается переименовать элементы "other".</target> <note /> </trans-unit> <trans-unit id="Unknown_rename_type"> <source>Unknown rename type</source> <target state="translated">Неизвестный тип переименования</target> <note /> </trans-unit> <trans-unit id="IDs_are_not_supported_for_this_symbol_type"> <source>IDs are not supported for this symbol type.</source> <target state="translated">Идентификаторы не поддерживаются для данного типа символов.</target> <note /> </trans-unit> <trans-unit id="Can_t_create_a_node_id_for_this_symbol_kind_colon_0"> <source>Can't create a node id for this symbol kind: '{0}'</source> <target state="translated">Не удается создать идентификатор узла для этого вида символов: "{0}".</target> <note /> </trans-unit> <trans-unit id="Project_References"> <source>Project References</source> <target state="translated">Ссылки проекта</target> <note /> </trans-unit> <trans-unit id="Base_Types"> <source>Base Types</source> <target state="translated">Базовые типы</target> <note /> </trans-unit> <trans-unit id="Miscellaneous_Files"> <source>Miscellaneous Files</source> <target state="translated">Прочие файлы</target> <note /> </trans-unit> <trans-unit id="Could_not_find_project_0"> <source>Could not find project '{0}'</source> <target state="translated">Не удалось найти проект "{0}".</target> <note /> </trans-unit> <trans-unit id="Could_not_find_location_of_folder_on_disk"> <source>Could not find location of folder on disk</source> <target state="translated">Не удалось найти путь к папке на диске.</target> <note /> </trans-unit> <trans-unit id="Assembly"> <source>Assembly </source> <target state="translated">Сборка </target> <note /> </trans-unit> <trans-unit id="Exceptions_colon"> <source>Exceptions:</source> <target state="translated">Исключения:</target> <note /> </trans-unit> <trans-unit id="Member_of_0"> <source>Member of {0}</source> <target state="translated">Элемент объекта {0}</target> <note /> </trans-unit> <trans-unit id="Parameters_colon1"> <source>Parameters:</source> <target state="translated">Параметры:</target> <note /> </trans-unit> <trans-unit id="Project"> <source>Project </source> <target state="translated">Проект </target> <note /> </trans-unit> <trans-unit id="Remarks_colon"> <source>Remarks:</source> <target state="translated">Примечания.</target> <note /> </trans-unit> <trans-unit id="Returns_colon"> <source>Returns:</source> <target state="translated">Возврат:</target> <note /> </trans-unit> <trans-unit id="Summary_colon"> <source>Summary:</source> <target state="translated">Сводка:</target> <note /> </trans-unit> <trans-unit id="Type_Parameters_colon"> <source>Type Parameters:</source> <target state="translated">Параметры типа:</target> <note /> </trans-unit> <trans-unit id="File_already_exists"> <source>File already exists</source> <target state="translated">Файл уже существует.</target> <note /> </trans-unit> <trans-unit id="File_path_cannot_use_reserved_keywords"> <source>File path cannot use reserved keywords</source> <target state="translated">В пути к файлу нельзя использовать зарезервированные ключевые слова.</target> <note /> </trans-unit> <trans-unit id="DocumentPath_is_illegal"> <source>DocumentPath is illegal</source> <target state="translated">Параметр DocumentPath недопустим.</target> <note /> </trans-unit> <trans-unit id="Project_Path_is_illegal"> <source>Project Path is illegal</source> <target state="translated">Путь проекта недопустим.</target> <note /> </trans-unit> <trans-unit id="Path_cannot_have_empty_filename"> <source>Path cannot have empty filename</source> <target state="translated">Имя файла в пути не может быть пустым.</target> <note /> </trans-unit> <trans-unit id="The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace"> <source>The given DocumentId did not come from the Visual Studio workspace.</source> <target state="translated">Указанный идентификатор документа DocumentId получен не из рабочей области Visual Studio.</target> <note /> </trans-unit> <trans-unit id="Project_colon_0_1_Use_the_dropdown_to_view_and_switch_to_other_projects_this_file_may_belong_to"> <source>Project: {0} ({1}) Use the dropdown to view and switch to other projects this file may belong to.</source> <target state="translated">Проект: {0} ({1}) Используйте раскрывающийся список для просмотра других проектов, к которым может относиться этот файл, и перехода к ним.</target> <note /> </trans-unit> <trans-unit id="_0_Use_the_dropdown_to_view_and_navigate_to_other_items_in_this_file"> <source>{0} Use the dropdown to view and navigate to other items in this file.</source> <target state="translated">{0} Для просмотра других элементов в этом файле используйте раскрывающийся список.</target> <note /> </trans-unit> <trans-unit id="Project_colon_0_Use_the_dropdown_to_view_and_switch_to_other_projects_this_file_may_belong_to"> <source>Project: {0} Use the dropdown to view and switch to other projects this file may belong to.</source> <target state="translated">Проект: {0} Используйте раскрывающийся список для просмотра других проектов, к которым может относиться этот файл, и перехода к ним.</target> <note /> </trans-unit> <trans-unit id="AnalyzerChangedOnDisk"> <source>AnalyzerChangedOnDisk</source> <target state="translated">AnalyzerChangedOnDisk</target> <note /> </trans-unit> <trans-unit id="The_analyzer_assembly_0_has_changed_Diagnostics_may_be_incorrect_until_Visual_Studio_is_restarted"> <source>The analyzer assembly '{0}' has changed. Diagnostics may be incorrect until Visual Studio is restarted.</source> <target state="translated">Сборка анализатора "{0}" была изменена. Перезапустите Visual Studio, в противном случае диагностика может быть неправильной.</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Diagnostics_Table_Data_Source"> <source>C#/VB Diagnostics Table Data Source</source> <target state="translated">Источник данных для таблицы диагностики C#/VB</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Todo_List_Table_Data_Source"> <source>C#/VB Todo List Table Data Source</source> <target state="translated">Источник данных для таблицы списка задач C#/VB</target> <note /> </trans-unit> <trans-unit id="Cancel"> <source>Cancel</source> <target state="translated">Отмена</target> <note /> </trans-unit> <trans-unit id="Deselect_All"> <source>_Deselect All</source> <target state="translated">_Отменить все</target> <note /> </trans-unit> <trans-unit id="Extract_Interface"> <source>Extract Interface</source> <target state="translated">Извлечь интерфейс</target> <note /> </trans-unit> <trans-unit id="Generated_name_colon"> <source>Generated name:</source> <target state="translated">Созданное название:</target> <note /> </trans-unit> <trans-unit id="New_file_name_colon"> <source>New _file name:</source> <target state="translated">Новое им_я файла:</target> <note /> </trans-unit> <trans-unit id="New_interface_name_colon"> <source>New _interface name:</source> <target state="translated">Новое название _интерфейса:</target> <note /> </trans-unit> <trans-unit id="OK"> <source>OK</source> <target state="translated">ОК</target> <note /> </trans-unit> <trans-unit id="Select_All"> <source>_Select All</source> <target state="translated">В_ыбрать все</target> <note /> </trans-unit> <trans-unit id="Select_public_members_to_form_interface"> <source>Select public _members to form interface</source> <target state="translated">Выбрать открытые _элементы для создания интерфейса</target> <note /> </trans-unit> <trans-unit id="Access_colon"> <source>_Access:</source> <target state="translated">Д_оступ:</target> <note /> </trans-unit> <trans-unit id="Add_to_existing_file"> <source>Add to _existing file</source> <target state="translated">Добавить в _существующий файл</target> <note /> </trans-unit> <trans-unit id="Change_Signature"> <source>Change Signature</source> <target state="translated">Изменить сигнатуру</target> <note /> </trans-unit> <trans-unit id="Create_new_file"> <source>_Create new file</source> <target state="translated">_Создать файл</target> <note /> </trans-unit> <trans-unit id="Default_"> <source>Default</source> <target state="translated">По умолчанию</target> <note /> </trans-unit> <trans-unit id="File_Name_colon"> <source>File Name:</source> <target state="translated">Имя файла:</target> <note /> </trans-unit> <trans-unit id="Generate_Type"> <source>Generate Type</source> <target state="translated">Сформировать тип</target> <note /> </trans-unit> <trans-unit id="Kind_colon"> <source>_Kind:</source> <target state="translated">_Вид:</target> <note /> </trans-unit> <trans-unit id="Location_colon"> <source>Location:</source> <target state="translated">Расположение:</target> <note /> </trans-unit> <trans-unit id="Modifier"> <source>Modifier</source> <target state="translated">Модификатор</target> <note /> </trans-unit> <trans-unit id="Name_colon1"> <source>Name:</source> <target state="translated">Название:</target> <note /> </trans-unit> <trans-unit id="Parameter"> <source>Parameter</source> <target state="translated">Параметр</target> <note /> </trans-unit> <trans-unit id="Parameters_colon2"> <source>Parameters:</source> <target state="translated">Параметры:</target> <note /> </trans-unit> <trans-unit id="Preview_method_signature_colon"> <source>Preview method signature:</source> <target state="translated">Предпросмотр сигнатуры метода:</target> <note /> </trans-unit> <trans-unit id="Preview_reference_changes"> <source>Preview reference changes</source> <target state="translated">Предпросмотр изменений в ссылках</target> <note /> </trans-unit> <trans-unit id="Project_colon"> <source>_Project:</source> <target state="translated">_Проект:</target> <note /> </trans-unit> <trans-unit id="Type"> <source>Type</source> <target state="translated">Тип</target> <note /> </trans-unit> <trans-unit id="Type_Details_colon"> <source>Type Details:</source> <target state="translated">Подробности о типе:</target> <note /> </trans-unit> <trans-unit id="Re_move"> <source>Re_move</source> <target state="translated">Уд_алить</target> <note /> </trans-unit> <trans-unit id="Restore"> <source>_Restore</source> <target state="translated">_Восстановить</target> <note /> </trans-unit> <trans-unit id="More_about_0"> <source>More about {0}</source> <target state="translated">{0}: подробнее</target> <note /> </trans-unit> <trans-unit id="Navigation_must_be_performed_on_the_foreground_thread"> <source>Navigation must be performed on the foreground thread.</source> <target state="translated">Навигация должна осуществляться в потоке переднего плана.</target> <note /> </trans-unit> <trans-unit id="bracket_plus_bracket"> <source>[+] </source> <target state="translated">[+] </target> <note /> </trans-unit> <trans-unit id="bracket_bracket"> <source>[-] </source> <target state="translated">[-] </target> <note /> </trans-unit> <trans-unit id="Reference_to_0_in_project_1"> <source>Reference to '{0}' in project '{1}'</source> <target state="translated">Ссылка на "{0}" в проекте "{1}"</target> <note /> </trans-unit> <trans-unit id="Unknown1"> <source>&lt;Unknown&gt;</source> <target state="translated">&lt;нет данных&gt;</target> <note /> </trans-unit> <trans-unit id="Analyzer_reference_to_0_in_project_1"> <source>Analyzer reference to '{0}' in project '{1}'</source> <target state="translated">Ссылка анализатора на "{0}" в проекте "{1}"</target> <note /> </trans-unit> <trans-unit id="Project_reference_to_0_in_project_1"> <source>Project reference to '{0}' in project '{1}'</source> <target state="translated">Ссылка проекта на "{0}" в проекте "{1}"</target> <note /> </trans-unit> <trans-unit id="AnalyzerDependencyConflict"> <source>AnalyzerDependencyConflict</source> <target state="translated">AnalyzerDependencyConflict</target> <note /> </trans-unit> <trans-unit id="Analyzer_assemblies_0_and_1_both_have_identity_2_but_different_contents_Only_one_will_be_loaded_and_analyzers_using_these_assemblies_may_not_run_correctly"> <source>Analyzer assemblies '{0}' and '{1}' both have identity '{2}' but different contents. Only one will be loaded and analyzers using these assemblies may not run correctly.</source> <target state="translated">Сборки анализатора "{0}" и "{1}" имеют одно и то же удостоверение ("{2}"), но разное содержимое. Будет загружена только одна сборка, и анализаторы, использующие эти сборки, могут работать неправильно.</target> <note /> </trans-unit> <trans-unit id="_0_references"> <source>{0} references</source> <target state="translated">Ссылок: {0}</target> <note /> </trans-unit> <trans-unit id="_1_reference"> <source>1 reference</source> <target state="translated">1 ссылка</target> <note /> </trans-unit> <trans-unit id="_0_encountered_an_error_and_has_been_disabled"> <source>'{0}' encountered an error and has been disabled.</source> <target state="translated">'Произошла ошибка, и анализатор "{0}" отключен.</target> <note /> </trans-unit> <trans-unit id="Enable"> <source>Enable</source> <target state="translated">Включить</target> <note /> </trans-unit> <trans-unit id="Enable_and_ignore_future_errors"> <source>Enable and ignore future errors</source> <target state="translated">Включить и пропускать будущие ошибки</target> <note /> </trans-unit> <trans-unit id="No_Changes"> <source>No Changes</source> <target state="translated">Изменений нет</target> <note /> </trans-unit> <trans-unit id="Current_block"> <source>Current block</source> <target state="translated">Текущий блок</target> <note /> </trans-unit> <trans-unit id="Determining_current_block"> <source>Determining current block.</source> <target state="translated">Определение текущего блока.</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Build_Table_Data_Source"> <source>C#/VB Build Table Data Source</source> <target state="translated">Источник данных для таблицы сборки C#/VB</target> <note /> </trans-unit> <trans-unit id="MissingAnalyzerReference"> <source>MissingAnalyzerReference</source> <target state="translated">MissingAnalyzerReference</target> <note /> </trans-unit> <trans-unit id="Analyzer_assembly_0_depends_on_1_but_it_was_not_found_Analyzers_may_not_run_correctly_unless_the_missing_assembly_is_added_as_an_analyzer_reference_as_well"> <source>Analyzer assembly '{0}' depends on '{1}' but it was not found. Analyzers may not run correctly unless the missing assembly is added as an analyzer reference as well.</source> <target state="translated">Сборка анализатора "{0}" зависит от "{1}", но последняя не найдена. Анализаторы могут работать неправильно, если не добавить отсутствующую сборку в качестве ссылки анализатора.</target> <note /> </trans-unit> <trans-unit id="Suppress_diagnostics"> <source>Suppress diagnostics</source> <target state="translated">Подавление диагностики</target> <note /> </trans-unit> <trans-unit id="Computing_suppressions_fix"> <source>Computing suppressions fix...</source> <target state="translated">Вычисление исправления для подавлений...</target> <note /> </trans-unit> <trans-unit id="Applying_suppressions_fix"> <source>Applying suppressions fix...</source> <target state="translated">Применяется исправление для подавлений...</target> <note /> </trans-unit> <trans-unit id="Remove_suppressions"> <source>Remove suppressions</source> <target state="translated">Удалить подавления</target> <note /> </trans-unit> <trans-unit id="Computing_remove_suppressions_fix"> <source>Computing remove suppressions fix...</source> <target state="translated">Вычисление исправления для удаления подавлений...</target> <note /> </trans-unit> <trans-unit id="Applying_remove_suppressions_fix"> <source>Applying remove suppressions fix...</source> <target state="translated">Применяется исправление для удаления подавлений...</target> <note /> </trans-unit> <trans-unit id="This_workspace_only_supports_opening_documents_on_the_UI_thread"> <source>This workspace only supports opening documents on the UI thread.</source> <target state="translated">Эта рабочая область поддерживает открытие документов только в потоке пользовательского интерфейса.</target> <note /> </trans-unit> <trans-unit id="This_workspace_does_not_support_updating_Visual_Basic_parse_options"> <source>This workspace does not support updating Visual Basic parse options.</source> <target state="translated">Эта рабочая область не поддерживает обновление параметров синтаксического анализа Visual Basic.</target> <note /> </trans-unit> <trans-unit id="Synchronize_0"> <source>Synchronize {0}</source> <target state="translated">Синхронизировать {0}</target> <note /> </trans-unit> <trans-unit id="Synchronizing_with_0"> <source>Synchronizing with {0}...</source> <target state="translated">Синхронизация с {0}...</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_has_suspended_some_advanced_features_to_improve_performance"> <source>Visual Studio has suspended some advanced features to improve performance.</source> <target state="translated">Visual Studio временно отключила некоторые дополнительные возможности, чтобы повысить производительность.</target> <note /> </trans-unit> <trans-unit id="Installing_0"> <source>Installing '{0}'</source> <target state="translated">Идет установка "{0}"</target> <note /> </trans-unit> <trans-unit id="Installing_0_completed"> <source>Installing '{0}' completed</source> <target state="translated">Установка "{0}" завершена</target> <note /> </trans-unit> <trans-unit id="Package_install_failed_colon_0"> <source>Package install failed: {0}</source> <target state="translated">Сбой при установке пакета: {0}</target> <note /> </trans-unit> <trans-unit id="Unknown2"> <source>&lt;Unknown&gt;</source> <target state="translated">&lt;нет данных&gt;</target> <note /> </trans-unit> <trans-unit id="No"> <source>No</source> <target state="translated">Нет</target> <note /> </trans-unit> <trans-unit id="Yes"> <source>Yes</source> <target state="translated">Да</target> <note /> </trans-unit> <trans-unit id="Choose_a_Symbol_Specification_and_a_Naming_Style"> <source>Choose a Symbol Specification and a Naming Style.</source> <target state="translated">Выберите спецификацию символов и стиль именования.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Naming_Rule"> <source>Enter a title for this Naming Rule.</source> <target state="translated">Введите название для этого правила именования.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Naming_Style"> <source>Enter a title for this Naming Style.</source> <target state="translated">Введите название для этого стиля именования.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Symbol_Specification"> <source>Enter a title for this Symbol Specification.</source> <target state="translated">Введите название для этой спецификации символа.</target> <note /> </trans-unit> <trans-unit id="Accessibilities_can_match_any"> <source>Accessibilities (can match any)</source> <target state="translated">Модификаторы доступности (соответствие любому)</target> <note /> </trans-unit> <trans-unit id="Capitalization_colon"> <source>Capitalization:</source> <target state="translated">Написание прописными буквами:</target> <note /> </trans-unit> <trans-unit id="all_lower"> <source>all lower</source> <target state="translated">все строчные</target> <note /> </trans-unit> <trans-unit id="ALL_UPPER"> <source>ALL UPPER</source> <target state="translated">ВСЕ ПРОПИСНЫЕ</target> <note /> </trans-unit> <trans-unit id="camel_Case_Name"> <source>camel Case Name</source> <target state="translated">Название в "Верблюжьем" стиле c первой прописной буквой</target> <note /> </trans-unit> <trans-unit id="First_word_upper"> <source>First word upper</source> <target state="translated">Первое слово с прописной буквы</target> <note /> </trans-unit> <trans-unit id="Pascal_Case_Name"> <source>Pascal Case Name</source> <target state="translated">Название в регистре Pascal</target> <note /> </trans-unit> <trans-unit id="Severity_colon"> <source>Severity:</source> <target state="translated">Серьезность:</target> <note /> </trans-unit> <trans-unit id="Modifiers_must_match_all"> <source>Modifiers (must match all)</source> <target state="translated">Модификаторы (должны соответствовать всему)</target> <note /> </trans-unit> <trans-unit id="Name_colon2"> <source>Name:</source> <target state="translated">Название:</target> <note /> </trans-unit> <trans-unit id="Naming_Rule"> <source>Naming Rule</source> <target state="translated">Правило именования</target> <note /> </trans-unit> <trans-unit id="Naming_Style"> <source>Naming Style</source> <target state="translated">Стиль именования</target> <note /> </trans-unit> <trans-unit id="Naming_Style_colon"> <source>Naming Style:</source> <target state="translated">Стиль именования:</target> <note /> </trans-unit> <trans-unit id="Naming_Rules_allow_you_to_define_how_particular_sets_of_symbols_should_be_named_and_how_incorrectly_named_symbols_should_be_handled"> <source>Naming Rules allow you to define how particular sets of symbols should be named and how incorrectly-named symbols should be handled.</source> <target state="translated">Правила именования позволяют определить, как должны именоваться определенные наборы символов и как должны обрабатываться неправильно названные символы.</target> <note /> </trans-unit> <trans-unit id="The_first_matching_top_level_Naming_Rule_is_used_by_default_when_naming_a_symbol_while_any_special_cases_are_handled_by_a_matching_child_rule"> <source>The first matching top-level Naming Rule is used by default when naming a symbol, while any special cases are handled by a matching child rule.</source> <target state="translated">По умолчанию при именовании символа используется первое соответствующее правило именования верхнего уровня, а все особые случаи обрабатываются соответствующим дочерним правилом.</target> <note /> </trans-unit> <trans-unit id="Naming_Style_Title_colon"> <source>Naming Style Title:</source> <target state="translated">Название стиля именования:</target> <note /> </trans-unit> <trans-unit id="Parent_Rule_colon"> <source>Parent Rule:</source> <target state="translated">Родительское правило:</target> <note /> </trans-unit> <trans-unit id="Required_Prefix_colon"> <source>Required Prefix:</source> <target state="translated">Необходимый префикс:</target> <note /> </trans-unit> <trans-unit id="Required_Suffix_colon"> <source>Required Suffix:</source> <target state="translated">Необходимый суффикс:</target> <note /> </trans-unit> <trans-unit id="Sample_Identifier_colon"> <source>Sample Identifier:</source> <target state="translated">Пример идентификатора:</target> <note /> </trans-unit> <trans-unit id="Symbol_Kinds_can_match_any"> <source>Symbol Kinds (can match any)</source> <target state="translated">Виды символов (соответствие любому)</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification"> <source>Symbol Specification</source> <target state="translated">Спецификация символа</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification_colon"> <source>Symbol Specification:</source> <target state="translated">Спецификация символа:</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification_Title_colon"> <source>Symbol Specification Title:</source> <target state="translated">Название спецификации символа:</target> <note /> </trans-unit> <trans-unit id="Word_Separator_colon"> <source>Word Separator:</source> <target state="translated">Разделитель слов:</target> <note /> </trans-unit> <trans-unit id="example"> <source>example</source> <target state="translated">пример</target> <note>IdentifierWord_Example and IdentifierWord_Identifier are combined (with prefixes, suffixes, and word separators) into an example identifier name in the NamingStyle UI.</note> </trans-unit> <trans-unit id="identifier"> <source>identifier</source> <target state="translated">идентификатор</target> <note>IdentifierWord_Example and IdentifierWord_Identifier are combined (with prefixes, suffixes, and word separators) into an example identifier name in the NamingStyle UI.</note> </trans-unit> <trans-unit id="Install_0"> <source>Install '{0}'</source> <target state="translated">Установить "{0}"</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0"> <source>Uninstalling '{0}'</source> <target state="translated">Идет удаление "{0}"</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0_completed"> <source>Uninstalling '{0}' completed</source> <target state="translated">Удаление "{0}" завершено.</target> <note /> </trans-unit> <trans-unit id="Uninstall_0"> <source>Uninstall '{0}'</source> <target state="translated">Удалить "{0}"</target> <note /> </trans-unit> <trans-unit id="Package_uninstall_failed_colon_0"> <source>Package uninstall failed: {0}</source> <target state="translated">Сбой при удалении пакета: {0}</target> <note /> </trans-unit> <trans-unit id="Error_encountered_while_loading_the_project_Some_project_features_such_as_full_solution_analysis_for_the_failed_project_and_projects_that_depend_on_it_have_been_disabled"> <source>Error encountered while loading the project. Some project features, such as full solution analysis for the failed project and projects that depend on it, have been disabled.</source> <target state="translated">Произошла ошибка при загрузке проекта. Некоторые возможности проекта, например полный анализ решения для неработоспособного проекта и зависящих от него проектов, были отключены.</target> <note /> </trans-unit> <trans-unit id="Project_loading_failed"> <source>Project loading failed.</source> <target state="translated">Сбой при загрузке проекта.</target> <note /> </trans-unit> <trans-unit id="To_see_what_caused_the_issue_please_try_below_1_Close_Visual_Studio_long_paragraph_follows"> <source>To see what caused the issue, please try below. 1. Close Visual Studio 2. Open a Visual Studio Developer Command Prompt 3. Set environment variable “TraceDesignTime” to true (set TraceDesignTime=true) 4. Delete .vs directory/.suo file 5. Restart VS from the command prompt you set the environment variable (devenv) 6. Open the solution 7. Check '{0}' and look for the failed tasks (FAILED)</source> <target state="translated">Чтобы узнать, что вызвало проблему, попробуйте сделать следующее. 1. Закройте Visual Studio. 2. Откройте командную строку разработчика Visual Studio. 3. Присвойте переменной "TraceDesignTime" значение true (set TraceDesignTime=true). 4. Удалите файл ".vs directory/.suo". 5. Перезапустите VS из командной строки, в которой вы присвоили значение переменной среды (devenv). 6. Откройте решение. 7. Проверьте "{0}" и найдите задачи, которые завершились сбоем (FAILED).</target> <note /> </trans-unit> <trans-unit id="Additional_information_colon"> <source>Additional information:</source> <target state="translated">Дополнительная информация:</target> <note /> </trans-unit> <trans-unit id="Installing_0_failed_Additional_information_colon_1"> <source>Installing '{0}' failed. Additional information: {1}</source> <target state="translated">Сбой при установке "{0}". Дополнительная информация: {1}</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0_failed_Additional_information_colon_1"> <source>Uninstalling '{0}' failed. Additional information: {1}</source> <target state="translated">Сбой при удалении "{0}". Дополнительная информация: {1}</target> <note /> </trans-unit> <trans-unit id="Move_0_below_1"> <source>Move {0} below {1}</source> <target state="translated">Переместить {0} под {1}</target> <note>{0} and {1} are parameter descriptions</note> </trans-unit> <trans-unit id="Move_0_above_1"> <source>Move {0} above {1}</source> <target state="translated">Переместить {0} над {1}</target> <note>{0} and {1} are parameter descriptions</note> </trans-unit> <trans-unit id="Remove_0"> <source>Remove {0}</source> <target state="translated">Удалить {0}</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Restore_0"> <source>Restore {0}</source> <target state="translated">Восстановить {0}</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Re_enable"> <source>Re-enable</source> <target state="translated">Повторно включить</target> <note /> </trans-unit> <trans-unit id="Learn_more"> <source>Learn more</source> <target state="translated">Подробнее...</target> <note /> </trans-unit> <trans-unit id="Prefer_framework_type"> <source>Prefer framework type</source> <target state="translated">Предпочитать тип платформы</target> <note /> </trans-unit> <trans-unit id="Prefer_predefined_type"> <source>Prefer predefined type</source> <target state="translated">Предпочитать предопределенный тип</target> <note /> </trans-unit> <trans-unit id="Copy_to_Clipboard"> <source>Copy to Clipboard</source> <target state="translated">Копировать в буфер обмена</target> <note /> </trans-unit> <trans-unit id="Close"> <source>Close</source> <target state="translated">Закрыть</target> <note /> </trans-unit> <trans-unit id="Unknown_parameters"> <source>&lt;Unknown Parameters&gt;</source> <target state="translated">&lt;Неизвестные параметры&gt;</target> <note /> </trans-unit> <trans-unit id="End_of_inner_exception_stack"> <source>--- End of inner exception stack trace ---</source> <target state="translated">--- Конец трассировки внутреннего стека исключений ---</target> <note /> </trans-unit> <trans-unit id="For_locals_parameters_and_members"> <source>For locals, parameters and members</source> <target state="translated">Для локальных переменных, параметров и элементов</target> <note /> </trans-unit> <trans-unit id="For_member_access_expressions"> <source>For member access expressions</source> <target state="translated">Для выражений доступа к элементам</target> <note /> </trans-unit> <trans-unit id="Prefer_object_initializer"> <source>Prefer object initializer</source> <target state="translated">Предпочитать инициализатор объекта</target> <note /> </trans-unit> <trans-unit id="Expression_preferences_colon"> <source>Expression preferences:</source> <target state="translated">Предпочтения в отношении выражения:</target> <note /> </trans-unit> <trans-unit id="Block_Structure_Guides"> <source>Block Structure Guides</source> <target state="translated">Направляющие для структуры блоков</target> <note /> </trans-unit> <trans-unit id="Outlining"> <source>Outlining</source> <target state="translated">Структура</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_code_level_constructs"> <source>Show guides for code level constructs</source> <target state="translated">Показывать направляющие для конструкций уровня кода</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_comments_and_preprocessor_regions"> <source>Show guides for comments and preprocessor regions</source> <target state="translated">Показывать направляющие для комментариев и областей препроцессора</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_declaration_level_constructs"> <source>Show guides for declaration level constructs</source> <target state="translated">Показывать направляющие для конструкций уровня объявления</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_code_level_constructs"> <source>Show outlining for code level constructs</source> <target state="translated">Показывать структуру для конструкций уровня кода</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_comments_and_preprocessor_regions"> <source>Show outlining for comments and preprocessor regions</source> <target state="translated">Показывать структуру для комментариев и областей препроцессора</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_declaration_level_constructs"> <source>Show outlining for declaration level constructs</source> <target state="translated">Показывать структуру для конструкций уровня объявления</target> <note /> </trans-unit> <trans-unit id="Variable_preferences_colon"> <source>Variable preferences:</source> <target state="translated">Предпочтения в отношении переменных:</target> <note /> </trans-unit> <trans-unit id="Prefer_inlined_variable_declaration"> <source>Prefer inlined variable declaration</source> <target state="translated">Предпочитать встроенное объявление переменной</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Использовать тело выражения для методов</target> <note /> </trans-unit> <trans-unit id="Code_block_preferences_colon"> <source>Code block preferences:</source> <target state="translated">Предпочтения в отношении блока кода:</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Использовать тело выражения для методов доступа</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Использовать тело выражения для конструкторов</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Использовать тело выражения для индексаторов</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Использовать тело выражения для операторов</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Использовать тело выражения для свойств</target> <note /> </trans-unit> <trans-unit id="Some_naming_rules_are_incomplete_Please_complete_or_remove_them"> <source>Some naming rules are incomplete. Please complete or remove them.</source> <target state="translated">Некоторые правила именования являются неполными. Дополните или удалите их.</target> <note /> </trans-unit> <trans-unit id="Manage_specifications"> <source>Manage specifications</source> <target state="translated">Управление спецификациями</target> <note /> </trans-unit> <trans-unit id="Reorder"> <source>Reorder</source> <target state="translated">Переупорядочить</target> <note /> </trans-unit> <trans-unit id="Severity"> <source>Severity</source> <target state="translated">Серьезность</target> <note /> </trans-unit> <trans-unit id="Specification"> <source>Specification</source> <target state="translated">Спецификация</target> <note /> </trans-unit> <trans-unit id="Required_Style"> <source>Required Style</source> <target state="translated">Необходимый стиль</target> <note /> </trans-unit> <trans-unit id="This_item_cannot_be_deleted_because_it_is_used_by_an_existing_Naming_Rule"> <source>This item cannot be deleted because it is used by an existing Naming Rule.</source> <target state="translated">Невозможно удалить этот элемент, так как он используется существующим правилом именования.</target> <note /> </trans-unit> <trans-unit id="Prefer_collection_initializer"> <source>Prefer collection initializer</source> <target state="translated">Предпочитать инициализатор коллекции</target> <note /> </trans-unit> <trans-unit id="Prefer_coalesce_expression"> <source>Prefer coalesce expression</source> <target state="translated">Предпочитать объединенное выражение</target> <note /> </trans-unit> <trans-unit id="Collapse_regions_when_collapsing_to_definitions"> <source>Collapse #regions when collapsing to definitions</source> <target state="translated">Сворачивать #regions при сворачивании в определения</target> <note /> </trans-unit> <trans-unit id="Prefer_null_propagation"> <source>Prefer null propagation</source> <target state="translated">Предпочитать распространение значений NULL</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_tuple_name"> <source>Prefer explicit tuple name</source> <target state="translated">Предпочитать явное имя кортежа</target> <note /> </trans-unit> <trans-unit id="Description"> <source>Description</source> <target state="translated">Описание</target> <note /> </trans-unit> <trans-unit id="Preference"> <source>Preference</source> <target state="translated">Предпочтения</target> <note /> </trans-unit> <trans-unit id="Implement_Interface_or_Abstract_Class"> <source>Implement Interface or Abstract Class</source> <target state="translated">Реализовать интерфейс или абстрактный класс</target> <note /> </trans-unit> <trans-unit id="For_a_given_symbol_only_the_topmost_rule_with_a_matching_Specification_will_be_applied_Violation_of_that_rules_Required_Style_will_be_reported_at_the_chosen_Severity_level"> <source>For a given symbol, only the topmost rule with a matching 'Specification' will be applied. Violation of that rule's 'Required Style' will be reported at the chosen 'Severity' level.</source> <target state="translated">Для указанного символа будет применено только самое верхнее правило соответствующей спецификации. При нарушении требуемого стиля для этого правила будет создано оповещение указанного уровня серьезности.</target> <note /> </trans-unit> <trans-unit id="at_the_end"> <source>at the end</source> <target state="translated">в конец</target> <note /> </trans-unit> <trans-unit id="When_inserting_properties_events_and_methods_place_them"> <source>When inserting properties, events and methods, place them:</source> <target state="translated">При вставке свойств, методов и событий помещать их:</target> <note /> </trans-unit> <trans-unit id="with_other_members_of_the_same_kind"> <source>with other members of the same kind</source> <target state="translated">вместе с другими элементами того же типа</target> <note /> </trans-unit> <trans-unit id="Prefer_braces"> <source>Prefer braces</source> <target state="translated">Предпочитать фигурные скобки</target> <note /> </trans-unit> <trans-unit id="Over_colon"> <source>Over:</source> <target state="translated">А не:</target> <note /> </trans-unit> <trans-unit id="Prefer_colon"> <source>Prefer:</source> <target state="translated">Предпочтение:</target> <note /> </trans-unit> <trans-unit id="or"> <source>or</source> <target state="translated">или</target> <note /> </trans-unit> <trans-unit id="built_in_types"> <source>built-in types</source> <target state="translated">встроенные типы</target> <note /> </trans-unit> <trans-unit id="everywhere_else"> <source>everywhere else</source> <target state="translated">в любое другое место</target> <note /> </trans-unit> <trans-unit id="type_is_apparent_from_assignment_expression"> <source>type is apparent from assignment expression</source> <target state="translated">тип предполагается из выражения назначения</target> <note /> </trans-unit> <trans-unit id="Move_down"> <source>Move down</source> <target state="translated">Переместить вниз</target> <note /> </trans-unit> <trans-unit id="Move_up"> <source>Move up</source> <target state="translated">Переместить вверх</target> <note /> </trans-unit> <trans-unit id="Remove"> <source>Remove</source> <target state="translated">Удалить</target> <note /> </trans-unit> <trans-unit id="Pick_members"> <source>Pick members</source> <target state="translated">Выбрать члены</target> <note /> </trans-unit> <trans-unit id="Unfortunately_a_process_used_by_Visual_Studio_has_encountered_an_unrecoverable_error_We_recommend_saving_your_work_and_then_closing_and_restarting_Visual_Studio"> <source>Unfortunately, a process used by Visual Studio has encountered an unrecoverable error. We recommend saving your work, and then closing and restarting Visual Studio.</source> <target state="translated">В процессе, используемом Visual Studio, произошла неустранимая ошибка. Рекомендуется сохранить изменения, а затем закрыть и снова запустить Visual Studio.</target> <note /> </trans-unit> <trans-unit id="Add_a_symbol_specification"> <source>Add a symbol specification</source> <target state="translated">Добавить спецификацию символа</target> <note /> </trans-unit> <trans-unit id="Remove_symbol_specification"> <source>Remove symbol specification</source> <target state="translated">Удалить спецификацию символа</target> <note /> </trans-unit> <trans-unit id="Add_item"> <source>Add item</source> <target state="translated">Добавить элемент</target> <note /> </trans-unit> <trans-unit id="Edit_item"> <source>Edit item</source> <target state="translated">Изменить элемент</target> <note /> </trans-unit> <trans-unit id="Remove_item"> <source>Remove item</source> <target state="translated">Удалить элемент</target> <note /> </trans-unit> <trans-unit id="Add_a_naming_rule"> <source>Add a naming rule</source> <target state="translated">Добавить правило именования</target> <note /> </trans-unit> <trans-unit id="Remove_naming_rule"> <source>Remove naming rule</source> <target state="translated">Удалить правило именования</target> <note /> </trans-unit> <trans-unit id="VisualStudioWorkspace_TryApplyChanges_cannot_be_called_from_a_background_thread"> <source>VisualStudioWorkspace.TryApplyChanges cannot be called from a background thread.</source> <target state="translated">VisualStudioWorkspace.TryApplyChanges нельзя вызывать из фонового потока.</target> <note /> </trans-unit> <trans-unit id="prefer_throwing_properties"> <source>prefer throwing properties</source> <target state="translated">предпочитать свойства, создающие исключения</target> <note /> </trans-unit> <trans-unit id="When_generating_properties"> <source>When generating properties:</source> <target state="translated">При создании свойств:</target> <note /> </trans-unit> <trans-unit id="Options"> <source>Options</source> <target state="translated">Параметры</target> <note /> </trans-unit> <trans-unit id="Never_show_this_again"> <source>Never show this again</source> <target state="translated">Больше не показывать</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_default_expression"> <source>Prefer simple 'default' expression</source> <target state="translated">Предпочитать простое выражение default</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_tuple_names"> <source>Prefer inferred tuple element names</source> <target state="translated">Предпочитать выводимые имена элементов кортежа</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_anonymous_type_member_names"> <source>Prefer inferred anonymous type member names</source> <target state="translated">Предпочитать выводимые имена членов анонимного типа</target> <note /> </trans-unit> <trans-unit id="Preview_pane"> <source>Preview pane</source> <target state="translated">Область просмотра</target> <note /> </trans-unit> <trans-unit id="Analysis"> <source>Analysis</source> <target state="translated">Анализ</target> <note /> </trans-unit> <trans-unit id="Fade_out_unreachable_code"> <source>Fade out unreachable code</source> <target state="translated">Скрывать недостижимый код</target> <note /> </trans-unit> <trans-unit id="Fading"> <source>Fading</source> <target state="translated">Исчезание</target> <note /> </trans-unit> <trans-unit id="Prefer_local_function_over_anonymous_function"> <source>Prefer local function over anonymous function</source> <target state="translated">Предпочитать локальную функцию анонимной функции</target> <note /> </trans-unit> <trans-unit id="Prefer_deconstructed_variable_declaration"> <source>Prefer deconstructed variable declaration</source> <target state="translated">Предпочитать деконструированное объявление переменной</target> <note /> </trans-unit> <trans-unit id="External_reference_found"> <source>External reference found</source> <target state="translated">Найдена внешняя ссылка.</target> <note /> </trans-unit> <trans-unit id="No_references_found_to_0"> <source>No references found to '{0}'</source> <target state="translated">Ссылки не найдены в "{0}".</target> <note /> </trans-unit> <trans-unit id="Search_found_no_results"> <source>Search found no results</source> <target state="translated">Поиск не дал результатов.</target> <note /> </trans-unit> <trans-unit id="analyzer_Prefer_auto_properties"> <source>Prefer auto properties</source> <target state="translated">Предпочитать автосвойства</target> <note /> </trans-unit> <trans-unit id="codegen_prefer_auto_properties"> <source>prefer auto properties</source> <target state="translated">предпочитать автосвойства</target> <note /> </trans-unit> <trans-unit id="ModuleHasBeenUnloaded"> <source>Module has been unloaded.</source> <target state="translated">Модуль был выгружен.</target> <note /> </trans-unit> <trans-unit id="Enable_navigation_to_decompiled_sources"> <source>Enable navigation to decompiled sources</source> <target state="needs-review-translation">Включить переход к декомпилированным источникам (экспериментальная функция)</target> <note /> </trans-unit> <trans-unit id="Code_style_header_use_editor_config"> <source>Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info</source> <target state="translated">Файл EditorConfig может переопределять локальные параметры, настроенные на этой странице, только для этого компьютера. Чтобы эти параметры были привязаны к решению, используйте файлы EditorConfig. Дополнительные сведения.</target> <note /> </trans-unit> <trans-unit id="Sync_Class_View"> <source>Sync Class View</source> <target state="translated">Синхронизировать представление классов</target> <note /> </trans-unit> <trans-unit id="Analyzing_0"> <source>Analyzing '{0}'</source> <target state="translated">Выполняется анализ "{0}"</target> <note /> </trans-unit> <trans-unit id="Manage_naming_styles"> <source>Manage naming styles</source> <target state="translated">Управление стилями именования</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_assignments"> <source>Prefer conditional expression over 'if' with assignments</source> <target state="translated">Предпочитать условное выражение оператору if в назначениях</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_returns"> <source>Prefer conditional expression over 'if' with returns</source> <target state="translated">Предпочитать условное выражение оператору if в операторах return</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/CSharp/Portable/Binder/PatternMethodLookupResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.CSharp { internal enum PatternLookupResult { /// <summary> /// The Lookup was successful /// </summary> Success, /// <summary> /// A member was found, but it was not a method /// </summary> NotAMethod, /// <summary> /// A member was found, but it was not callable /// </summary> NotCallable, /// <summary> /// The lookup failed to find anything /// </summary> NoResults, /// <summary> /// One or more errors occurred while performing the lookup /// </summary> ResultHasErrors } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.CSharp { internal enum PatternLookupResult { /// <summary> /// The Lookup was successful /// </summary> Success, /// <summary> /// A member was found, but it was not a method /// </summary> NotAMethod, /// <summary> /// A member was found, but it was not callable /// </summary> NotCallable, /// <summary> /// The lookup failed to find anything /// </summary> NoResults, /// <summary> /// One or more errors occurred while performing the lookup /// </summary> ResultHasErrors } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioAddSolutionItemService.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.Concurrent; using System.Composition; using System.IO; using System.Threading; using EnvDTE; using EnvDTE80; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { [Export] [ExportWorkspaceService(typeof(IAddSolutionItemService)), Shared] internal partial class VisualStudioAddSolutionItemService : IAddSolutionItemService { private const string SolutionItemsFolderName = "Solution Items"; private readonly object _gate = new(); private readonly IThreadingContext _threadingContext; private readonly ConcurrentDictionary<string, FileChangeTracker> _fileChangeTrackers; private DTE? _dte; private IVsFileChangeEx? _fileChangeService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioAddSolutionItemService( IThreadingContext threadingContext) { _threadingContext = threadingContext; _fileChangeTrackers = new ConcurrentDictionary<string, FileChangeTracker>(StringComparer.OrdinalIgnoreCase); } public void Initialize(IServiceProvider serviceProvider) { _dte = (DTE)serviceProvider.GetService(typeof(DTE)); _fileChangeService = (IVsFileChangeEx)serviceProvider.GetService(typeof(SVsFileChangeEx)); } public void TrackFilePathAndAddSolutionItemWhenFileCreated(string filePath) { if (_fileChangeService != null && PathUtilities.IsAbsolute(filePath) && FileExistsWithGuard(filePath) == false) { // Setup a new file change tracker to track file path and // add newly created file as solution item. _fileChangeTrackers.GetOrAdd(filePath, CreateTracker); } return; // Local functions FileChangeTracker CreateTracker(string filePath) { var tracker = new FileChangeTracker(_fileChangeService, filePath, _VSFILECHANGEFLAGS.VSFILECHG_Add); tracker.UpdatedOnDisk += OnFileAdded; _ = tracker.StartFileChangeListeningAsync(); return tracker; } } private void OnFileAdded(object sender, EventArgs e) { var tracker = (FileChangeTracker)sender; var filePath = tracker.FilePath; _fileChangeTrackers.TryRemove(filePath, out _); AddSolutionItemAsync(filePath, CancellationToken.None).Wait(); tracker.UpdatedOnDisk -= OnFileAdded; tracker.Dispose(); } public async Task AddSolutionItemAsync(string filePath, CancellationToken cancellationToken) { if (_dte == null) { return; } await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); lock (_gate) { var solution = (Solution2)_dte.Solution; if (!TryGetExistingSolutionItemsFolder(solution, filePath, out var solutionItemsFolder, out var hasExistingSolutionItem)) { solutionItemsFolder = solution.AddSolutionFolder("Solution Items"); } if (!hasExistingSolutionItem && solutionItemsFolder != null && FileExistsWithGuard(filePath) == true) { solutionItemsFolder.ProjectItems.AddFromFile(filePath); solution.SaveAs(solution.FileName); } } } private static bool? FileExistsWithGuard(string filePath) { try { return File.Exists(filePath); } catch (IOException) { return null; } } public static bool TryGetExistingSolutionItemsFolder(Solution2 solution, string filePath, out EnvDTE.Project? solutionItemsFolder, out bool hasExistingSolutionItem) { solutionItemsFolder = null; hasExistingSolutionItem = false; var fileName = PathUtilities.GetFileName(filePath); foreach (Project project in solution.Projects) { if (project.Kind == EnvDTE.Constants.vsProjectKindSolutionItems && project.Name == SolutionItemsFolderName) { solutionItemsFolder = project; foreach (ProjectItem projectItem in solutionItemsFolder.ProjectItems) { if (fileName == projectItem.Name) { hasExistingSolutionItem = true; break; } } return true; } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Composition; using System.IO; using System.Threading; using EnvDTE; using EnvDTE80; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { [Export] [ExportWorkspaceService(typeof(IAddSolutionItemService)), Shared] internal partial class VisualStudioAddSolutionItemService : IAddSolutionItemService { private const string SolutionItemsFolderName = "Solution Items"; private readonly object _gate = new(); private readonly IThreadingContext _threadingContext; private readonly ConcurrentDictionary<string, FileChangeTracker> _fileChangeTrackers; private DTE? _dte; private IVsFileChangeEx? _fileChangeService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioAddSolutionItemService( IThreadingContext threadingContext) { _threadingContext = threadingContext; _fileChangeTrackers = new ConcurrentDictionary<string, FileChangeTracker>(StringComparer.OrdinalIgnoreCase); } public void Initialize(IServiceProvider serviceProvider) { _dte = (DTE)serviceProvider.GetService(typeof(DTE)); _fileChangeService = (IVsFileChangeEx)serviceProvider.GetService(typeof(SVsFileChangeEx)); } public void TrackFilePathAndAddSolutionItemWhenFileCreated(string filePath) { if (_fileChangeService != null && PathUtilities.IsAbsolute(filePath) && FileExistsWithGuard(filePath) == false) { // Setup a new file change tracker to track file path and // add newly created file as solution item. _fileChangeTrackers.GetOrAdd(filePath, CreateTracker); } return; // Local functions FileChangeTracker CreateTracker(string filePath) { var tracker = new FileChangeTracker(_fileChangeService, filePath, _VSFILECHANGEFLAGS.VSFILECHG_Add); tracker.UpdatedOnDisk += OnFileAdded; _ = tracker.StartFileChangeListeningAsync(); return tracker; } } private void OnFileAdded(object sender, EventArgs e) { var tracker = (FileChangeTracker)sender; var filePath = tracker.FilePath; _fileChangeTrackers.TryRemove(filePath, out _); AddSolutionItemAsync(filePath, CancellationToken.None).Wait(); tracker.UpdatedOnDisk -= OnFileAdded; tracker.Dispose(); } public async Task AddSolutionItemAsync(string filePath, CancellationToken cancellationToken) { if (_dte == null) { return; } await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); lock (_gate) { var solution = (Solution2)_dte.Solution; if (!TryGetExistingSolutionItemsFolder(solution, filePath, out var solutionItemsFolder, out var hasExistingSolutionItem)) { solutionItemsFolder = solution.AddSolutionFolder("Solution Items"); } if (!hasExistingSolutionItem && solutionItemsFolder != null && FileExistsWithGuard(filePath) == true) { solutionItemsFolder.ProjectItems.AddFromFile(filePath); solution.SaveAs(solution.FileName); } } } private static bool? FileExistsWithGuard(string filePath) { try { return File.Exists(filePath); } catch (IOException) { return null; } } public static bool TryGetExistingSolutionItemsFolder(Solution2 solution, string filePath, out EnvDTE.Project? solutionItemsFolder, out bool hasExistingSolutionItem) { solutionItemsFolder = null; hasExistingSolutionItem = false; var fileName = PathUtilities.GetFileName(filePath); foreach (Project project in solution.Projects) { if (project.Kind == EnvDTE.Constants.vsProjectKindSolutionItems && project.Name == SolutionItemsFolderName) { solutionItemsFolder = project; foreach (ProjectItem projectItem in solutionItemsFolder.ProjectItems) { if (fileName == projectItem.Name) { hasExistingSolutionItem = true; break; } } return true; } } return false; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Features/Core/Portable/EditAndContinue/Remote/RemoteDebuggingSessionProxy.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class RemoteDebuggingSessionProxy : IActiveStatementSpanProvider, IDisposable { private readonly IDisposable? _connection; private readonly DebuggingSessionId _sessionId; private readonly Workspace _workspace; public RemoteDebuggingSessionProxy(Workspace workspace, IDisposable? connection, DebuggingSessionId sessionId) { _connection = connection; _sessionId = sessionId; _workspace = workspace; } public void Dispose() { _connection?.Dispose(); } private IEditAndContinueWorkspaceService GetLocalService() => _workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); public async ValueTask BreakStateChangedAsync(IDiagnosticAnalyzerService diagnosticService, bool inBreakState, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().BreakStateChanged(_sessionId, inBreakState, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.BreakStateChangedAsync(_sessionId, inBreakState, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask EndDebuggingSessionAsync(Solution compileTimeSolution, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().EndDebuggingSession(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.EndDebuggingSessionAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } var designTimeDocumentsToReanalyze = await CompileTimeSolutionProvider.GetDesignTimeDocumentsAsync( compileTimeSolution, documentsToReanalyze, designTimeSolution: _workspace.CurrentSolution, cancellationToken).ConfigureAwait(false); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: designTimeDocumentsToReanalyze); // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); Dispose(); } public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().HasChangesAsync(_sessionId, solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.HasChangesAsync(solutionInfo, callbackId, _sessionId, sourceFilePath, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : true; } public async ValueTask<( ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>)> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, CancellationToken cancellationToken) { ManagedModuleUpdates moduleUpdates; ImmutableArray<DiagnosticData> diagnosticData; ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> rudeEdits; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { var results = await GetLocalService().EmitSolutionUpdateAsync(_sessionId, solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); moduleUpdates = results.ModuleUpdates; diagnosticData = results.GetDiagnosticData(solution); rudeEdits = results.RudeEdits; } else { var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, EmitSolutionUpdateResults.Data>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.EmitSolutionUpdateAsync(solutionInfo, callbackId, _sessionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); if (result.HasValue) { moduleUpdates = result.Value.ModuleUpdates; diagnosticData = result.Value.Diagnostics; rudeEdits = result.Value.RudeEdits; } else { moduleUpdates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); diagnosticData = ImmutableArray<DiagnosticData>.Empty; rudeEdits = ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty; } } // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: rudeEdits.Select(d => d.DocumentId)); // report emit/apply diagnostics: diagnosticUpdateSource.ReportDiagnostics(_workspace, solution, diagnosticData); return (moduleUpdates, diagnosticData, rudeEdits); } public async ValueTask CommitSolutionUpdateAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().CommitSolutionUpdate(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.CommitSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask DiscardSolutionUpdateAsync(CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().DiscardSolutionUpdate(_sessionId); return; } await client.TryInvokeAsync<IRemoteEditAndContinueService>( (service, cancellationToken) => service.DiscardSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetCurrentActiveStatementPositionAsync(_sessionId, solution, activeStatementSpanProvider, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, LinePositionSpan?>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetCurrentActiveStatementPositionAsync(solutionInfo, callbackId, _sessionId, instructionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().IsActiveStatementInExceptionRegionAsync(_sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool?>( solution, (service, solutionInfo, cancellationToken) => service.IsActiveStatementInExceptionRegionAsync(solutionInfo, _sessionId, instructionId, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetBaseActiveStatementSpansAsync(_sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>( solution, (service, solutionInfo, cancellationToken) => service.GetBaseActiveStatementSpansAsync(solutionInfo, _sessionId, documentIds, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ImmutableArray<ActiveStatementSpan>>.Empty; } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetAdjustedActiveStatementSpansAsync(_sessionId, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ActiveStatementSpan>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetAdjustedActiveStatementSpansAsync(solutionInfo, callbackId, _sessionId, document.Id, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ActiveStatementSpan>.Empty; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class RemoteDebuggingSessionProxy : IActiveStatementSpanProvider, IDisposable { private readonly IDisposable? _connection; private readonly DebuggingSessionId _sessionId; private readonly Workspace _workspace; public RemoteDebuggingSessionProxy(Workspace workspace, IDisposable? connection, DebuggingSessionId sessionId) { _connection = connection; _sessionId = sessionId; _workspace = workspace; } public void Dispose() { _connection?.Dispose(); } private IEditAndContinueWorkspaceService GetLocalService() => _workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); public async ValueTask BreakStateChangedAsync(IDiagnosticAnalyzerService diagnosticService, bool inBreakState, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().BreakStateChanged(_sessionId, inBreakState, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.BreakStateChangedAsync(_sessionId, inBreakState, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask EndDebuggingSessionAsync(Solution compileTimeSolution, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().EndDebuggingSession(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.EndDebuggingSessionAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } var designTimeDocumentsToReanalyze = await CompileTimeSolutionProvider.GetDesignTimeDocumentsAsync( compileTimeSolution, documentsToReanalyze, designTimeSolution: _workspace.CurrentSolution, cancellationToken).ConfigureAwait(false); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: designTimeDocumentsToReanalyze); // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); Dispose(); } public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().HasChangesAsync(_sessionId, solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.HasChangesAsync(solutionInfo, callbackId, _sessionId, sourceFilePath, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : true; } public async ValueTask<( ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>)> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, CancellationToken cancellationToken) { ManagedModuleUpdates moduleUpdates; ImmutableArray<DiagnosticData> diagnosticData; ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> rudeEdits; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { var results = await GetLocalService().EmitSolutionUpdateAsync(_sessionId, solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); moduleUpdates = results.ModuleUpdates; diagnosticData = results.GetDiagnosticData(solution); rudeEdits = results.RudeEdits; } else { var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, EmitSolutionUpdateResults.Data>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.EmitSolutionUpdateAsync(solutionInfo, callbackId, _sessionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); if (result.HasValue) { moduleUpdates = result.Value.ModuleUpdates; diagnosticData = result.Value.Diagnostics; rudeEdits = result.Value.RudeEdits; } else { moduleUpdates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); diagnosticData = ImmutableArray<DiagnosticData>.Empty; rudeEdits = ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty; } } // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: rudeEdits.Select(d => d.DocumentId)); // report emit/apply diagnostics: diagnosticUpdateSource.ReportDiagnostics(_workspace, solution, diagnosticData); return (moduleUpdates, diagnosticData, rudeEdits); } public async ValueTask CommitSolutionUpdateAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().CommitSolutionUpdate(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.CommitSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask DiscardSolutionUpdateAsync(CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().DiscardSolutionUpdate(_sessionId); return; } await client.TryInvokeAsync<IRemoteEditAndContinueService>( (service, cancellationToken) => service.DiscardSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetCurrentActiveStatementPositionAsync(_sessionId, solution, activeStatementSpanProvider, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, LinePositionSpan?>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetCurrentActiveStatementPositionAsync(solutionInfo, callbackId, _sessionId, instructionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().IsActiveStatementInExceptionRegionAsync(_sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool?>( solution, (service, solutionInfo, cancellationToken) => service.IsActiveStatementInExceptionRegionAsync(solutionInfo, _sessionId, instructionId, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetBaseActiveStatementSpansAsync(_sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>( solution, (service, solutionInfo, cancellationToken) => service.GetBaseActiveStatementSpansAsync(solutionInfo, _sessionId, documentIds, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ImmutableArray<ActiveStatementSpan>>.Empty; } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetAdjustedActiveStatementSpansAsync(_sessionId, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ActiveStatementSpan>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetAdjustedActiveStatementSpansAsync(solutionInfo, callbackId, _sessionId, document.Id, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ActiveStatementSpan>.Empty; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Tools/ExternalAccess/FSharp/Internal/Editor/FSharpGoToDefinitionService.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.Composition; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Navigation; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor { [Shared] [ExportLanguageService(typeof(IGoToDefinitionService), LanguageNames.FSharp)] internal class FSharpGoToDefinitionService : IGoToDefinitionService { private readonly IFSharpGoToDefinitionService _service; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpGoToDefinitionService(IFSharpGoToDefinitionService service) { _service = service; } public async Task<IEnumerable<INavigableItem>> FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken) { var items = await _service.FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); return items?.Select(x => new InternalFSharpNavigableItem(x)); } public bool TryGoToDefinition(Document document, int position, CancellationToken cancellationToken) { return _service.TryGoToDefinition(document, position, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Composition; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Navigation; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor { [Shared] [ExportLanguageService(typeof(IGoToDefinitionService), LanguageNames.FSharp)] internal class FSharpGoToDefinitionService : IGoToDefinitionService { private readonly IFSharpGoToDefinitionService _service; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpGoToDefinitionService(IFSharpGoToDefinitionService service) { _service = service; } public async Task<IEnumerable<INavigableItem>> FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken) { var items = await _service.FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); return items?.Select(x => new InternalFSharpNavigableItem(x)); } public bool TryGoToDefinition(Document document, int position, CancellationToken cancellationToken) { return _service.TryGoToDefinition(document, position, cancellationToken); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/Core/Portable/DiaSymReader/SymUnmanagedFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Reflection; using System.Runtime.InteropServices; namespace Microsoft.DiaSymReader { internal static class SymUnmanagedFactory { private const string AlternateLoadPathEnvironmentVariableName = "MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH"; private const string LegacyDiaSymReaderModuleName = "diasymreader.dll"; private const string DiaSymReaderModuleName32 = "Microsoft.DiaSymReader.Native.x86.dll"; private const string DiaSymReaderModuleName64 = "Microsoft.DiaSymReader.Native.amd64.dll"; private const string CreateSymReaderFactoryName = "CreateSymReader"; private const string CreateSymWriterFactoryName = "CreateSymWriter"; // CorSymWriter_SxS from corsym.idl private const string SymWriterClsid = "0AE2DEB0-F901-478b-BB9F-881EE8066788"; // CorSymReader_SxS from corsym.idl private const string SymReaderClsid = "0A3976C5-4529-4ef8-B0B0-42EED37082CD"; private static Type s_lazySymReaderComType, s_lazySymWriterComType; internal static string DiaSymReaderModuleName => (IntPtr.Size == 4) ? DiaSymReaderModuleName32 : DiaSymReaderModuleName64; [DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory | DllImportSearchPath.SafeDirectories)] [DllImport(DiaSymReaderModuleName32, EntryPoint = CreateSymReaderFactoryName)] private static extern void CreateSymReader32(ref Guid id, [MarshalAs(UnmanagedType.IUnknown)] out object symReader); [DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory | DllImportSearchPath.SafeDirectories)] [DllImport(DiaSymReaderModuleName64, EntryPoint = CreateSymReaderFactoryName)] private static extern void CreateSymReader64(ref Guid id, [MarshalAs(UnmanagedType.IUnknown)] out object symReader); [DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory | DllImportSearchPath.SafeDirectories)] [DllImport(DiaSymReaderModuleName32, EntryPoint = CreateSymWriterFactoryName)] private static extern void CreateSymWriter32(ref Guid id, [MarshalAs(UnmanagedType.IUnknown)] out object symWriter); [DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory | DllImportSearchPath.SafeDirectories)] [DllImport(DiaSymReaderModuleName64, EntryPoint = CreateSymWriterFactoryName)] private static extern void CreateSymWriter64(ref Guid id, [MarshalAs(UnmanagedType.IUnknown)] out object symWriter); [DllImport("kernel32")] private static extern IntPtr LoadLibrary(string path); [DllImport("kernel32")] private static extern bool FreeLibrary(IntPtr hModule); [DllImport("kernel32")] private static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName); private delegate void NativeFactory(ref Guid id, [MarshalAs(UnmanagedType.IUnknown)] out object instance); #if !NET20 private static readonly Lazy<Func<string, string>> s_lazyGetEnvironmentVariable = new Lazy<Func<string, string>>(() => { try { foreach (var method in typeof(Environment).GetTypeInfo().GetDeclaredMethods("GetEnvironmentVariable")) { var parameters = method.GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType == typeof(string)) { return (Func<string, string>)method.CreateDelegate(typeof(Func<string, string>)); } } } catch { } return null; }); #endif // internal for testing internal static string GetEnvironmentVariable(string name) { try { #if NET20 return Environment.GetEnvironmentVariable(name); #else return s_lazyGetEnvironmentVariable.Value?.Invoke(name); #endif } catch { return null; } } private static object TryLoadFromAlternativePath(Guid clsid, string factoryName) { var dir = GetEnvironmentVariable(AlternateLoadPathEnvironmentVariableName); if (string.IsNullOrEmpty(dir)) { return null; } var moduleHandle = LoadLibrary(Path.Combine(dir, DiaSymReaderModuleName)); if (moduleHandle == IntPtr.Zero) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } object instance = null; try { var createAddress = GetProcAddress(moduleHandle, factoryName); if (createAddress == IntPtr.Zero) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } #if NET20 || NETSTANDARD1_1 var creator = (NativeFactory)Marshal.GetDelegateForFunctionPointer(createAddress, typeof(NativeFactory)); #else var creator = Marshal.GetDelegateForFunctionPointer<NativeFactory>(createAddress); #endif creator(ref clsid, out instance); } finally { if (instance == null && !FreeLibrary(moduleHandle)) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } } return instance; } private static Type GetComTypeType(ref Type lazyType, Guid clsid) { if (lazyType == null) { #if NET20 lazyType = Type.GetTypeFromCLSID(clsid); #else lazyType = Marshal.GetTypeFromCLSID(clsid); #endif } return lazyType; } internal static object CreateObject(bool createReader, bool useAlternativeLoadPath, bool useComRegistry, out string moduleName, out Exception loadException) { object instance = null; loadException = null; moduleName = null; var clsid = new Guid(createReader ? SymReaderClsid : SymWriterClsid); try { try { if (IntPtr.Size == 4) { if (createReader) { CreateSymReader32(ref clsid, out instance); } else { CreateSymWriter32(ref clsid, out instance); } } else { if (createReader) { CreateSymReader64(ref clsid, out instance); } else { CreateSymWriter64(ref clsid, out instance); } } } catch (DllNotFoundException e) when (useAlternativeLoadPath) { instance = TryLoadFromAlternativePath(clsid, createReader ? CreateSymReaderFactoryName : CreateSymWriterFactoryName); if (instance == null) { loadException = e; } } } catch (Exception e) { loadException = e; instance = null; } if (instance != null) { moduleName = DiaSymReaderModuleName; } else if (useComRegistry) { // Try to find a registered CLR implementation try { var comType = createReader ? GetComTypeType(ref s_lazySymReaderComType, clsid) : GetComTypeType(ref s_lazySymWriterComType, clsid); instance = Activator.CreateInstance(comType); moduleName = LegacyDiaSymReaderModuleName; } catch (Exception e) { loadException = e; instance = null; } } return instance; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Reflection; using System.Runtime.InteropServices; namespace Microsoft.DiaSymReader { internal static class SymUnmanagedFactory { private const string AlternateLoadPathEnvironmentVariableName = "MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH"; private const string LegacyDiaSymReaderModuleName = "diasymreader.dll"; private const string DiaSymReaderModuleName32 = "Microsoft.DiaSymReader.Native.x86.dll"; private const string DiaSymReaderModuleName64 = "Microsoft.DiaSymReader.Native.amd64.dll"; private const string CreateSymReaderFactoryName = "CreateSymReader"; private const string CreateSymWriterFactoryName = "CreateSymWriter"; // CorSymWriter_SxS from corsym.idl private const string SymWriterClsid = "0AE2DEB0-F901-478b-BB9F-881EE8066788"; // CorSymReader_SxS from corsym.idl private const string SymReaderClsid = "0A3976C5-4529-4ef8-B0B0-42EED37082CD"; private static Type s_lazySymReaderComType, s_lazySymWriterComType; internal static string DiaSymReaderModuleName => (IntPtr.Size == 4) ? DiaSymReaderModuleName32 : DiaSymReaderModuleName64; [DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory | DllImportSearchPath.SafeDirectories)] [DllImport(DiaSymReaderModuleName32, EntryPoint = CreateSymReaderFactoryName)] private static extern void CreateSymReader32(ref Guid id, [MarshalAs(UnmanagedType.IUnknown)] out object symReader); [DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory | DllImportSearchPath.SafeDirectories)] [DllImport(DiaSymReaderModuleName64, EntryPoint = CreateSymReaderFactoryName)] private static extern void CreateSymReader64(ref Guid id, [MarshalAs(UnmanagedType.IUnknown)] out object symReader); [DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory | DllImportSearchPath.SafeDirectories)] [DllImport(DiaSymReaderModuleName32, EntryPoint = CreateSymWriterFactoryName)] private static extern void CreateSymWriter32(ref Guid id, [MarshalAs(UnmanagedType.IUnknown)] out object symWriter); [DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory | DllImportSearchPath.SafeDirectories)] [DllImport(DiaSymReaderModuleName64, EntryPoint = CreateSymWriterFactoryName)] private static extern void CreateSymWriter64(ref Guid id, [MarshalAs(UnmanagedType.IUnknown)] out object symWriter); [DllImport("kernel32")] private static extern IntPtr LoadLibrary(string path); [DllImport("kernel32")] private static extern bool FreeLibrary(IntPtr hModule); [DllImport("kernel32")] private static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName); private delegate void NativeFactory(ref Guid id, [MarshalAs(UnmanagedType.IUnknown)] out object instance); #if !NET20 private static readonly Lazy<Func<string, string>> s_lazyGetEnvironmentVariable = new Lazy<Func<string, string>>(() => { try { foreach (var method in typeof(Environment).GetTypeInfo().GetDeclaredMethods("GetEnvironmentVariable")) { var parameters = method.GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType == typeof(string)) { return (Func<string, string>)method.CreateDelegate(typeof(Func<string, string>)); } } } catch { } return null; }); #endif // internal for testing internal static string GetEnvironmentVariable(string name) { try { #if NET20 return Environment.GetEnvironmentVariable(name); #else return s_lazyGetEnvironmentVariable.Value?.Invoke(name); #endif } catch { return null; } } private static object TryLoadFromAlternativePath(Guid clsid, string factoryName) { var dir = GetEnvironmentVariable(AlternateLoadPathEnvironmentVariableName); if (string.IsNullOrEmpty(dir)) { return null; } var moduleHandle = LoadLibrary(Path.Combine(dir, DiaSymReaderModuleName)); if (moduleHandle == IntPtr.Zero) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } object instance = null; try { var createAddress = GetProcAddress(moduleHandle, factoryName); if (createAddress == IntPtr.Zero) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } #if NET20 || NETSTANDARD1_1 var creator = (NativeFactory)Marshal.GetDelegateForFunctionPointer(createAddress, typeof(NativeFactory)); #else var creator = Marshal.GetDelegateForFunctionPointer<NativeFactory>(createAddress); #endif creator(ref clsid, out instance); } finally { if (instance == null && !FreeLibrary(moduleHandle)) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } } return instance; } private static Type GetComTypeType(ref Type lazyType, Guid clsid) { if (lazyType == null) { #if NET20 lazyType = Type.GetTypeFromCLSID(clsid); #else lazyType = Marshal.GetTypeFromCLSID(clsid); #endif } return lazyType; } internal static object CreateObject(bool createReader, bool useAlternativeLoadPath, bool useComRegistry, out string moduleName, out Exception loadException) { object instance = null; loadException = null; moduleName = null; var clsid = new Guid(createReader ? SymReaderClsid : SymWriterClsid); try { try { if (IntPtr.Size == 4) { if (createReader) { CreateSymReader32(ref clsid, out instance); } else { CreateSymWriter32(ref clsid, out instance); } } else { if (createReader) { CreateSymReader64(ref clsid, out instance); } else { CreateSymWriter64(ref clsid, out instance); } } } catch (DllNotFoundException e) when (useAlternativeLoadPath) { instance = TryLoadFromAlternativePath(clsid, createReader ? CreateSymReaderFactoryName : CreateSymWriterFactoryName); if (instance == null) { loadException = e; } } } catch (Exception e) { loadException = e; instance = null; } if (instance != null) { moduleName = DiaSymReaderModuleName; } else if (useComRegistry) { // Try to find a registered CLR implementation try { var comType = createReader ? GetComTypeType(ref s_lazySymReaderComType, clsid) : GetComTypeType(ref s_lazySymWriterComType, clsid); instance = Activator.CreateInstance(comType); moduleName = LegacyDiaSymReaderModuleName; } catch (Exception e) { loadException = e; instance = null; } } return instance; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/EditorFeatures/CSharpTest/Organizing/OrganizeTypeDeclarationTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.Commanding.Commands; using Microsoft.CodeAnalysis.Editor.Implementation.Interactive; using Microsoft.CodeAnalysis.Editor.Implementation.Organizing; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Organizing { public class OrganizeTypeDeclarationTests : AbstractOrganizerTests { [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] [InlineData("record class")] [InlineData("record struct")] public async Task TestFieldsWithoutInitializers1(string typeKind) { var initial = $@"{typeKind} C {{ int A; int B; int C; }}"; var final = $@"{typeKind} C {{ int A; int B; int C; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("struct")] [InlineData("record")] [InlineData("record class")] [InlineData("record struct")] public async Task TestNestedTypes(string typeKind) { var initial = $@"class C {{ {typeKind} Nested1 {{ }} {typeKind} Nested2 {{ }} int A; }}"; var final = $@"class C {{ int A; {typeKind} Nested1 {{ }} {typeKind} Nested2 {{ }} }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestFieldsWithoutInitializers2(string typeKind) { var initial = $@"{typeKind} C {{ int C; int B; int A; }}"; var final = $@"{typeKind} C {{ int A; int B; int C; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] [InlineData("record struct")] public async Task TestFieldsWithInitializers1(string typeKind) { var initial = $@"{typeKind} C {{ int C = 0; int B; int A; }}"; var final = $@"{typeKind} C {{ int A; int B; int C = 0; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestFieldsWithInitializers2(string typeKind) { var initial = $@"{typeKind} C {{ int C = 0; int B = 0; int A; }}"; var final = $@"{typeKind} C {{ int A; int C = 0; int B = 0; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestEventFieldDeclaration(string typeKind) { var initial = $@"{typeKind} C {{ public void Goo() {{}} public event EventHandler MyEvent; }}"; var final = $@"{typeKind} C {{ public event EventHandler MyEvent; public void Goo() {{}} }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestEventDeclaration(string typeKind) { var initial = $@"{typeKind} C {{ public void Goo() {{}} public event EventHandler Event {{ remove {{ }} add {{ }} }} public static int Property {{ get; set; }} }}"; var final = $@"{typeKind} C {{ public static int Property {{ get; set; }} public event EventHandler Event {{ remove {{ }} add {{ }} }} public void Goo() {{}} }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestOperator(string typeKind) { var initial = $@"{typeKind} C {{ public void Goo() {{}} public static int operator +(Goo<T> a, int b) {{ return 1; }} }}"; var final = $@"{typeKind} C {{ public static int operator +(Goo<T> a, int b) {{ return 1; }} public void Goo() {{}} }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestIndexer(string typeKind) { var initial = $@"{typeKind} C {{ public void Goo() {{}} public T this[int i] {{ get {{ return default(T); }} }} C() {{}} }}"; var final = $@"{typeKind} C {{ C() {{}} public T this[int i] {{ get {{ return default(T); }} }} public void Goo() {{}} }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestConstructorAndDestructors(string typeKind) { var initial = $@"{typeKind} C {{ public ~Goo() {{}} enum Days {{Sat, Sun}}; public Goo() {{}} }}"; var final = $@"{typeKind} C {{ public Goo() {{}} public ~Goo() {{}} enum Days {{Sat, Sun}}; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestInterface(string typeKind) { var initial = $@"{typeKind} C {{}} interface I {{ void Goo(); int Property {{ get; set; }} event EventHandler Event; }}"; var final = $@"{typeKind} C {{}} interface I {{ event EventHandler Event; int Property {{ get; set; }} void Goo(); }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestStaticInstance(string typeKind) { var initial = $@"{typeKind} C {{ int A; static int B; int C; static int D; }}"; var final = $@"{typeKind} C {{ static int B; static int D; int A; int C; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] [InlineData("record struct")] public async Task TestAccessibility(string typeKind) { var initial = $@"{typeKind} C {{ int A; private int B; internal int C; protected int D; public int E; protected internal int F; }}"; var final = $@"{typeKind} C {{ public int E; protected int D; protected internal int F; internal int C; int A; private int B; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestStaticAccessibility(string typeKind) { var initial = $@"{typeKind} C {{ int A1; private int B1; internal int C1; protected int D1; public int E1; static int A2; static private int B2; static internal int C2; static protected int D2; static public int E2; }}"; var final = $@"{typeKind} C {{ public static int E2; protected static int D2; internal static int C2; static int A2; private static int B2; public int E1; protected int D1; internal int C1; int A1; private int B1; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestGenerics(string typeKind) { var initial = $@"{typeKind} C {{ void B<X,Y>(); void B<Z>(); void B(); void A<X,Y>(); void A<Z>(); void A(); }}"; var final = $@"{typeKind} C {{ void A(); void A<Z>(); void A<X,Y>(); void B(); void B<Z>(); void B<X,Y>(); }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestInsidePPRegion(string typeKind) { var initial = $@"{typeKind} C {{ #if true int c; int b; int a; #endif }}"; var final = $@"{typeKind} C {{ #if true int a; int b; int c; #endif }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestInsidePPRegion2(string typeKind) { var initial = $@"{typeKind} C {{ #if true int z; int y; int x; #endif #if true int c; int b; int a; #endif }}"; var final = $@"{typeKind} C {{ #if true int x; int y; int z; #endif #if true int a; int b; int c; #endif }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestInsidePPRegion3(string typeKind) { var initial = $@"{typeKind} C {{ int z; int y; #if true int x; int c; #endif int b; int a; }}"; var final = $@"{typeKind} C {{ int y; int z; #if true int c; int x; #endif int a; int b; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestInsidePPRegion4(string typeKind) { var initial = $@"{typeKind} C {{ int c() {{ }} int b {{ }} int a {{ #if true #endif }} }}"; var final = $@"{typeKind} C {{ int a {{ #if true #endif }} int b {{ }} int c() {{ }} }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestInsidePPRegion5(string typeKind) { var initial = $@"{typeKind} C {{ int c() {{ }} int b {{ }} int a {{ #if true #else #endif }} }}"; var final = $@"{typeKind} C {{ int a {{ #if true #else #endif }} int b {{ }} int c() {{ }} }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestInsidePPRegion6(string typeKind) { var initial = $@"{typeKind} C {{ #region int e() {{ }} int d() {{ }} int c() {{ #region }} #endregion int b {{ }} int a {{ }} #endregion }}"; var final = $@"{typeKind} C {{ #region int d() {{ }} int e() {{ }} int c() {{ #region }} #endregion int a {{ }} int b {{ }} #endregion }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestPinned(string typeKind) { var initial = $@"{typeKind} C {{ int z() {{ }} int y() {{ }} int x() {{ #if true }} int n; int m; int c() {{ #endif }} int b() {{ }} int a() {{ }} }}"; var final = $@"{typeKind} C {{ int y() {{ }} int z() {{ }} int x() {{ #if true }} int m; int n; int c() {{ #endif }} int a() {{ }} int b() {{ }} }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestSensitivity(string typeKind) { var initial = $@"{typeKind} C {{ int Bb; int B; int bB; int b; int Aa; int a; int A; int aa; int aA; int AA; int bb; int BB; int bBb; int bbB; int あ; int ア; int ア; int ああ; int あア; int あア; int アあ; int cC; int Cc; int アア; int アア; int アあ; int アア; int アア; int BBb; int BbB; int bBB; int BBB; int c; int C; int bbb; int Bbb; int cc; int cC; int CC; }}"; var final = $@"{typeKind} C {{ int a; int A; int aa; int aA; int Aa; int AA; int b; int B; int bb; int bB; int Bb; int BB; int bbb; int bbB; int bBb; int bBB; int Bbb; int BbB; int BBb; int BBB; int c; int C; int cc; int cC; int cC; int Cc; int CC; int ア; int ア; int あ; int アア; int アア; int アア; int アア; int アあ; int アあ; int あア; int あア; int ああ; }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestWhitespaceBetweenMethods1(string typeKind) { var initial = $@"{typeKind} Program {{ void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestWhitespaceBetweenMethods2(string typeKind) { var initial = $@"{typeKind} Program {{ void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestWhitespaceBetweenMethods3(string typeKind) { var initial = $@"{typeKind} Program {{ void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestWhitespaceBetweenMethods4(string typeKind) { var initial = $@"{typeKind} Program {{ void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestWhitespaceBetweenMethods5(string typeKind) { var initial = $@"{typeKind} Program {{ void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestWhitespaceBetweenMethods6(string typeKind) { var initial = $@"{typeKind} Program {{ void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestMoveComments1(string typeKind) { var initial = $@"{typeKind} Program {{ // B void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} // B void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestMoveComments2(string typeKind) { var initial = $@"{typeKind} Program {{ // B void B() {{ }} // A void A() {{ }} }}"; var final = $@"{typeKind} Program {{ // A void A() {{ }} // B void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestMoveDocComments1(string typeKind) { var initial = $@"{typeKind} Program {{ /// B void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} /// B void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestMoveDocComments2(string typeKind) { var initial = $@"{typeKind} Program {{ /// B void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} /// B void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestDontMoveBanner(string typeKind) { var initial = $@"{typeKind} Program {{ // Banner void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ // Banner void A() {{ }} void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestDontMoveBanner2(string typeKind) { var initial = $@"{typeKind} Program {{ // Banner // More banner // Bannery stuff void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ // Banner // More banner // Bannery stuff void A() {{ }} void B() {{ }} }}"; await CheckAsync(initial, final); } [WpfFact] [Trait(Traits.Feature, Traits.Features.Organizing)] [Trait(Traits.Feature, Traits.Features.Interactive)] public void OrganizingCommandsDisabledInSubmission() { using var workspace = TestWorkspace.Create(XElement.Parse(@" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> class C { object $$goo; } </Submission> </Workspace> "), workspaceKind: WorkspaceKind.Interactive, composition: EditorTestCompositions.EditorFeaturesWpf); // Force initialization. workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList(); var textView = workspace.Documents.Single().GetTextView(); var handler = new OrganizeDocumentCommandHandler(workspace.ExportProvider.GetExportedValue<IThreadingContext>()); var state = handler.GetCommandState(new SortAndRemoveUnnecessaryImportsCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); state = handler.GetCommandState(new OrganizeDocumentCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.Commanding.Commands; using Microsoft.CodeAnalysis.Editor.Implementation.Interactive; using Microsoft.CodeAnalysis.Editor.Implementation.Organizing; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Organizing { public class OrganizeTypeDeclarationTests : AbstractOrganizerTests { [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] [InlineData("record class")] [InlineData("record struct")] public async Task TestFieldsWithoutInitializers1(string typeKind) { var initial = $@"{typeKind} C {{ int A; int B; int C; }}"; var final = $@"{typeKind} C {{ int A; int B; int C; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("struct")] [InlineData("record")] [InlineData("record class")] [InlineData("record struct")] public async Task TestNestedTypes(string typeKind) { var initial = $@"class C {{ {typeKind} Nested1 {{ }} {typeKind} Nested2 {{ }} int A; }}"; var final = $@"class C {{ int A; {typeKind} Nested1 {{ }} {typeKind} Nested2 {{ }} }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestFieldsWithoutInitializers2(string typeKind) { var initial = $@"{typeKind} C {{ int C; int B; int A; }}"; var final = $@"{typeKind} C {{ int A; int B; int C; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] [InlineData("record struct")] public async Task TestFieldsWithInitializers1(string typeKind) { var initial = $@"{typeKind} C {{ int C = 0; int B; int A; }}"; var final = $@"{typeKind} C {{ int A; int B; int C = 0; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestFieldsWithInitializers2(string typeKind) { var initial = $@"{typeKind} C {{ int C = 0; int B = 0; int A; }}"; var final = $@"{typeKind} C {{ int A; int C = 0; int B = 0; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestEventFieldDeclaration(string typeKind) { var initial = $@"{typeKind} C {{ public void Goo() {{}} public event EventHandler MyEvent; }}"; var final = $@"{typeKind} C {{ public event EventHandler MyEvent; public void Goo() {{}} }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestEventDeclaration(string typeKind) { var initial = $@"{typeKind} C {{ public void Goo() {{}} public event EventHandler Event {{ remove {{ }} add {{ }} }} public static int Property {{ get; set; }} }}"; var final = $@"{typeKind} C {{ public static int Property {{ get; set; }} public event EventHandler Event {{ remove {{ }} add {{ }} }} public void Goo() {{}} }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestOperator(string typeKind) { var initial = $@"{typeKind} C {{ public void Goo() {{}} public static int operator +(Goo<T> a, int b) {{ return 1; }} }}"; var final = $@"{typeKind} C {{ public static int operator +(Goo<T> a, int b) {{ return 1; }} public void Goo() {{}} }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestIndexer(string typeKind) { var initial = $@"{typeKind} C {{ public void Goo() {{}} public T this[int i] {{ get {{ return default(T); }} }} C() {{}} }}"; var final = $@"{typeKind} C {{ C() {{}} public T this[int i] {{ get {{ return default(T); }} }} public void Goo() {{}} }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestConstructorAndDestructors(string typeKind) { var initial = $@"{typeKind} C {{ public ~Goo() {{}} enum Days {{Sat, Sun}}; public Goo() {{}} }}"; var final = $@"{typeKind} C {{ public Goo() {{}} public ~Goo() {{}} enum Days {{Sat, Sun}}; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestInterface(string typeKind) { var initial = $@"{typeKind} C {{}} interface I {{ void Goo(); int Property {{ get; set; }} event EventHandler Event; }}"; var final = $@"{typeKind} C {{}} interface I {{ event EventHandler Event; int Property {{ get; set; }} void Goo(); }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestStaticInstance(string typeKind) { var initial = $@"{typeKind} C {{ int A; static int B; int C; static int D; }}"; var final = $@"{typeKind} C {{ static int B; static int D; int A; int C; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] [InlineData("record struct")] public async Task TestAccessibility(string typeKind) { var initial = $@"{typeKind} C {{ int A; private int B; internal int C; protected int D; public int E; protected internal int F; }}"; var final = $@"{typeKind} C {{ public int E; protected int D; protected internal int F; internal int C; int A; private int B; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestStaticAccessibility(string typeKind) { var initial = $@"{typeKind} C {{ int A1; private int B1; internal int C1; protected int D1; public int E1; static int A2; static private int B2; static internal int C2; static protected int D2; static public int E2; }}"; var final = $@"{typeKind} C {{ public static int E2; protected static int D2; internal static int C2; static int A2; private static int B2; public int E1; protected int D1; internal int C1; int A1; private int B1; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestGenerics(string typeKind) { var initial = $@"{typeKind} C {{ void B<X,Y>(); void B<Z>(); void B(); void A<X,Y>(); void A<Z>(); void A(); }}"; var final = $@"{typeKind} C {{ void A(); void A<Z>(); void A<X,Y>(); void B(); void B<Z>(); void B<X,Y>(); }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestInsidePPRegion(string typeKind) { var initial = $@"{typeKind} C {{ #if true int c; int b; int a; #endif }}"; var final = $@"{typeKind} C {{ #if true int a; int b; int c; #endif }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestInsidePPRegion2(string typeKind) { var initial = $@"{typeKind} C {{ #if true int z; int y; int x; #endif #if true int c; int b; int a; #endif }}"; var final = $@"{typeKind} C {{ #if true int x; int y; int z; #endif #if true int a; int b; int c; #endif }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestInsidePPRegion3(string typeKind) { var initial = $@"{typeKind} C {{ int z; int y; #if true int x; int c; #endif int b; int a; }}"; var final = $@"{typeKind} C {{ int y; int z; #if true int c; int x; #endif int a; int b; }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestInsidePPRegion4(string typeKind) { var initial = $@"{typeKind} C {{ int c() {{ }} int b {{ }} int a {{ #if true #endif }} }}"; var final = $@"{typeKind} C {{ int a {{ #if true #endif }} int b {{ }} int c() {{ }} }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestInsidePPRegion5(string typeKind) { var initial = $@"{typeKind} C {{ int c() {{ }} int b {{ }} int a {{ #if true #else #endif }} }}"; var final = $@"{typeKind} C {{ int a {{ #if true #else #endif }} int b {{ }} int c() {{ }} }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestInsidePPRegion6(string typeKind) { var initial = $@"{typeKind} C {{ #region int e() {{ }} int d() {{ }} int c() {{ #region }} #endregion int b {{ }} int a {{ }} #endregion }}"; var final = $@"{typeKind} C {{ #region int d() {{ }} int e() {{ }} int c() {{ #region }} #endregion int a {{ }} int b {{ }} #endregion }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestPinned(string typeKind) { var initial = $@"{typeKind} C {{ int z() {{ }} int y() {{ }} int x() {{ #if true }} int n; int m; int c() {{ #endif }} int b() {{ }} int a() {{ }} }}"; var final = $@"{typeKind} C {{ int y() {{ }} int z() {{ }} int x() {{ #if true }} int m; int n; int c() {{ #endif }} int a() {{ }} int b() {{ }} }}"; await CheckAsync(initial, final); } [Theory, Trait(Traits.Feature, Traits.Features.Organizing)] [InlineData("class")] [InlineData("record")] public async Task TestSensitivity(string typeKind) { var initial = $@"{typeKind} C {{ int Bb; int B; int bB; int b; int Aa; int a; int A; int aa; int aA; int AA; int bb; int BB; int bBb; int bbB; int あ; int ア; int ア; int ああ; int あア; int あア; int アあ; int cC; int Cc; int アア; int アア; int アあ; int アア; int アア; int BBb; int BbB; int bBB; int BBB; int c; int C; int bbb; int Bbb; int cc; int cC; int CC; }}"; var final = $@"{typeKind} C {{ int a; int A; int aa; int aA; int Aa; int AA; int b; int B; int bb; int bB; int Bb; int BB; int bbb; int bbB; int bBb; int bBB; int Bbb; int BbB; int BBb; int BBB; int c; int C; int cc; int cC; int cC; int Cc; int CC; int ア; int ア; int あ; int アア; int アア; int アア; int アア; int アあ; int アあ; int あア; int あア; int ああ; }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestWhitespaceBetweenMethods1(string typeKind) { var initial = $@"{typeKind} Program {{ void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestWhitespaceBetweenMethods2(string typeKind) { var initial = $@"{typeKind} Program {{ void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestWhitespaceBetweenMethods3(string typeKind) { var initial = $@"{typeKind} Program {{ void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestWhitespaceBetweenMethods4(string typeKind) { var initial = $@"{typeKind} Program {{ void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestWhitespaceBetweenMethods5(string typeKind) { var initial = $@"{typeKind} Program {{ void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestWhitespaceBetweenMethods6(string typeKind) { var initial = $@"{typeKind} Program {{ void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestMoveComments1(string typeKind) { var initial = $@"{typeKind} Program {{ // B void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} // B void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestMoveComments2(string typeKind) { var initial = $@"{typeKind} Program {{ // B void B() {{ }} // A void A() {{ }} }}"; var final = $@"{typeKind} Program {{ // A void A() {{ }} // B void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestMoveDocComments1(string typeKind) { var initial = $@"{typeKind} Program {{ /// B void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} /// B void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestMoveDocComments2(string typeKind) { var initial = $@"{typeKind} Program {{ /// B void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ void A() {{ }} /// B void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestDontMoveBanner(string typeKind) { var initial = $@"{typeKind} Program {{ // Banner void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ // Banner void A() {{ }} void B() {{ }} }}"; await CheckAsync(initial, final); } [WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")] [Theory] [InlineData("class")] [InlineData("record")] public async Task TestDontMoveBanner2(string typeKind) { var initial = $@"{typeKind} Program {{ // Banner // More banner // Bannery stuff void B() {{ }} void A() {{ }} }}"; var final = $@"{typeKind} Program {{ // Banner // More banner // Bannery stuff void A() {{ }} void B() {{ }} }}"; await CheckAsync(initial, final); } [WpfFact] [Trait(Traits.Feature, Traits.Features.Organizing)] [Trait(Traits.Feature, Traits.Features.Interactive)] public void OrganizingCommandsDisabledInSubmission() { using var workspace = TestWorkspace.Create(XElement.Parse(@" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> class C { object $$goo; } </Submission> </Workspace> "), workspaceKind: WorkspaceKind.Interactive, composition: EditorTestCompositions.EditorFeaturesWpf); // Force initialization. workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList(); var textView = workspace.Documents.Single().GetTextView(); var handler = new OrganizeDocumentCommandHandler(workspace.ExportProvider.GetExportedValue<IThreadingContext>()); var state = handler.GetCommandState(new SortAndRemoveUnnecessaryImportsCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); state = handler.GetCommandState(new OrganizeDocumentCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Dependencies/CodeAnalysis.Debugging/TupleElementNamesInfo.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; namespace Microsoft.CodeAnalysis.Debugging { internal struct TupleElementNamesInfo { internal readonly ImmutableArray<string> ElementNames; internal readonly int SlotIndex; // Locals only internal readonly string LocalName; internal readonly int ScopeStart; // Constants only internal readonly int ScopeEnd; // Constants only internal TupleElementNamesInfo(ImmutableArray<string> elementNames, int slotIndex, string localName, int scopeStart, int scopeEnd) { Debug.Assert(!elementNames.IsDefault); ElementNames = elementNames; SlotIndex = slotIndex; LocalName = localName; ScopeStart = scopeStart; ScopeEnd = scopeEnd; } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.Debugging { internal struct TupleElementNamesInfo { internal readonly ImmutableArray<string> ElementNames; internal readonly int SlotIndex; // Locals only internal readonly string LocalName; internal readonly int ScopeStart; // Constants only internal readonly int ScopeEnd; // Constants only internal TupleElementNamesInfo(ImmutableArray<string> elementNames, int slotIndex, string localName, int scopeStart, int scopeEnd) { Debug.Assert(!elementNames.IsDefault); ElementNames = elementNames; SlotIndex = slotIndex; LocalName = localName; ScopeStart = scopeStart; ScopeEnd = scopeEnd; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Features/Core/Portable/QuickInfo/ExportQuickInfoProviderAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; namespace Microsoft.CodeAnalysis.QuickInfo { /// <summary> /// Use this attribute to export a <see cref="QuickInfoProvider"/> so that it will /// be found and used by the per language associated <see cref="QuickInfoService"/>. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] internal sealed class ExportQuickInfoProviderAttribute : ExportAttribute { public string Name { get; } public string Language { get; } public ExportQuickInfoProviderAttribute(string name, string language) : base(typeof(QuickInfoProvider)) { Name = name ?? throw new ArgumentNullException(nameof(name)); Language = language ?? throw new ArgumentNullException(nameof(language)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; namespace Microsoft.CodeAnalysis.QuickInfo { /// <summary> /// Use this attribute to export a <see cref="QuickInfoProvider"/> so that it will /// be found and used by the per language associated <see cref="QuickInfoService"/>. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] internal sealed class ExportQuickInfoProviderAttribute : ExportAttribute { public string Name { get; } public string Language { get; } public ExportQuickInfoProviderAttribute(string name, string language) : base(typeof(QuickInfoProvider)) { Name = name ?? throw new ArgumentNullException(nameof(name)); Language = language ?? throw new ArgumentNullException(nameof(language)); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Features/Core/Portable/ClassifiedSpansAndHighlightSpan.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Classification { internal readonly struct ClassifiedSpansAndHighlightSpan { public const string Key = nameof(ClassifiedSpansAndHighlightSpan); public readonly ImmutableArray<ClassifiedSpan> ClassifiedSpans; public readonly TextSpan HighlightSpan; public ClassifiedSpansAndHighlightSpan( ImmutableArray<ClassifiedSpan> classifiedSpans, TextSpan highlightSpan) { ClassifiedSpans = classifiedSpans; HighlightSpan = highlightSpan; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Classification { internal readonly struct ClassifiedSpansAndHighlightSpan { public const string Key = nameof(ClassifiedSpansAndHighlightSpan); public readonly ImmutableArray<ClassifiedSpan> ClassifiedSpans; public readonly TextSpan HighlightSpan; public ClassifiedSpansAndHighlightSpan( ImmutableArray<ClassifiedSpan> classifiedSpans, TextSpan highlightSpan) { ClassifiedSpans = classifiedSpans; HighlightSpan = highlightSpan; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.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="../CSharpVSResources.resx"> <body> <trans-unit id="Add_missing_using_directives_on_paste"> <source>Add missing using directives on paste</source> <target state="translated">Ajouter les directives using manquantes au moment du collage</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Allow_bank_line_after_colon_in_constructor_initializer"> <source>Allow blank line after colon in constructor initializer</source> <target state="translated">Autoriser une ligne vide après le signe des deux-points dans l'initialiseur du constructeur</target> <note /> </trans-unit> <trans-unit id="Allow_blank_lines_between_consecutive_braces"> <source>Allow blank lines between consecutive braces</source> <target state="translated">Autoriser les lignes vides entre les accolades consécutives</target> <note /> </trans-unit> <trans-unit id="Allow_embedded_statements_on_same_line"> <source>Allow embedded statements on same line</source> <target state="translated">Autoriser les instructions imbriquées sur la même ligne</target> <note /> </trans-unit> <trans-unit id="Apply_all_csharp_formatting_rules_indentation_wrapping_spacing"> <source>Apply all C# formatting rules (indentation, wrapping, spacing)</source> <target state="translated">Appliquer toutes les règles de mise en forme de C# (indentation, enveloppement, espacement)</target> <note /> </trans-unit> <trans-unit id="Automatically_complete_statement_on_semicolon"> <source>Automatically complete statement on semicolon</source> <target state="translated">Effectuer la complétion automatique de l'instruction après l'entrée d'un point-virgule</target> <note /> </trans-unit> <trans-unit id="Automatically_show_completion_list_in_argument_lists"> <source>Automatically show completion list in argument lists</source> <target state="translated">Afficher automatiquement la liste de complétion dans les listes d'arguments</target> <note /> </trans-unit> <trans-unit id="Block_scoped"> <source>Block scoped</source> <target state="new">Block scoped</target> <note /> </trans-unit> <trans-unit id="CSharp"> <source>C#</source> <target state="translated">C#</target> <note /> </trans-unit> <trans-unit id="CSharp_Coding_Conventions"> <source>C# Coding Conventions</source> <target state="translated">Conventions de codage C#</target> <note /> </trans-unit> <trans-unit id="CSharp_Formatting_Rules"> <source>C# Formatting Rules</source> <target state="translated">Règles de formatage C#</target> <note /> </trans-unit> <trans-unit id="Completion"> <source>Completion</source> <target state="translated">Complétion</target> <note /> </trans-unit> <trans-unit id="Discard"> <source>Discard</source> <target state="translated">Discard</target> <note /> </trans-unit> <trans-unit id="Edit_color_scheme"> <source>Edit color scheme</source> <target state="translated">Modifier le modèle de couleurs</target> <note /> </trans-unit> <trans-unit id="File_scoped"> <source>File scoped</source> <target state="new">File scoped</target> <note /> </trans-unit> <trans-unit id="Format_document_settings"> <source>Format Document Settings (Experiment) </source> <target state="translated">Paramètres de mise en forme du document (essai)</target> <note /> </trans-unit> <trans-unit id="General"> <source>General</source> <target state="translated">Général</target> <note>Title of the control group on the General Formatting options page</note> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators: &lt; &gt; &lt;= &gt;= is as == !=</source> <target state="translated">Dans les opérateurs relationnels : &lt; &gt; &lt;= &gt;= is as == !=</target> <note>'is' and 'as' are C# keywords and should not be localized</note> </trans-unit> <trans-unit id="Insert_slash_slash_at_the_start_of_new_lines_when_writing_slash_slash_comments"> <source>Insert // at the start of new lines when writing // comments</source> <target state="translated">Insérer // au début des nouvelles lignes pour l'écriture de commentaires //</target> <note /> </trans-unit> <trans-unit id="Inside_namespace"> <source>Inside namespace</source> <target state="translated">Dans le namespace</target> <note>'namespace' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Outside_namespace"> <source>Outside namespace</source> <target state="translated">Hors du namespace</target> <note>'namespace' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Pattern_matching_preferences_colon"> <source>Pattern matching preferences:</source> <target state="translated">Préférences relatives aux critères spéciaux :</target> <note /> </trans-unit> <trans-unit id="Perform_additional_code_cleanup_during_formatting"> <source>Perform additional code cleanup during formatting</source> <target state="translated">Effectuer un nettoyage supplémentaire du code pendant la mise en forme</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers"> <source>Place open brace on new line for object, collection, array, and with initializers</source> <target state="translated">Placer une accolade ouvrante sur une nouvelle ligne pour les initialiseurs d'objets, de collections, de tableaux et with</target> <note>{Locked="with"}</note> </trans-unit> <trans-unit id="Prefer_implicit_object_creation_when_type_is_apparent"> <source>Prefer implicit object creation when type is apparent</source> <target state="translated">Préférer la création d'objets implicites quand le type est apparent</target> <note /> </trans-unit> <trans-unit id="Prefer_is_null_for_reference_equality_checks"> <source>Prefer 'is null' for reference equality checks</source> <target state="translated">Préférer 'is nul' pour les vérifications d'égalité de référence</target> <note>'is null' is a C# string and should not be localized.</note> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching"> <source>Prefer pattern matching</source> <target state="translated">Préférer les critères spéciaux</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_mixed_type_check"> <source>Prefer pattern matching over mixed type check</source> <target state="translated">Préférer les critères spéciaux à la vérification de type mixte</target> <note /> </trans-unit> <trans-unit id="Prefer_switch_expression"> <source>Prefer switch expression</source> <target state="translated">Préférer l'expression switch</target> <note /> </trans-unit> <trans-unit id="Preferred_using_directive_placement"> <source>Preferred 'using' directive placement</source> <target state="translated">Emplacement par défaut de la directive 'using'</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Remove_unnecessary_usings"> <source>Remove unnecessary usings</source> <target state="translated">Supprimer les Usings inutiles</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_new_expressions"> <source>Show hints for 'new' expressions</source> <target state="translated">Afficher les indicateurs pour les expressions 'new'</target> <note /> </trans-unit> <trans-unit id="Show_items_from_unimported_namespaces"> <source>Show items from unimported namespaces</source> <target state="translated">Afficher les éléments des espaces de noms qui ne sont pas importés</target> <note /> </trans-unit> <trans-unit id="Show_remarks_in_Quick_Info"> <source>Show remarks in Quick Info</source> <target state="translated">Afficher les notes dans Info express</target> <note /> </trans-unit> <trans-unit id="Sort_usings"> <source>Sort usings</source> <target state="translated">Trier les instructions using</target> <note /> </trans-unit> <trans-unit id="Suggest_usings_for_types_in_dotnet_framework_assemblies"> <source>Suggest usings for types in .NET Framework assemblies</source> <target state="translated">Suggérer des using pour les types dans les assemblys .NET Framework</target> <note /> </trans-unit> <trans-unit id="Surround_With"> <source>Surround With</source> <target state="translated">Entourer de</target> <note /> </trans-unit> <trans-unit id="Insert_Snippet"> <source>Insert Snippet</source> <target state="translated">Insérer un extrait</target> <note /> </trans-unit> <trans-unit id="Automatically_format_block_on_close_brace"> <source>Automatically format _block on }</source> <target state="translated">Mise en forme automatique du _bloc lors de la saisie d'une }</target> <note /> </trans-unit> <trans-unit id="Automatically_format_on_paste"> <source>Automatically format on _paste</source> <target state="translated">Mise en forme automati_que lors du collage</target> <note /> </trans-unit> <trans-unit id="Automatically_format_statement_on_semicolon"> <source>Automatically format _statement on ;</source> <target state="translated">Mise en forme automatique de l'in_struction lors de la saisie d'un ;</target> <note /> </trans-unit> <trans-unit id="Place_members_in_anonymous_types_on_new_line"> <source>Place members in anonymous types on new line</source> <target state="translated">Placer les membres dans les types anonymes sur une nouvelle ligne</target> <note /> </trans-unit> <trans-unit id="Leave_block_on_single_line"> <source>Leave block on single line</source> <target state="translated">Laisser un bloc sur une seule ligne</target> <note /> </trans-unit> <trans-unit id="Place_catch_on_new_line"> <source>Place "catch" on new line</source> <target state="translated">Placer "catch" sur une nouvelle ligne</target> <note /> </trans-unit> <trans-unit id="Place_else_on_new_line"> <source>Place "else" on new line</source> <target state="translated">Placer "else" sur une nouvelle ligne</target> <note /> </trans-unit> <trans-unit id="Indent_block_contents"> <source>Indent block contents</source> <target state="translated">Mettre en retrait le contenu d'un bloc</target> <note /> </trans-unit> <trans-unit id="Indent_open_and_close_braces"> <source>Indent open and close braces</source> <target state="translated">Mettre en retrait les accolades ouvrantes et fermantes</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents"> <source>Indent case contents</source> <target state="translated">Mettre en retrait le contenu de case</target> <note /> </trans-unit> <trans-unit id="Indent_case_labels"> <source>Indent case labels</source> <target state="translated">Mettre en retrait des étiquettes case</target> <note /> </trans-unit> <trans-unit id="Place_finally_on_new_line"> <source>Place "finally" on new line</source> <target state="translated">Placer "finally" sur une nouvelle ligne</target> <note /> </trans-unit> <trans-unit id="Place_goto_labels_in_leftmost_column"> <source>Place goto labels in leftmost column</source> <target state="translated">Placer des étiquettes goto dans la colonne située le plus à gauche</target> <note /> </trans-unit> <trans-unit id="Indent_labels_normally"> <source>Indent labels normally</source> <target state="translated">Mettre en retrait normalement les étiquettes</target> <note /> </trans-unit> <trans-unit id="Place_goto_labels_one_indent_less_than_current"> <source>Place goto labels one indent less than current</source> <target state="translated">Placer les étiquettes goto d'un niveau inférieur au niveau actuel</target> <note /> </trans-unit> <trans-unit id="Label_Indentation"> <source>Label Indentation</source> <target state="translated">Mise en retrait d'étiquette</target> <note /> </trans-unit> <trans-unit id="Place_members_in_object_initializers_on_new_line"> <source>Place members in object initializers on new line</source> <target state="translated">Placer les membres dans les initialiseurs d'objets sur une nouvelle ligne</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_methods"> <source>Place open brace on new line for anonymous methods</source> <target state="translated">Placer une accolade ouvrante sur une nouvelle ligne pour les méthodes anonymes</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_types"> <source>Place open brace on new line for anonymous types</source> <target state="translated">Placer une accolade ouvrante sur une nouvelle ligne pour des types anonymes</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_control_blocks"> <source>Place open brace on new line for control blocks</source> <target state="translated">Placer l'accolade ouvrante sur une nouvelle ligne pour les blocs de contrôle</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_lambda_expression"> <source>Place open brace on new line for lambda expression</source> <target state="translated">Placer une accolade ouvrante sur une nouvelle ligne pour une expression lambda</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_methods_local_functions"> <source>Place open brace on new line for methods and local functions</source> <target state="translated">Placer une accolade ouvrante sur une nouvelle ligne pour les méthodes et les fonctions locales</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_types"> <source>Place open brace on new line for types</source> <target state="translated">Placer une accolade ouvrante sur une nouvelle ligne pour les types</target> <note /> </trans-unit> <trans-unit id="Place_query_expression_clauses_on_new_line"> <source>Place query expression clauses on new line</source> <target state="translated">Placer les clauses d'expression de requête sur une nouvelle ligne</target> <note /> </trans-unit> <trans-unit id="Leave_statements_and_member_declarations_on_the_same_line"> <source>Leave statements and member declarations on the same line</source> <target state="translated">Laisser les instructions et les déclarations de membre sur la même ligne</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_and_after_binary_operators"> <source>Insert space before and after binary operators</source> <target state="translated">Insérer un espace avant et après les opérateurs binaires</target> <note /> </trans-unit> <trans-unit id="Ignore_spaces_around_binary_operators"> <source>Ignore spaces around binary operators</source> <target state="translated">Ignorer les espaces autour des opérateurs binaires</target> <note /> </trans-unit> <trans-unit id="Remove_spaces_before_and_after_binary_operators"> <source>Remove spaces before and after binary operators</source> <target state="translated">Supprimer les espaces avant et après les opérateurs binaires</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_colon_for_base_or_interface_in_type_declaration"> <source>Insert space after colon for base or interface in type declaration</source> <target state="translated">Insérer un espace après le signe deux-points pour base ou interface dans une déclaration de type</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_comma"> <source>Insert space after comma</source> <target state="translated">Insérer un espace après la virgule</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_dot"> <source>Insert space after dot</source> <target state="translated">Insérer un espace après le point</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_semicolon_in_for_statement"> <source>Insert space after semicolon in "for" statement</source> <target state="translated">Insérer un espace après le point-virgule dans une instruction "for"</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_colon_for_base_or_interface_in_type_declaration"> <source>Insert space before colon for base or interface in type declaration</source> <target state="translated">Insérer un espace avant le signe deux-points pour base ou interface dans une déclaration de type</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_comma"> <source>Insert space before comma</source> <target state="translated">Insérer un espace avant la virgule</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_dot"> <source>Insert space before dot</source> <target state="translated">Insérer un espace avant le point</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_semicolon_in_for_statement"> <source>Insert space before semicolon in "for" statement</source> <target state="translated">Insérer un espace avant le point-virgule dans une instruction "for"</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_argument_list_parentheses"> <source>Insert space within argument list parentheses</source> <target state="translated">Insérer un espace dans les parenthèses de la liste d'arguments</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_argument_list_parentheses"> <source>Insert space within empty argument list parentheses</source> <target state="translated">Insérer un espace dans les parenthèses de la liste d'arguments vide</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis1"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">Insérer un espace entre le nom de la méthode et sa parenthèse ouvrante</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_parameter_list_parentheses"> <source>Insert space within empty parameter list parentheses</source> <target state="translated">Insérer un espace dans les parenthèses vides de la liste de paramètres</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis2"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">Insérer un espace entre le nom de la méthode et sa parenthèse ouvrante</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parameter_list_parentheses"> <source>Insert space within parameter list parentheses</source> <target state="translated">Insérer un espace dans les parenthèses de la liste de paramètres</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_keywords_in_control_flow_statements"> <source>Insert space after keywords in control flow statements</source> <target state="translated">Insérer un espace après les mots clés dans les instructions de flux de contrôle</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_expressions"> <source>Insert space within parentheses of expressions</source> <target state="translated">Insérer un espace dans les parenthèses d'expressions</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_cast"> <source>Insert space after cast</source> <target state="translated">Insérer un espace après le cast</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_parentheses_of_control_flow_statements"> <source>Insert spaces within parentheses of control flow statements</source> <target state="translated">Insérer des espaces à l'intérieur des parenthèses des instructions de flux de contrôle</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_type_casts"> <source>Insert space within parentheses of type casts</source> <target state="translated">Insérer un espace dans les parenthèses de casts de type</target> <note /> </trans-unit> <trans-unit id="Ignore_spaces_in_declaration_statements"> <source>Ignore spaces in declaration statements</source> <target state="translated">Ignorer les espaces dans les instructions de déclaration</target> <note /> </trans-unit> <trans-unit id="Set_other_spacing_options"> <source>Set other spacing options</source> <target state="translated">Définir d'autres options d'espacement</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_brackets"> <source>Set spacing for brackets</source> <target state="translated">Définir l'espacement des crochets</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_delimiters"> <source>Set spacing for delimiters</source> <target state="translated">Définir l'espacement des délimiteurs</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_method_calls"> <source>Set spacing for method calls</source> <target state="translated">Définir l'espacement des appels de méthode</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_method_declarations"> <source>Set spacing for method declarations</source> <target state="translated">Définir l'espacement des déclarations de méthode</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_operators"> <source>Set spacing for operators</source> <target state="translated">Définir l'espacement des opérateurs</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_square_brackets"> <source>Insert spaces within square brackets</source> <target state="translated">Insérer des espaces dans des crochets</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_open_square_bracket"> <source>Insert space before open square bracket</source> <target state="translated">Insérer un espace avant un crochet ouvrant</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_square_brackets"> <source>Insert space within empty square brackets</source> <target state="translated">Insérer un espace dans des crochets vides</target> <note /> </trans-unit> <trans-unit id="New_line_options_for_braces"> <source>New line options for braces</source> <target state="translated">Nouvelles options de ligne pour les accolades</target> <note /> </trans-unit> <trans-unit id="New_line_options_for_expressions"> <source>New line options for expressions</source> <target state="translated">Nouvelles options de lignes pour expressions</target> <note /> </trans-unit> <trans-unit id="New_line_options_for_keywords"> <source>New line options for keywords</source> <target state="translated">Nouvelles options de ligne pour les mots clés</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">Local inutilisé</target> <note /> </trans-unit> <trans-unit id="Use_var_when_generating_locals"> <source>Use 'var' when generating locals</source> <target state="translated">Utiliser 'var' lors de la génération de variables locales</target> <note /> </trans-unit> <trans-unit id="Show_procedure_line_separators"> <source>_Show procedure line separators</source> <target state="translated">_Afficher les séparateurs de ligne de procédure</target> <note /> </trans-unit> <trans-unit id="Don_t_put_ref_or_out_on_custom_struct"> <source>_Don't put ref or out on custom struct</source> <target state="translated">_Ne pas ajouter ref ou out dans un struct personnalisé</target> <note /> </trans-unit> <trans-unit id="Editor_Help"> <source>Editor Help</source> <target state="translated">Aide de l'éditeur</target> <note /> </trans-unit> <trans-unit id="Highlight_related_keywords_under_cursor"> <source>Highlight related _keywords under cursor</source> <target state="translated">Surligner les mots clés liés sous le _curseur</target> <note /> </trans-unit> <trans-unit id="Highlight_references_to_symbol_under_cursor"> <source>_Highlight references to symbol under cursor</source> <target state="translated">_Surligner les références jusqu'au symbole sous le curseur</target> <note /> </trans-unit> <trans-unit id="Enter_outlining_mode_when_files_open"> <source>Enter _outlining mode when files open</source> <target state="translated">Passer en m_ode Plan à l'ouverture des fichiers</target> <note /> </trans-unit> <trans-unit id="Extract_Method"> <source>Extract Method</source> <target state="translated">Extraire la méthode</target> <note /> </trans-unit> <trans-unit id="Generate_XML_documentation_comments_for"> <source>_Generate XML documentation comments for ///</source> <target state="translated">_Générer des commentaires de documentation XML pour ///</target> <note /> </trans-unit> <trans-unit id="Highlighting"> <source>Highlighting</source> <target state="translated">Mise en surbrillance</target> <note /> </trans-unit> <trans-unit id="Insert_at_the_start_of_new_lines_when_writing_comments"> <source>_Insert * at the start of new lines when writing /* */ comments</source> <target state="translated">_Insérer * au début des nouvelles lignes pour l'écriture de commentaires /* */</target> <note /> </trans-unit> <trans-unit id="Optimize_for_solution_size"> <source>Optimize for solution size</source> <target state="translated">Optimiser pour la taille de la solution</target> <note /> </trans-unit> <trans-unit id="Large"> <source>Large</source> <target state="translated">Grande</target> <note /> </trans-unit> <trans-unit id="Regular"> <source>Regular</source> <target state="translated">Normal</target> <note /> </trans-unit> <trans-unit id="Small"> <source>Small</source> <target state="translated">Petite</target> <note /> </trans-unit> <trans-unit id="Using_Directives"> <source>Using Directives</source> <target state="translated">Directives Using</target> <note /> </trans-unit> <trans-unit id="Performance"> <source>Performance</source> <target state="translated">Performances</target> <note /> </trans-unit> <trans-unit id="Place_System_directives_first_when_sorting_usings"> <source>_Place 'System' directives first when sorting usings</source> <target state="translated">_Placer les directives 'System' en premier lors du tri des usings</target> <note /> </trans-unit> <trans-unit id="Show_completion_list_after_a_character_is_typed"> <source>_Show completion list after a character is typed</source> <target state="translated">_Afficher la liste de saisie semi-automatique après la saisie d'un caractère</target> <note /> </trans-unit> <trans-unit id="Place_keywords_in_completion_lists"> <source>Place _keywords in completion lists</source> <target state="translated">Placer les mots _clés dans les listes de saisie semi-automatique</target> <note /> </trans-unit> <trans-unit id="Place_code_snippets_in_completion_lists"> <source>Place _code snippets in completion lists</source> <target state="translated">Placer les extraits de _code dans les listes de saisie semi-automatique</target> <note /> </trans-unit> <trans-unit id="Selection_In_Completion_List"> <source>Selection In Completion List</source> <target state="translated">Sélection dans la liste de saisie semi-automatique</target> <note /> </trans-unit> <trans-unit id="Show_preview_for_rename_tracking"> <source>Show preview for rename _tracking</source> <target state="translated">Affiche_r un aperçu pour le suivi des renommages</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_property_indexer_and_event_accessors"> <source>Place open brace on new line for property, indexer, and event accessors</source> <target state="translated">Placer une accolade ouvrante sur une nouvelle ligne pour les accesseurs de propriété, d'indexeur et d'événement</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_properties_indexers_and_events"> <source>Place open brace on new line for properties, indexers, and events</source> <target state="translated">Placer une accolade ouvrante sur une nouvelle ligne pour les propriétés, indexeurs et événements</target> <note /> </trans-unit> <trans-unit id="Suggest_usings_for_types_in_NuGet_packages"> <source>Suggest usings for types in _NuGet packages</source> <target state="translated">Suggérer des usings pour les types dans les packages _NuGet</target> <note /> </trans-unit> <trans-unit id="Type_Inference_preferences_colon"> <source>Type Inference preferences:</source> <target state="translated">Préférences d'inférence de type :</target> <note /> </trans-unit> <trans-unit id="For_built_in_types"> <source>For built-in types</source> <target state="translated">Pour les types intégrés</target> <note /> </trans-unit> <trans-unit id="Elsewhere"> <source>Elsewhere</source> <target state="translated">Ailleurs</target> <note /> </trans-unit> <trans-unit id="When_on_multiple_lines"> <source>When on multiple lines</source> <target state="translated">Si plusieurs lignes</target> <note /> </trans-unit> <trans-unit id="When_variable_type_is_apparent"> <source>When variable type is apparent</source> <target state="translated">Quand le type de variable est apparent</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_this"> <source>Qualify event access with 'this'</source> <target state="translated">Qualifier l'accès à l'événement avec 'this'</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_this"> <source>Qualify field access with 'this'</source> <target state="translated">Qualifier l'accès au champ avec 'this'</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_this"> <source>Qualify method access with 'this'</source> <target state="translated">Qualifier l'accès à la méthode avec 'this'</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_this"> <source>Qualify property access with 'this'</source> <target state="translated">Qualifier l'accès à la propriété avec 'this'</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_type"> <source>Prefer explicit type</source> <target state="translated">Préférer un type explicite</target> <note /> </trans-unit> <trans-unit id="Prefer_this"> <source>Prefer 'this.'</source> <target state="translated">Préférer 'this.'</target> <note /> </trans-unit> <trans-unit id="Prefer_var"> <source>Prefer 'var'</source> <target state="translated">Préférer 'var'</target> <note /> </trans-unit> <trans-unit id="this_preferences_colon"> <source>'this.' preferences:</source> <target state="translated">'Préférences 'this.' :</target> <note /> </trans-unit> <trans-unit id="using_preferences_colon"> <source>'using' preferences:</source> <target state="translated">Préférences pour 'using' :</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="var_preferences_colon"> <source>'var' preferences:</source> <target state="translated">'Préférences 'var' :</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_this"> <source>Do not prefer 'this.'</source> <target state="translated">Ne pas préférer 'this.'</target> <note /> </trans-unit> <trans-unit id="predefined_type_preferences_colon"> <source>predefined type preferences:</source> <target state="translated">Préférences de types prédéfinies :</target> <note /> </trans-unit> <trans-unit id="Split_string_literals_on_enter"> <source>Split string literals on _enter</source> <target state="translated">Fractionner les littéraux de chaîne avec _Entrée</target> <note /> </trans-unit> <trans-unit id="Highlight_matching_portions_of_completion_list_items"> <source>_Highlight matching portions of completion list items</source> <target state="translated">_Mettre en surbrillance les parties correspondantes des éléments de liste de saisie semi-automatique</target> <note /> </trans-unit> <trans-unit id="Show_completion_item_filters"> <source>Show completion item _filters</source> <target state="translated">Afficher les _filtres d'éléments de saisie semi-automatique</target> <note /> </trans-unit> <trans-unit id="Enter_key_behavior_colon"> <source>Enter key behavior:</source> <target state="translated">Comportement de la touche Entrée :</target> <note /> </trans-unit> <trans-unit id="Only_add_new_line_on_enter_after_end_of_fully_typed_word"> <source>_Only add new line on enter after end of fully typed word</source> <target state="translated">Aj_outer uniquement une nouvelle ligne après Entrée à la fin d'un mot complet tapé</target> <note /> </trans-unit> <trans-unit id="Always_add_new_line_on_enter"> <source>_Always add new line on enter</source> <target state="translated">Toujours _ajouter une nouvelle ligne après Entrée</target> <note /> </trans-unit> <trans-unit id="Never_add_new_line_on_enter"> <source>_Never add new line on enter</source> <target state="translated">_Ne jamais ajouter de nouvelle ligne après Entrée</target> <note /> </trans-unit> <trans-unit id="Always_include_snippets"> <source>Always include snippets</source> <target state="translated">Toujours inclure les extraits de code</target> <note /> </trans-unit> <trans-unit id="Include_snippets_when_Tab_is_typed_after_an_identifier"> <source>Include snippets when ?-Tab is typed after an identifier</source> <target state="translated">Inclure les extraits de code quand ?-Tab est typé après un identificateur</target> <note /> </trans-unit> <trans-unit id="Never_include_snippets"> <source>Never include snippets</source> <target state="translated">Ne jamais inclure d'extrait de code</target> <note /> </trans-unit> <trans-unit id="Snippets_behavior"> <source>Snippets behavior</source> <target state="translated">Comportement des extraits de code</target> <note /> </trans-unit> <trans-unit id="Show_completion_list_after_a_character_is_deleted"> <source>Show completion list after a character is _deleted</source> <target state="translated">Afficher la liste de saisie semi-automatique après la suppression d'un _caractère</target> <note /> </trans-unit> <trans-unit id="null_checking_colon"> <source>'null' checking:</source> <target state="translated">'vérification de valeur 'null' :</target> <note /> </trans-unit> <trans-unit id="Prefer_throw_expression"> <source>Prefer throw-expression</source> <target state="translated">Préférer l'expression throw</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_delegate_call"> <source>Prefer conditional delegate call</source> <target state="translated">Préférer l'appel de délégué conditionnel</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_is_with_cast_check"> <source>Prefer pattern matching over 'is' with 'cast' check</source> <target state="translated">Préférer les critères spéciaux à 'is' avec le contrôle de 'cast'</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_as_with_null_check"> <source>Prefer pattern matching over 'as' with 'null' check</source> <target state="translated">Préférer les critères spéciaux à 'as' avec le contrôle de 'null'</target> <note /> </trans-unit> <trans-unit id="Prefer_block_body"> <source>Prefer block body</source> <target state="translated">Préférer un corps de bloc</target> <note /> </trans-unit> <trans-unit id="Prefer_expression_body"> <source>Prefer expression body</source> <target state="translated">Préférer un corps d'expression</target> <note /> </trans-unit> <trans-unit id="Automatically_format_on_return"> <source>Automatically format on return</source> <target state="translated">Mise en forme automatique au retour</target> <note /> </trans-unit> <trans-unit id="Automatically_format_when_typing"> <source>Automatically format when typing</source> <target state="translated">Mise en forme automatique en cours de frappe</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">Jamais</target> <note /> </trans-unit> <trans-unit id="When_on_single_line"> <source>When on single line</source> <target state="translated">Sur une seule ligne</target> <note /> </trans-unit> <trans-unit id="When_possible"> <source>When possible</source> <target state="translated">Quand cela est possible</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents_when_block"> <source>Indent case contents (when block)</source> <target state="translated">Mettre en retrait le contenu de case (dans un bloc)</target> <note /> </trans-unit> <trans-unit id="Fade_out_unused_usings"> <source>Fade out unused usings</source> <target state="translated">Supprimer les instructions using inutilisées</target> <note /> </trans-unit> <trans-unit id="Report_invalid_placeholders_in_string_dot_format_calls"> <source>Report invalid placeholders in 'string.Format' calls</source> <target state="translated">Signaler les espaces réservés non valides dans les appels de 'String.Format'</target> <note /> </trans-unit> <trans-unit id="Separate_using_directive_groups"> <source>Separate using directive groups</source> <target state="translated">Séparer les groupes de directives using</target> <note /> </trans-unit> <trans-unit id="Show_name_suggestions"> <source>Show name s_uggestions</source> <target state="translated">Afficher les s_uggestions de nom</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators: * / % + - &lt;&lt; &gt;&gt; &amp; ^ |</source> <target state="translated">Dans les opérateurs arithmétiques : * / % + - &lt;&lt; &gt;&gt; &amp; ^ |</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators: &amp;&amp; || ?? and or</source> <target state="translated">Dans d'autres opérateurs binaires : &amp;&amp; || ?? and or</target> <note>'and' and 'or' are C# keywords and should not be localized</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="../CSharpVSResources.resx"> <body> <trans-unit id="Add_missing_using_directives_on_paste"> <source>Add missing using directives on paste</source> <target state="translated">Ajouter les directives using manquantes au moment du collage</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Allow_bank_line_after_colon_in_constructor_initializer"> <source>Allow blank line after colon in constructor initializer</source> <target state="translated">Autoriser une ligne vide après le signe des deux-points dans l'initialiseur du constructeur</target> <note /> </trans-unit> <trans-unit id="Allow_blank_lines_between_consecutive_braces"> <source>Allow blank lines between consecutive braces</source> <target state="translated">Autoriser les lignes vides entre les accolades consécutives</target> <note /> </trans-unit> <trans-unit id="Allow_embedded_statements_on_same_line"> <source>Allow embedded statements on same line</source> <target state="translated">Autoriser les instructions imbriquées sur la même ligne</target> <note /> </trans-unit> <trans-unit id="Apply_all_csharp_formatting_rules_indentation_wrapping_spacing"> <source>Apply all C# formatting rules (indentation, wrapping, spacing)</source> <target state="translated">Appliquer toutes les règles de mise en forme de C# (indentation, enveloppement, espacement)</target> <note /> </trans-unit> <trans-unit id="Automatically_complete_statement_on_semicolon"> <source>Automatically complete statement on semicolon</source> <target state="translated">Effectuer la complétion automatique de l'instruction après l'entrée d'un point-virgule</target> <note /> </trans-unit> <trans-unit id="Automatically_show_completion_list_in_argument_lists"> <source>Automatically show completion list in argument lists</source> <target state="translated">Afficher automatiquement la liste de complétion dans les listes d'arguments</target> <note /> </trans-unit> <trans-unit id="Block_scoped"> <source>Block scoped</source> <target state="new">Block scoped</target> <note /> </trans-unit> <trans-unit id="CSharp"> <source>C#</source> <target state="translated">C#</target> <note /> </trans-unit> <trans-unit id="CSharp_Coding_Conventions"> <source>C# Coding Conventions</source> <target state="translated">Conventions de codage C#</target> <note /> </trans-unit> <trans-unit id="CSharp_Formatting_Rules"> <source>C# Formatting Rules</source> <target state="translated">Règles de formatage C#</target> <note /> </trans-unit> <trans-unit id="Completion"> <source>Completion</source> <target state="translated">Complétion</target> <note /> </trans-unit> <trans-unit id="Discard"> <source>Discard</source> <target state="translated">Discard</target> <note /> </trans-unit> <trans-unit id="Edit_color_scheme"> <source>Edit color scheme</source> <target state="translated">Modifier le modèle de couleurs</target> <note /> </trans-unit> <trans-unit id="File_scoped"> <source>File scoped</source> <target state="new">File scoped</target> <note /> </trans-unit> <trans-unit id="Format_document_settings"> <source>Format Document Settings (Experiment) </source> <target state="translated">Paramètres de mise en forme du document (essai)</target> <note /> </trans-unit> <trans-unit id="General"> <source>General</source> <target state="translated">Général</target> <note>Title of the control group on the General Formatting options page</note> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators: &lt; &gt; &lt;= &gt;= is as == !=</source> <target state="translated">Dans les opérateurs relationnels : &lt; &gt; &lt;= &gt;= is as == !=</target> <note>'is' and 'as' are C# keywords and should not be localized</note> </trans-unit> <trans-unit id="Insert_slash_slash_at_the_start_of_new_lines_when_writing_slash_slash_comments"> <source>Insert // at the start of new lines when writing // comments</source> <target state="translated">Insérer // au début des nouvelles lignes pour l'écriture de commentaires //</target> <note /> </trans-unit> <trans-unit id="Inside_namespace"> <source>Inside namespace</source> <target state="translated">Dans le namespace</target> <note>'namespace' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Outside_namespace"> <source>Outside namespace</source> <target state="translated">Hors du namespace</target> <note>'namespace' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Pattern_matching_preferences_colon"> <source>Pattern matching preferences:</source> <target state="translated">Préférences relatives aux critères spéciaux :</target> <note /> </trans-unit> <trans-unit id="Perform_additional_code_cleanup_during_formatting"> <source>Perform additional code cleanup during formatting</source> <target state="translated">Effectuer un nettoyage supplémentaire du code pendant la mise en forme</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers"> <source>Place open brace on new line for object, collection, array, and with initializers</source> <target state="translated">Placer une accolade ouvrante sur une nouvelle ligne pour les initialiseurs d'objets, de collections, de tableaux et with</target> <note>{Locked="with"}</note> </trans-unit> <trans-unit id="Prefer_implicit_object_creation_when_type_is_apparent"> <source>Prefer implicit object creation when type is apparent</source> <target state="translated">Préférer la création d'objets implicites quand le type est apparent</target> <note /> </trans-unit> <trans-unit id="Prefer_is_null_for_reference_equality_checks"> <source>Prefer 'is null' for reference equality checks</source> <target state="translated">Préférer 'is nul' pour les vérifications d'égalité de référence</target> <note>'is null' is a C# string and should not be localized.</note> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching"> <source>Prefer pattern matching</source> <target state="translated">Préférer les critères spéciaux</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_mixed_type_check"> <source>Prefer pattern matching over mixed type check</source> <target state="translated">Préférer les critères spéciaux à la vérification de type mixte</target> <note /> </trans-unit> <trans-unit id="Prefer_switch_expression"> <source>Prefer switch expression</source> <target state="translated">Préférer l'expression switch</target> <note /> </trans-unit> <trans-unit id="Preferred_using_directive_placement"> <source>Preferred 'using' directive placement</source> <target state="translated">Emplacement par défaut de la directive 'using'</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Remove_unnecessary_usings"> <source>Remove unnecessary usings</source> <target state="translated">Supprimer les Usings inutiles</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_new_expressions"> <source>Show hints for 'new' expressions</source> <target state="translated">Afficher les indicateurs pour les expressions 'new'</target> <note /> </trans-unit> <trans-unit id="Show_items_from_unimported_namespaces"> <source>Show items from unimported namespaces</source> <target state="translated">Afficher les éléments des espaces de noms qui ne sont pas importés</target> <note /> </trans-unit> <trans-unit id="Show_remarks_in_Quick_Info"> <source>Show remarks in Quick Info</source> <target state="translated">Afficher les notes dans Info express</target> <note /> </trans-unit> <trans-unit id="Sort_usings"> <source>Sort usings</source> <target state="translated">Trier les instructions using</target> <note /> </trans-unit> <trans-unit id="Suggest_usings_for_types_in_dotnet_framework_assemblies"> <source>Suggest usings for types in .NET Framework assemblies</source> <target state="translated">Suggérer des using pour les types dans les assemblys .NET Framework</target> <note /> </trans-unit> <trans-unit id="Surround_With"> <source>Surround With</source> <target state="translated">Entourer de</target> <note /> </trans-unit> <trans-unit id="Insert_Snippet"> <source>Insert Snippet</source> <target state="translated">Insérer un extrait</target> <note /> </trans-unit> <trans-unit id="Automatically_format_block_on_close_brace"> <source>Automatically format _block on }</source> <target state="translated">Mise en forme automatique du _bloc lors de la saisie d'une }</target> <note /> </trans-unit> <trans-unit id="Automatically_format_on_paste"> <source>Automatically format on _paste</source> <target state="translated">Mise en forme automati_que lors du collage</target> <note /> </trans-unit> <trans-unit id="Automatically_format_statement_on_semicolon"> <source>Automatically format _statement on ;</source> <target state="translated">Mise en forme automatique de l'in_struction lors de la saisie d'un ;</target> <note /> </trans-unit> <trans-unit id="Place_members_in_anonymous_types_on_new_line"> <source>Place members in anonymous types on new line</source> <target state="translated">Placer les membres dans les types anonymes sur une nouvelle ligne</target> <note /> </trans-unit> <trans-unit id="Leave_block_on_single_line"> <source>Leave block on single line</source> <target state="translated">Laisser un bloc sur une seule ligne</target> <note /> </trans-unit> <trans-unit id="Place_catch_on_new_line"> <source>Place "catch" on new line</source> <target state="translated">Placer "catch" sur une nouvelle ligne</target> <note /> </trans-unit> <trans-unit id="Place_else_on_new_line"> <source>Place "else" on new line</source> <target state="translated">Placer "else" sur une nouvelle ligne</target> <note /> </trans-unit> <trans-unit id="Indent_block_contents"> <source>Indent block contents</source> <target state="translated">Mettre en retrait le contenu d'un bloc</target> <note /> </trans-unit> <trans-unit id="Indent_open_and_close_braces"> <source>Indent open and close braces</source> <target state="translated">Mettre en retrait les accolades ouvrantes et fermantes</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents"> <source>Indent case contents</source> <target state="translated">Mettre en retrait le contenu de case</target> <note /> </trans-unit> <trans-unit id="Indent_case_labels"> <source>Indent case labels</source> <target state="translated">Mettre en retrait des étiquettes case</target> <note /> </trans-unit> <trans-unit id="Place_finally_on_new_line"> <source>Place "finally" on new line</source> <target state="translated">Placer "finally" sur une nouvelle ligne</target> <note /> </trans-unit> <trans-unit id="Place_goto_labels_in_leftmost_column"> <source>Place goto labels in leftmost column</source> <target state="translated">Placer des étiquettes goto dans la colonne située le plus à gauche</target> <note /> </trans-unit> <trans-unit id="Indent_labels_normally"> <source>Indent labels normally</source> <target state="translated">Mettre en retrait normalement les étiquettes</target> <note /> </trans-unit> <trans-unit id="Place_goto_labels_one_indent_less_than_current"> <source>Place goto labels one indent less than current</source> <target state="translated">Placer les étiquettes goto d'un niveau inférieur au niveau actuel</target> <note /> </trans-unit> <trans-unit id="Label_Indentation"> <source>Label Indentation</source> <target state="translated">Mise en retrait d'étiquette</target> <note /> </trans-unit> <trans-unit id="Place_members_in_object_initializers_on_new_line"> <source>Place members in object initializers on new line</source> <target state="translated">Placer les membres dans les initialiseurs d'objets sur une nouvelle ligne</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_methods"> <source>Place open brace on new line for anonymous methods</source> <target state="translated">Placer une accolade ouvrante sur une nouvelle ligne pour les méthodes anonymes</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_types"> <source>Place open brace on new line for anonymous types</source> <target state="translated">Placer une accolade ouvrante sur une nouvelle ligne pour des types anonymes</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_control_blocks"> <source>Place open brace on new line for control blocks</source> <target state="translated">Placer l'accolade ouvrante sur une nouvelle ligne pour les blocs de contrôle</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_lambda_expression"> <source>Place open brace on new line for lambda expression</source> <target state="translated">Placer une accolade ouvrante sur une nouvelle ligne pour une expression lambda</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_methods_local_functions"> <source>Place open brace on new line for methods and local functions</source> <target state="translated">Placer une accolade ouvrante sur une nouvelle ligne pour les méthodes et les fonctions locales</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_types"> <source>Place open brace on new line for types</source> <target state="translated">Placer une accolade ouvrante sur une nouvelle ligne pour les types</target> <note /> </trans-unit> <trans-unit id="Place_query_expression_clauses_on_new_line"> <source>Place query expression clauses on new line</source> <target state="translated">Placer les clauses d'expression de requête sur une nouvelle ligne</target> <note /> </trans-unit> <trans-unit id="Leave_statements_and_member_declarations_on_the_same_line"> <source>Leave statements and member declarations on the same line</source> <target state="translated">Laisser les instructions et les déclarations de membre sur la même ligne</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_and_after_binary_operators"> <source>Insert space before and after binary operators</source> <target state="translated">Insérer un espace avant et après les opérateurs binaires</target> <note /> </trans-unit> <trans-unit id="Ignore_spaces_around_binary_operators"> <source>Ignore spaces around binary operators</source> <target state="translated">Ignorer les espaces autour des opérateurs binaires</target> <note /> </trans-unit> <trans-unit id="Remove_spaces_before_and_after_binary_operators"> <source>Remove spaces before and after binary operators</source> <target state="translated">Supprimer les espaces avant et après les opérateurs binaires</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_colon_for_base_or_interface_in_type_declaration"> <source>Insert space after colon for base or interface in type declaration</source> <target state="translated">Insérer un espace après le signe deux-points pour base ou interface dans une déclaration de type</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_comma"> <source>Insert space after comma</source> <target state="translated">Insérer un espace après la virgule</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_dot"> <source>Insert space after dot</source> <target state="translated">Insérer un espace après le point</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_semicolon_in_for_statement"> <source>Insert space after semicolon in "for" statement</source> <target state="translated">Insérer un espace après le point-virgule dans une instruction "for"</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_colon_for_base_or_interface_in_type_declaration"> <source>Insert space before colon for base or interface in type declaration</source> <target state="translated">Insérer un espace avant le signe deux-points pour base ou interface dans une déclaration de type</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_comma"> <source>Insert space before comma</source> <target state="translated">Insérer un espace avant la virgule</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_dot"> <source>Insert space before dot</source> <target state="translated">Insérer un espace avant le point</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_semicolon_in_for_statement"> <source>Insert space before semicolon in "for" statement</source> <target state="translated">Insérer un espace avant le point-virgule dans une instruction "for"</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_argument_list_parentheses"> <source>Insert space within argument list parentheses</source> <target state="translated">Insérer un espace dans les parenthèses de la liste d'arguments</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_argument_list_parentheses"> <source>Insert space within empty argument list parentheses</source> <target state="translated">Insérer un espace dans les parenthèses de la liste d'arguments vide</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis1"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">Insérer un espace entre le nom de la méthode et sa parenthèse ouvrante</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_parameter_list_parentheses"> <source>Insert space within empty parameter list parentheses</source> <target state="translated">Insérer un espace dans les parenthèses vides de la liste de paramètres</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis2"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">Insérer un espace entre le nom de la méthode et sa parenthèse ouvrante</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parameter_list_parentheses"> <source>Insert space within parameter list parentheses</source> <target state="translated">Insérer un espace dans les parenthèses de la liste de paramètres</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_keywords_in_control_flow_statements"> <source>Insert space after keywords in control flow statements</source> <target state="translated">Insérer un espace après les mots clés dans les instructions de flux de contrôle</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_expressions"> <source>Insert space within parentheses of expressions</source> <target state="translated">Insérer un espace dans les parenthèses d'expressions</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_cast"> <source>Insert space after cast</source> <target state="translated">Insérer un espace après le cast</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_parentheses_of_control_flow_statements"> <source>Insert spaces within parentheses of control flow statements</source> <target state="translated">Insérer des espaces à l'intérieur des parenthèses des instructions de flux de contrôle</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_type_casts"> <source>Insert space within parentheses of type casts</source> <target state="translated">Insérer un espace dans les parenthèses de casts de type</target> <note /> </trans-unit> <trans-unit id="Ignore_spaces_in_declaration_statements"> <source>Ignore spaces in declaration statements</source> <target state="translated">Ignorer les espaces dans les instructions de déclaration</target> <note /> </trans-unit> <trans-unit id="Set_other_spacing_options"> <source>Set other spacing options</source> <target state="translated">Définir d'autres options d'espacement</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_brackets"> <source>Set spacing for brackets</source> <target state="translated">Définir l'espacement des crochets</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_delimiters"> <source>Set spacing for delimiters</source> <target state="translated">Définir l'espacement des délimiteurs</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_method_calls"> <source>Set spacing for method calls</source> <target state="translated">Définir l'espacement des appels de méthode</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_method_declarations"> <source>Set spacing for method declarations</source> <target state="translated">Définir l'espacement des déclarations de méthode</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_operators"> <source>Set spacing for operators</source> <target state="translated">Définir l'espacement des opérateurs</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_square_brackets"> <source>Insert spaces within square brackets</source> <target state="translated">Insérer des espaces dans des crochets</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_open_square_bracket"> <source>Insert space before open square bracket</source> <target state="translated">Insérer un espace avant un crochet ouvrant</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_square_brackets"> <source>Insert space within empty square brackets</source> <target state="translated">Insérer un espace dans des crochets vides</target> <note /> </trans-unit> <trans-unit id="New_line_options_for_braces"> <source>New line options for braces</source> <target state="translated">Nouvelles options de ligne pour les accolades</target> <note /> </trans-unit> <trans-unit id="New_line_options_for_expressions"> <source>New line options for expressions</source> <target state="translated">Nouvelles options de lignes pour expressions</target> <note /> </trans-unit> <trans-unit id="New_line_options_for_keywords"> <source>New line options for keywords</source> <target state="translated">Nouvelles options de ligne pour les mots clés</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">Local inutilisé</target> <note /> </trans-unit> <trans-unit id="Use_var_when_generating_locals"> <source>Use 'var' when generating locals</source> <target state="translated">Utiliser 'var' lors de la génération de variables locales</target> <note /> </trans-unit> <trans-unit id="Show_procedure_line_separators"> <source>_Show procedure line separators</source> <target state="translated">_Afficher les séparateurs de ligne de procédure</target> <note /> </trans-unit> <trans-unit id="Don_t_put_ref_or_out_on_custom_struct"> <source>_Don't put ref or out on custom struct</source> <target state="translated">_Ne pas ajouter ref ou out dans un struct personnalisé</target> <note /> </trans-unit> <trans-unit id="Editor_Help"> <source>Editor Help</source> <target state="translated">Aide de l'éditeur</target> <note /> </trans-unit> <trans-unit id="Highlight_related_keywords_under_cursor"> <source>Highlight related _keywords under cursor</source> <target state="translated">Surligner les mots clés liés sous le _curseur</target> <note /> </trans-unit> <trans-unit id="Highlight_references_to_symbol_under_cursor"> <source>_Highlight references to symbol under cursor</source> <target state="translated">_Surligner les références jusqu'au symbole sous le curseur</target> <note /> </trans-unit> <trans-unit id="Enter_outlining_mode_when_files_open"> <source>Enter _outlining mode when files open</source> <target state="translated">Passer en m_ode Plan à l'ouverture des fichiers</target> <note /> </trans-unit> <trans-unit id="Extract_Method"> <source>Extract Method</source> <target state="translated">Extraire la méthode</target> <note /> </trans-unit> <trans-unit id="Generate_XML_documentation_comments_for"> <source>_Generate XML documentation comments for ///</source> <target state="translated">_Générer des commentaires de documentation XML pour ///</target> <note /> </trans-unit> <trans-unit id="Highlighting"> <source>Highlighting</source> <target state="translated">Mise en surbrillance</target> <note /> </trans-unit> <trans-unit id="Insert_at_the_start_of_new_lines_when_writing_comments"> <source>_Insert * at the start of new lines when writing /* */ comments</source> <target state="translated">_Insérer * au début des nouvelles lignes pour l'écriture de commentaires /* */</target> <note /> </trans-unit> <trans-unit id="Optimize_for_solution_size"> <source>Optimize for solution size</source> <target state="translated">Optimiser pour la taille de la solution</target> <note /> </trans-unit> <trans-unit id="Large"> <source>Large</source> <target state="translated">Grande</target> <note /> </trans-unit> <trans-unit id="Regular"> <source>Regular</source> <target state="translated">Normal</target> <note /> </trans-unit> <trans-unit id="Small"> <source>Small</source> <target state="translated">Petite</target> <note /> </trans-unit> <trans-unit id="Using_Directives"> <source>Using Directives</source> <target state="translated">Directives Using</target> <note /> </trans-unit> <trans-unit id="Performance"> <source>Performance</source> <target state="translated">Performances</target> <note /> </trans-unit> <trans-unit id="Place_System_directives_first_when_sorting_usings"> <source>_Place 'System' directives first when sorting usings</source> <target state="translated">_Placer les directives 'System' en premier lors du tri des usings</target> <note /> </trans-unit> <trans-unit id="Show_completion_list_after_a_character_is_typed"> <source>_Show completion list after a character is typed</source> <target state="translated">_Afficher la liste de saisie semi-automatique après la saisie d'un caractère</target> <note /> </trans-unit> <trans-unit id="Place_keywords_in_completion_lists"> <source>Place _keywords in completion lists</source> <target state="translated">Placer les mots _clés dans les listes de saisie semi-automatique</target> <note /> </trans-unit> <trans-unit id="Place_code_snippets_in_completion_lists"> <source>Place _code snippets in completion lists</source> <target state="translated">Placer les extraits de _code dans les listes de saisie semi-automatique</target> <note /> </trans-unit> <trans-unit id="Selection_In_Completion_List"> <source>Selection In Completion List</source> <target state="translated">Sélection dans la liste de saisie semi-automatique</target> <note /> </trans-unit> <trans-unit id="Show_preview_for_rename_tracking"> <source>Show preview for rename _tracking</source> <target state="translated">Affiche_r un aperçu pour le suivi des renommages</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_property_indexer_and_event_accessors"> <source>Place open brace on new line for property, indexer, and event accessors</source> <target state="translated">Placer une accolade ouvrante sur une nouvelle ligne pour les accesseurs de propriété, d'indexeur et d'événement</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_properties_indexers_and_events"> <source>Place open brace on new line for properties, indexers, and events</source> <target state="translated">Placer une accolade ouvrante sur une nouvelle ligne pour les propriétés, indexeurs et événements</target> <note /> </trans-unit> <trans-unit id="Suggest_usings_for_types_in_NuGet_packages"> <source>Suggest usings for types in _NuGet packages</source> <target state="translated">Suggérer des usings pour les types dans les packages _NuGet</target> <note /> </trans-unit> <trans-unit id="Type_Inference_preferences_colon"> <source>Type Inference preferences:</source> <target state="translated">Préférences d'inférence de type :</target> <note /> </trans-unit> <trans-unit id="For_built_in_types"> <source>For built-in types</source> <target state="translated">Pour les types intégrés</target> <note /> </trans-unit> <trans-unit id="Elsewhere"> <source>Elsewhere</source> <target state="translated">Ailleurs</target> <note /> </trans-unit> <trans-unit id="When_on_multiple_lines"> <source>When on multiple lines</source> <target state="translated">Si plusieurs lignes</target> <note /> </trans-unit> <trans-unit id="When_variable_type_is_apparent"> <source>When variable type is apparent</source> <target state="translated">Quand le type de variable est apparent</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_this"> <source>Qualify event access with 'this'</source> <target state="translated">Qualifier l'accès à l'événement avec 'this'</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_this"> <source>Qualify field access with 'this'</source> <target state="translated">Qualifier l'accès au champ avec 'this'</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_this"> <source>Qualify method access with 'this'</source> <target state="translated">Qualifier l'accès à la méthode avec 'this'</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_this"> <source>Qualify property access with 'this'</source> <target state="translated">Qualifier l'accès à la propriété avec 'this'</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_type"> <source>Prefer explicit type</source> <target state="translated">Préférer un type explicite</target> <note /> </trans-unit> <trans-unit id="Prefer_this"> <source>Prefer 'this.'</source> <target state="translated">Préférer 'this.'</target> <note /> </trans-unit> <trans-unit id="Prefer_var"> <source>Prefer 'var'</source> <target state="translated">Préférer 'var'</target> <note /> </trans-unit> <trans-unit id="this_preferences_colon"> <source>'this.' preferences:</source> <target state="translated">'Préférences 'this.' :</target> <note /> </trans-unit> <trans-unit id="using_preferences_colon"> <source>'using' preferences:</source> <target state="translated">Préférences pour 'using' :</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="var_preferences_colon"> <source>'var' preferences:</source> <target state="translated">'Préférences 'var' :</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_this"> <source>Do not prefer 'this.'</source> <target state="translated">Ne pas préférer 'this.'</target> <note /> </trans-unit> <trans-unit id="predefined_type_preferences_colon"> <source>predefined type preferences:</source> <target state="translated">Préférences de types prédéfinies :</target> <note /> </trans-unit> <trans-unit id="Split_string_literals_on_enter"> <source>Split string literals on _enter</source> <target state="translated">Fractionner les littéraux de chaîne avec _Entrée</target> <note /> </trans-unit> <trans-unit id="Highlight_matching_portions_of_completion_list_items"> <source>_Highlight matching portions of completion list items</source> <target state="translated">_Mettre en surbrillance les parties correspondantes des éléments de liste de saisie semi-automatique</target> <note /> </trans-unit> <trans-unit id="Show_completion_item_filters"> <source>Show completion item _filters</source> <target state="translated">Afficher les _filtres d'éléments de saisie semi-automatique</target> <note /> </trans-unit> <trans-unit id="Enter_key_behavior_colon"> <source>Enter key behavior:</source> <target state="translated">Comportement de la touche Entrée :</target> <note /> </trans-unit> <trans-unit id="Only_add_new_line_on_enter_after_end_of_fully_typed_word"> <source>_Only add new line on enter after end of fully typed word</source> <target state="translated">Aj_outer uniquement une nouvelle ligne après Entrée à la fin d'un mot complet tapé</target> <note /> </trans-unit> <trans-unit id="Always_add_new_line_on_enter"> <source>_Always add new line on enter</source> <target state="translated">Toujours _ajouter une nouvelle ligne après Entrée</target> <note /> </trans-unit> <trans-unit id="Never_add_new_line_on_enter"> <source>_Never add new line on enter</source> <target state="translated">_Ne jamais ajouter de nouvelle ligne après Entrée</target> <note /> </trans-unit> <trans-unit id="Always_include_snippets"> <source>Always include snippets</source> <target state="translated">Toujours inclure les extraits de code</target> <note /> </trans-unit> <trans-unit id="Include_snippets_when_Tab_is_typed_after_an_identifier"> <source>Include snippets when ?-Tab is typed after an identifier</source> <target state="translated">Inclure les extraits de code quand ?-Tab est typé après un identificateur</target> <note /> </trans-unit> <trans-unit id="Never_include_snippets"> <source>Never include snippets</source> <target state="translated">Ne jamais inclure d'extrait de code</target> <note /> </trans-unit> <trans-unit id="Snippets_behavior"> <source>Snippets behavior</source> <target state="translated">Comportement des extraits de code</target> <note /> </trans-unit> <trans-unit id="Show_completion_list_after_a_character_is_deleted"> <source>Show completion list after a character is _deleted</source> <target state="translated">Afficher la liste de saisie semi-automatique après la suppression d'un _caractère</target> <note /> </trans-unit> <trans-unit id="null_checking_colon"> <source>'null' checking:</source> <target state="translated">'vérification de valeur 'null' :</target> <note /> </trans-unit> <trans-unit id="Prefer_throw_expression"> <source>Prefer throw-expression</source> <target state="translated">Préférer l'expression throw</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_delegate_call"> <source>Prefer conditional delegate call</source> <target state="translated">Préférer l'appel de délégué conditionnel</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_is_with_cast_check"> <source>Prefer pattern matching over 'is' with 'cast' check</source> <target state="translated">Préférer les critères spéciaux à 'is' avec le contrôle de 'cast'</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_as_with_null_check"> <source>Prefer pattern matching over 'as' with 'null' check</source> <target state="translated">Préférer les critères spéciaux à 'as' avec le contrôle de 'null'</target> <note /> </trans-unit> <trans-unit id="Prefer_block_body"> <source>Prefer block body</source> <target state="translated">Préférer un corps de bloc</target> <note /> </trans-unit> <trans-unit id="Prefer_expression_body"> <source>Prefer expression body</source> <target state="translated">Préférer un corps d'expression</target> <note /> </trans-unit> <trans-unit id="Automatically_format_on_return"> <source>Automatically format on return</source> <target state="translated">Mise en forme automatique au retour</target> <note /> </trans-unit> <trans-unit id="Automatically_format_when_typing"> <source>Automatically format when typing</source> <target state="translated">Mise en forme automatique en cours de frappe</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">Jamais</target> <note /> </trans-unit> <trans-unit id="When_on_single_line"> <source>When on single line</source> <target state="translated">Sur une seule ligne</target> <note /> </trans-unit> <trans-unit id="When_possible"> <source>When possible</source> <target state="translated">Quand cela est possible</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents_when_block"> <source>Indent case contents (when block)</source> <target state="translated">Mettre en retrait le contenu de case (dans un bloc)</target> <note /> </trans-unit> <trans-unit id="Fade_out_unused_usings"> <source>Fade out unused usings</source> <target state="translated">Supprimer les instructions using inutilisées</target> <note /> </trans-unit> <trans-unit id="Report_invalid_placeholders_in_string_dot_format_calls"> <source>Report invalid placeholders in 'string.Format' calls</source> <target state="translated">Signaler les espaces réservés non valides dans les appels de 'String.Format'</target> <note /> </trans-unit> <trans-unit id="Separate_using_directive_groups"> <source>Separate using directive groups</source> <target state="translated">Séparer les groupes de directives using</target> <note /> </trans-unit> <trans-unit id="Show_name_suggestions"> <source>Show name s_uggestions</source> <target state="translated">Afficher les s_uggestions de nom</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators: * / % + - &lt;&lt; &gt;&gt; &amp; ^ |</source> <target state="translated">Dans les opérateurs arithmétiques : * / % + - &lt;&lt; &gt;&gt; &amp; ^ |</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators: &amp;&amp; || ?? and or</source> <target state="translated">Dans d'autres opérateurs binaires : &amp;&amp; || ?? and or</target> <note>'and' and 'or' are C# keywords and should not be localized</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/ExpressionEvaluator/Core/Source/FunctionResolver/FunctionResolverBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.VisualStudio.Debugger.Evaluation; using System; using System.Collections.Generic; using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal abstract class FunctionResolverBase<TProcess, TModule, TRequest> where TProcess : class where TModule : class where TRequest : class { internal abstract bool ShouldEnableFunctionResolver(TProcess process); internal abstract IEnumerable<TModule> GetAllModules(TProcess process); internal abstract string GetModuleName(TModule module); internal abstract unsafe bool TryGetMetadata(TModule module, out byte* pointer, out int length); internal abstract TRequest[] GetRequests(TProcess process); internal abstract string GetRequestModuleName(TRequest request); internal abstract RequestSignature GetParsedSignature(TRequest request); internal abstract bool IgnoreCase { get; } internal abstract Guid GetLanguageId(TRequest request); internal abstract Guid LanguageId { get; } internal void EnableResolution(TProcess process, TRequest request, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { if (!ShouldHandleRequest(request)) { return; } var moduleName = GetRequestModuleName(request); var signature = GetParsedSignature(request); if (signature == null) { return; } bool checkEnabled = true; foreach (var module in GetAllModules(process)) { if (checkEnabled) { if (!ShouldEnableFunctionResolver(process)) { return; } checkEnabled = false; } if (!ShouldModuleHandleRequest(module, moduleName)) { continue; } var reader = GetMetadataReader(module); if (reader == null) { // ignore modules with bad metadata continue; } var resolver = CreateMetadataResolver(module, reader, onFunctionResolved); resolver.Resolve(request, signature); } } private unsafe MetadataReader GetMetadataReader(TModule module) { if (!TryGetMetadata(module, out var pointer, out var length)) { return null; } try { return new MetadataReader(pointer, length); } catch (BadImageFormatException) { return null; } } internal void OnModuleLoad(TProcess process, TModule module, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { if (!ShouldEnableFunctionResolver(process)) { return; } MetadataResolver<TProcess, TModule, TRequest> resolver = null; var requests = GetRequests(process); foreach (var request in requests) { if (!ShouldHandleRequest(request)) { continue; } var moduleName = GetRequestModuleName(request); if (!ShouldModuleHandleRequest(module, moduleName)) { continue; } var signature = GetParsedSignature(request); if (signature == null) { continue; } if (resolver == null) { var reader = GetMetadataReader(module); if (reader == null) { return; } resolver = CreateMetadataResolver(module, reader, onFunctionResolved); } resolver.Resolve(request, signature); } } private MetadataResolver<TProcess, TModule, TRequest> CreateMetadataResolver( TModule module, MetadataReader reader, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { return new MetadataResolver<TProcess, TModule, TRequest>(module, reader, IgnoreCase, onFunctionResolved); } private bool ShouldHandleRequest(TRequest request) { var languageId = GetLanguageId(request); // Handle requests with no language id, a matching language id, // or causality breakpoint requests (debugging web services). return languageId == Guid.Empty || languageId == LanguageId || languageId == DkmLanguageId.CausalityBreakpoint; } private bool ShouldModuleHandleRequest(TModule module, string moduleName) { if (string.IsNullOrEmpty(moduleName)) { return true; } var name = GetModuleName(module); return moduleName.Equals(name, StringComparison.OrdinalIgnoreCase); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.VisualStudio.Debugger.Evaluation; using System; using System.Collections.Generic; using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal abstract class FunctionResolverBase<TProcess, TModule, TRequest> where TProcess : class where TModule : class where TRequest : class { internal abstract bool ShouldEnableFunctionResolver(TProcess process); internal abstract IEnumerable<TModule> GetAllModules(TProcess process); internal abstract string GetModuleName(TModule module); internal abstract unsafe bool TryGetMetadata(TModule module, out byte* pointer, out int length); internal abstract TRequest[] GetRequests(TProcess process); internal abstract string GetRequestModuleName(TRequest request); internal abstract RequestSignature GetParsedSignature(TRequest request); internal abstract bool IgnoreCase { get; } internal abstract Guid GetLanguageId(TRequest request); internal abstract Guid LanguageId { get; } internal void EnableResolution(TProcess process, TRequest request, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { if (!ShouldHandleRequest(request)) { return; } var moduleName = GetRequestModuleName(request); var signature = GetParsedSignature(request); if (signature == null) { return; } bool checkEnabled = true; foreach (var module in GetAllModules(process)) { if (checkEnabled) { if (!ShouldEnableFunctionResolver(process)) { return; } checkEnabled = false; } if (!ShouldModuleHandleRequest(module, moduleName)) { continue; } var reader = GetMetadataReader(module); if (reader == null) { // ignore modules with bad metadata continue; } var resolver = CreateMetadataResolver(module, reader, onFunctionResolved); resolver.Resolve(request, signature); } } private unsafe MetadataReader GetMetadataReader(TModule module) { if (!TryGetMetadata(module, out var pointer, out var length)) { return null; } try { return new MetadataReader(pointer, length); } catch (BadImageFormatException) { return null; } } internal void OnModuleLoad(TProcess process, TModule module, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { if (!ShouldEnableFunctionResolver(process)) { return; } MetadataResolver<TProcess, TModule, TRequest> resolver = null; var requests = GetRequests(process); foreach (var request in requests) { if (!ShouldHandleRequest(request)) { continue; } var moduleName = GetRequestModuleName(request); if (!ShouldModuleHandleRequest(module, moduleName)) { continue; } var signature = GetParsedSignature(request); if (signature == null) { continue; } if (resolver == null) { var reader = GetMetadataReader(module); if (reader == null) { return; } resolver = CreateMetadataResolver(module, reader, onFunctionResolved); } resolver.Resolve(request, signature); } } private MetadataResolver<TProcess, TModule, TRequest> CreateMetadataResolver( TModule module, MetadataReader reader, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { return new MetadataResolver<TProcess, TModule, TRequest>(module, reader, IgnoreCase, onFunctionResolved); } private bool ShouldHandleRequest(TRequest request) { var languageId = GetLanguageId(request); // Handle requests with no language id, a matching language id, // or causality breakpoint requests (debugging web services). return languageId == Guid.Empty || languageId == LanguageId || languageId == DkmLanguageId.CausalityBreakpoint; } private bool ShouldModuleHandleRequest(TModule module, string moduleName) { if (string.IsNullOrEmpty(moduleName)) { return true; } var name = GetModuleName(module); return moduleName.Equals(name, StringComparison.OrdinalIgnoreCase); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/CSharp/Test/Symbol/Symbols/StaticAbstractMembersInInterfacesTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; 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.Symbols { public class StaticAbstractMembersInInterfacesTests : CSharpTestBase { [Fact] public void MethodModifiers_01() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } private static void ValidateMethodModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<MethodSymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<MethodSymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<MethodSymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<MethodSymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<MethodSymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<MethodSymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<MethodSymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<MethodSymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<MethodSymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } [Fact] public void MethodModifiers_02() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_03() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_04() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_05() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static void M02() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static void M04() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static void M09() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_06() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static void M02() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static void M04() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static void M09() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void SealedStaticConstructor_01() { var source1 = @" interface I1 { sealed static I1() {} } partial interface I2 { partial sealed static I2(); } partial interface I2 { partial static I2() {} } partial interface I3 { partial static I3(); } partial interface I3 { partial sealed static I3() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,19): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I1").WithArguments("sealed").WithLocation(4, 19), // (9,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I2(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(9, 5), // (9,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I2(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(9, 5), // (9,27): error CS0106: The modifier 'sealed' is not valid for this item // partial sealed static I2(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(9, 27), // (14,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I2() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(14, 5), // (14,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I2() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(14, 5), // (14,20): error CS0111: Type 'I2' already defines a member called 'I2' with the same parameter types // partial static I2() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I2").WithArguments("I2", "I2").WithLocation(14, 20), // (19,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I3(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(19, 5), // (19,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I3(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(19, 5), // (24,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(24, 5), // (24,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(24, 5), // (24,27): error CS0106: The modifier 'sealed' is not valid for this item // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(24, 27), // (24,27): error CS0111: Type 'I3' already defines a member called 'I3' with the same parameter types // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I3").WithArguments("I3", "I3").WithLocation(24, 27) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>(".cctor"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); } [Fact] public void SealedStaticConstructor_02() { var source1 = @" partial interface I2 { sealed static partial I2(); } partial interface I2 { static partial I2() {} } partial interface I3 { static partial I3(); } partial interface I3 { sealed static partial I3() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,19): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // sealed static partial I2(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(4, 19), // (4,27): error CS0501: 'I2.I2()' must declare a body because it is not marked abstract, extern, or partial // sealed static partial I2(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I2").WithArguments("I2.I2()").WithLocation(4, 27), // (4,27): error CS0542: 'I2': member names cannot be the same as their enclosing type // sealed static partial I2(); Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I2").WithArguments("I2").WithLocation(4, 27), // (9,12): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // static partial I2() {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(9, 12), // (9,20): error CS0542: 'I2': member names cannot be the same as their enclosing type // static partial I2() {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I2").WithArguments("I2").WithLocation(9, 20), // (9,20): error CS0111: Type 'I2' already defines a member called 'I2' with the same parameter types // static partial I2() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I2").WithArguments("I2", "I2").WithLocation(9, 20), // (9,20): error CS0161: 'I2.I2()': not all code paths return a value // static partial I2() {} Diagnostic(ErrorCode.ERR_ReturnExpected, "I2").WithArguments("I2.I2()").WithLocation(9, 20), // (14,12): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // static partial I3(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(14, 12), // (14,20): error CS0501: 'I3.I3()' must declare a body because it is not marked abstract, extern, or partial // static partial I3(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I3").WithArguments("I3.I3()").WithLocation(14, 20), // (14,20): error CS0542: 'I3': member names cannot be the same as their enclosing type // static partial I3(); Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I3").WithArguments("I3").WithLocation(14, 20), // (19,19): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(19, 19), // (19,27): error CS0542: 'I3': member names cannot be the same as their enclosing type // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I3").WithArguments("I3").WithLocation(19, 27), // (19,27): error CS0111: Type 'I3' already defines a member called 'I3' with the same parameter types // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I3").WithArguments("I3", "I3").WithLocation(19, 27), // (19,27): error CS0161: 'I3.I3()': not all code paths return a value // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_ReturnExpected, "I3").WithArguments("I3.I3()").WithLocation(19, 27) ); } [Fact] public void AbstractStaticConstructor_01() { var source1 = @" interface I1 { abstract static I1(); } interface I2 { abstract static I2() {} } interface I3 { static I3(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "I1").WithArguments("abstract").WithLocation(4, 21), // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I2() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("abstract").WithLocation(9, 21), // (14,12): error CS0501: 'I3.I3()' must declare a body because it is not marked abstract, extern, or partial // static I3(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I3").WithArguments("I3.I3()").WithLocation(14, 12) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>(".cctor"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); } [Fact] public void PartialSealedStatic_01() { var source1 = @" partial interface I1 { sealed static partial void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Null(m01.PartialImplementationPart); } [Fact] public void PartialSealedStatic_02() { var source1 = @" partial interface I1 { sealed static partial void M01(); } partial interface I1 { sealed static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ValidatePartialSealedStatic_02(compilation1); } private static void ValidatePartialSealedStatic_02(CSharpCompilation compilation1) { compilation1.VerifyDiagnostics(); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialSealedStatic_03() { var source1 = @" partial interface I1 { static partial void M01(); } partial interface I1 { sealed static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ValidatePartialSealedStatic_02(compilation1); } [Fact] public void PartialSealedStatic_04() { var source1 = @" partial interface I1 { sealed static partial void M01(); } partial interface I1 { static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ValidatePartialSealedStatic_02(compilation1); } [Fact] public void PartialAbstractStatic_01() { var source1 = @" partial interface I1 { abstract static partial void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Null(m01.PartialImplementationPart); } [Fact] public void PartialAbstractStatic_02() { var source1 = @" partial interface I1 { abstract static partial void M01(); } partial interface I1 { abstract static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34), // (8,34): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(8, 34), // (8,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(8, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialAbstractStatic_03() { var source1 = @" partial interface I1 { abstract static partial void M01(); } partial interface I1 { static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialAbstractStatic_04() { var source1 = @" partial interface I1 { static partial void M01(); } partial interface I1 { abstract static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,34): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(8, 34), // (8,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(8, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PrivateAbstractStatic_01() { var source1 = @" interface I1 { private abstract static void M01(); private abstract static bool P01 { get; } private abstract static event System.Action E01; private abstract static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0621: 'I1.M01()': virtual or abstract members cannot be private // private abstract static void M01(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "M01").WithArguments("I1.M01()").WithLocation(4, 34), // (5,34): error CS0621: 'I1.P01': virtual or abstract members cannot be private // private abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_VirtualPrivate, "P01").WithArguments("I1.P01").WithLocation(5, 34), // (6,49): error CS0621: 'I1.E01': virtual or abstract members cannot be private // private abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_VirtualPrivate, "E01").WithArguments("I1.E01").WithLocation(6, 49), // (7,40): error CS0558: User-defined operator 'I1.operator +(I1)' must be declared static and public // private abstract static I1 operator+ (I1 x); Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 40) ); } [Fact] public void PropertyModifiers_01() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } private static void ValidatePropertyModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); { var m01 = i1.GetMember<PropertySymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<PropertySymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<PropertySymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<PropertySymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<PropertySymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<PropertySymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<PropertySymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<PropertySymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<PropertySymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<PropertySymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } { var m01 = i1.GetMember<PropertySymbol>("M01").GetMethod; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<PropertySymbol>("M02").GetMethod; Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<PropertySymbol>("M03").GetMethod; Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<PropertySymbol>("M04").GetMethod; Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<PropertySymbol>("M05").GetMethod; Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<PropertySymbol>("M06").GetMethod; Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<PropertySymbol>("M07").GetMethod; Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<PropertySymbol>("M08").GetMethod; Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<PropertySymbol>("M09").GetMethod; Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<PropertySymbol>("M10").GetMethod; Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } } [Fact] public void PropertyModifiers_02() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_03() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_04() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_05() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static bool M04 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_06() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static bool M04 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void EventModifiers_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event D M01 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 29), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static event D M03 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static event D M07 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static event D M10 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } private static void ValidateEventModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); { var m01 = i1.GetMember<EventSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<EventSymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<EventSymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<EventSymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<EventSymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<EventSymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<EventSymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<EventSymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<EventSymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<EventSymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } foreach (var addAccessor in new[] { true, false }) { var m01 = getAccessor(i1.GetMember<EventSymbol>("M01"), addAccessor); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = getAccessor(i1.GetMember<EventSymbol>("M02"), addAccessor); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = getAccessor(i1.GetMember<EventSymbol>("M03"), addAccessor); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = getAccessor(i1.GetMember<EventSymbol>("M04"), addAccessor); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = getAccessor(i1.GetMember<EventSymbol>("M05"), addAccessor); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = getAccessor(i1.GetMember<EventSymbol>("M06"), addAccessor); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = getAccessor(i1.GetMember<EventSymbol>("M07"), addAccessor); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = getAccessor(i1.GetMember<EventSymbol>("M08"), addAccessor); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = getAccessor(i1.GetMember<EventSymbol>("M09"), addAccessor); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = getAccessor(i1.GetMember<EventSymbol>("M10"), addAccessor); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } static MethodSymbol getAccessor(EventSymbol e, bool addAccessor) { return addAccessor ? e.AddMethod : e.RemoveMethod; } } [Fact] public void EventModifiers_02() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 29), // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static event D M03 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_03() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_04() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_05() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static event D M01 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 29), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (7,28): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static event D M02 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static event D M03 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (13,29): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static event D M04 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static event D M07 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (28,37): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static event D M09 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static event D M10 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_06() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 29), // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (7,28): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static event D M03 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (13,29): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (28,37): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void OperatorModifiers_01() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "9.0", "preview").WithLocation(10, 30), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "9.0", "preview").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "9.0", "preview").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "9.0", "preview").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "9.0", "preview").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } private static void ValidateOperatorModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("op_UnaryPlus"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<MethodSymbol>("op_UnaryNegation"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<MethodSymbol>("op_Increment"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<MethodSymbol>("op_Decrement"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<MethodSymbol>("op_LogicalNot"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<MethodSymbol>("op_OnesComplement"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<MethodSymbol>("op_Addition"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<MethodSymbol>("op_Subtraction"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<MethodSymbol>("op_Multiply"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<MethodSymbol>("op_Division"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } [Fact] public void OperatorModifiers_02() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(4, 32), // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "9.0", "preview").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "9.0", "preview").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "9.0", "preview").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "9.0", "preview").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "9.0", "preview").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_03() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_04() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_05() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-").WithArguments("default interface implementation", "8.0").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "7.3", "preview").WithLocation(10, 30), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "--").WithArguments("default interface implementation", "8.0").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "7.3", "preview").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "7.3", "preview").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "7.3", "preview").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "*").WithArguments("default interface implementation", "8.0").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "7.3", "preview").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_06() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(4, 32), // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-").WithArguments("default interface implementation", "8.0").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "7.3", "preview").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "--").WithArguments("default interface implementation", "8.0").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "7.3", "preview").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "7.3", "preview").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "7.3", "preview").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "*").WithArguments("default interface implementation", "8.0").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "7.3", "preview").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_07() { var source1 = @" public interface I1 { abstract static bool operator== (I1 x, I1 y); abstract static bool operator!= (I1 x, I1 y) {return false;} } public interface I2 { sealed static bool operator== (I2 x, I2 y); sealed static bool operator!= (I2 x, I2 y) {return false;} } public interface I3 { abstract sealed static bool operator== (I3 x, I3 y); abstract sealed static bool operator!= (I3 x, I3 y) {return false;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool operator== (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "7.3", "preview").WithLocation(4, 34), // (6,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "7.3", "preview").WithLocation(6, 34), // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (18,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "7.3", "preview").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "7.3", "preview").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator== (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(4, 34), // (6,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(6, 34), // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (18,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); void validate() { foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I1").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I2").GetMembers()) { Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I3").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } } } [Fact] public void OperatorModifiers_08() { var source1 = @" public interface I1 { abstract static implicit operator int(I1 x); abstract static explicit operator I1(bool x) {return null;} } public interface I2 { sealed static implicit operator int(I2 x); sealed static explicit operator I2(bool x) {return null;} } public interface I3 { abstract sealed static implicit operator int(I3 x); abstract sealed static explicit operator I3(bool x) {return null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "7.3", "preview").WithLocation(4, 39), // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I1").WithArguments("abstract", "7.3", "preview").WithLocation(6, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "7.3", "preview").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I3").WithArguments("abstract", "7.3", "preview").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(4, 39), // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I1").WithArguments("abstract", "9.0", "preview").WithLocation(6, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I3").WithArguments("abstract", "9.0", "preview").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); void validate() { foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I1").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I2").GetMembers()) { Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I3").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } } } [Fact] public void FieldModifiers_01() { var source1 = @" public interface I1 { abstract static int F1; sealed static int F2; abstract int F3; sealed int F4; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,25): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // abstract static int F1; Diagnostic(ErrorCode.ERR_AbstractField, "F1").WithLocation(4, 25), // (5,23): error CS0106: The modifier 'sealed' is not valid for this item // sealed static int F2; Diagnostic(ErrorCode.ERR_BadMemberFlag, "F2").WithArguments("sealed").WithLocation(5, 23), // (6,18): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // abstract int F3; Diagnostic(ErrorCode.ERR_AbstractField, "F3").WithLocation(6, 18), // (6,18): error CS0525: Interfaces cannot contain instance fields // abstract int F3; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F3").WithLocation(6, 18), // (7,16): error CS0106: The modifier 'sealed' is not valid for this item // sealed int F4; Diagnostic(ErrorCode.ERR_BadMemberFlag, "F4").WithArguments("sealed").WithLocation(7, 16), // (7,16): error CS0525: Interfaces cannot contain instance fields // sealed int F4; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F4").WithLocation(7, 16) ); } [Fact] public void ExternAbstractStatic_01() { var source1 = @" interface I1 { extern abstract static void M01(); extern abstract static bool P01 { get; } extern abstract static event System.Action E01; extern abstract static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0180: 'I1.M01()' cannot be both extern and abstract // extern abstract static void M01(); Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M01").WithArguments("I1.M01()").WithLocation(4, 33), // (5,33): error CS0180: 'I1.P01' cannot be both extern and abstract // extern abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P01").WithArguments("I1.P01").WithLocation(5, 33), // (6,48): error CS0180: 'I1.E01' cannot be both extern and abstract // extern abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "E01").WithArguments("I1.E01").WithLocation(6, 48), // (7,39): error CS0180: 'I1.operator +(I1)' cannot be both extern and abstract // extern abstract static I1 operator+ (I1 x); Diagnostic(ErrorCode.ERR_AbstractAndExtern, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 39) ); } [Fact] public void ExternAbstractStatic_02() { var source1 = @" interface I1 { extern abstract static void M01() {} extern abstract static bool P01 { get => false; } extern abstract static event System.Action E01 { add {} remove {} } extern abstract static I1 operator+ (I1 x) => null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0180: 'I1.M01()' cannot be both extern and abstract // extern abstract static void M01() {} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M01").WithArguments("I1.M01()").WithLocation(4, 33), // (5,33): error CS0180: 'I1.P01' cannot be both extern and abstract // extern abstract static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P01").WithArguments("I1.P01").WithLocation(5, 33), // (6,48): error CS0180: 'I1.E01' cannot be both extern and abstract // extern abstract static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "E01").WithArguments("I1.E01").WithLocation(6, 48), // (6,52): error CS8712: 'I1.E01': abstract event cannot use event accessor syntax // extern abstract static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.E01").WithLocation(6, 52), // (7,39): error CS0180: 'I1.operator +(I1)' cannot be both extern and abstract // extern abstract static I1 operator+ (I1 x) => null; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 39) ); } [Fact] public void ExternSealedStatic_01() { var source1 = @" #pragma warning disable CS0626 // Method, operator, or accessor is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. interface I1 { extern sealed static void M01(); extern sealed static bool P01 { get; } extern sealed static event System.Action E01; extern sealed static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void AbstractStaticInClass_01() { var source1 = @" abstract class C1 { public abstract static void M01(); public abstract static bool P01 { get; } public abstract static event System.Action E01; public abstract static C1 operator+ (C1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static void M01(); Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M01").WithArguments("abstract").WithLocation(4, 33), // (5,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P01").WithArguments("abstract").WithLocation(5, 33), // (6,48): error CS0112: A static member cannot be marked as 'abstract' // public abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "E01").WithArguments("abstract").WithLocation(6, 48), // (7,39): error CS0106: The modifier 'abstract' is not valid for this item // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("abstract").WithLocation(7, 39), // (7,39): error CS0501: 'C1.operator +(C1)' must declare a body because it is not marked abstract, extern, or partial // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("C1.operator +(C1)").WithLocation(7, 39) ); } [Fact] public void SealedStaticInClass_01() { var source1 = @" class C1 { sealed static void M01() {} sealed static bool P01 { get => false; } sealed static event System.Action E01 { add {} remove {} } public sealed static C1 operator+ (C1 x) => null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0238: 'C1.M01()' cannot be sealed because it is not an override // sealed static void M01() {} Diagnostic(ErrorCode.ERR_SealedNonOverride, "M01").WithArguments("C1.M01()").WithLocation(4, 24), // (5,24): error CS0238: 'C1.P01' cannot be sealed because it is not an override // sealed static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_SealedNonOverride, "P01").WithArguments("C1.P01").WithLocation(5, 24), // (6,39): error CS0238: 'C1.E01' cannot be sealed because it is not an override // sealed static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_SealedNonOverride, "E01").WithArguments("C1.E01").WithLocation(6, 39), // (7,37): error CS0106: The modifier 'sealed' is not valid for this item // public sealed static C1 operator+ (C1 x) => null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("sealed").WithLocation(7, 37) ); } [Fact] public void AbstractStaticInStruct_01() { var source1 = @" struct C1 { public abstract static void M01(); public abstract static bool P01 { get; } public abstract static event System.Action E01; public abstract static C1 operator+ (C1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static void M01(); Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M01").WithArguments("abstract").WithLocation(4, 33), // (5,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P01").WithArguments("abstract").WithLocation(5, 33), // (6,48): error CS0112: A static member cannot be marked as 'abstract' // public abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "E01").WithArguments("abstract").WithLocation(6, 48), // (7,39): error CS0106: The modifier 'abstract' is not valid for this item // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("abstract").WithLocation(7, 39), // (7,39): error CS0501: 'C1.operator +(C1)' must declare a body because it is not marked abstract, extern, or partial // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("C1.operator +(C1)").WithLocation(7, 39) ); } [Fact] public void SealedStaticInStruct_01() { var source1 = @" struct C1 { sealed static void M01() {} sealed static bool P01 { get => false; } sealed static event System.Action E01 { add {} remove {} } public sealed static C1 operator+ (C1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0238: 'C1.M01()' cannot be sealed because it is not an override // sealed static void M01() {} Diagnostic(ErrorCode.ERR_SealedNonOverride, "M01").WithArguments("C1.M01()").WithLocation(4, 24), // (5,24): error CS0238: 'C1.P01' cannot be sealed because it is not an override // sealed static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_SealedNonOverride, "P01").WithArguments("C1.P01").WithLocation(5, 24), // (6,39): error CS0238: 'C1.E01' cannot be sealed because it is not an override // sealed static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_SealedNonOverride, "E01").WithArguments("C1.E01").WithLocation(6, 39), // (7,37): error CS0106: The modifier 'sealed' is not valid for this item // public sealed static C1 operator+ (C1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("sealed").WithLocation(7, 37) ); } [Fact] public void DefineAbstractStaticMethod_01() { var source1 = @" interface I1 { abstract static void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); } } [Fact] public void DefineAbstractStaticMethod_02() { var source1 = @" interface I1 { abstract static void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 26) ); } [Theory] [InlineData("I1", "+", "(I1 x)")] [InlineData("I1", "-", "(I1 x)")] [InlineData("I1", "!", "(I1 x)")] [InlineData("I1", "~", "(I1 x)")] [InlineData("I1", "++", "(I1 x)")] [InlineData("I1", "--", "(I1 x)")] [InlineData("I1", "+", "(I1 x, I1 y)")] [InlineData("I1", "-", "(I1 x, I1 y)")] [InlineData("I1", "*", "(I1 x, I1 y)")] [InlineData("I1", "/", "(I1 x, I1 y)")] [InlineData("I1", "%", "(I1 x, I1 y)")] [InlineData("I1", "&", "(I1 x, I1 y)")] [InlineData("I1", "|", "(I1 x, I1 y)")] [InlineData("I1", "^", "(I1 x, I1 y)")] [InlineData("I1", "<<", "(I1 x, int y)")] [InlineData("I1", ">>", "(I1 x, int y)")] public void DefineAbstractStaticOperator_01(string type, string op, string paramList) { var source1 = @" interface I1 { abstract static " + type + " operator " + op + " " + paramList + @"; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); } } [Fact] public void DefineAbstractStaticOperator_02() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); abstract static I1 operator > (I1 x, I1 y); abstract static I1 operator < (I1 x, I1 y); abstract static I1 operator >= (I1 x, I1 y); abstract static I1 operator <= (I1 x, I1 y); abstract static I1 operator == (I1 x, I1 y); abstract static I1 operator != (I1 x, I1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(8, count); } } [Theory] [InlineData("I1", "+", "(I1 x)")] [InlineData("I1", "-", "(I1 x)")] [InlineData("I1", "!", "(I1 x)")] [InlineData("I1", "~", "(I1 x)")] [InlineData("I1", "++", "(I1 x)")] [InlineData("I1", "--", "(I1 x)")] [InlineData("I1", "+", "(I1 x, I1 y)")] [InlineData("I1", "-", "(I1 x, I1 y)")] [InlineData("I1", "*", "(I1 x, I1 y)")] [InlineData("I1", "/", "(I1 x, I1 y)")] [InlineData("I1", "%", "(I1 x, I1 y)")] [InlineData("I1", "&", "(I1 x, I1 y)")] [InlineData("I1", "|", "(I1 x, I1 y)")] [InlineData("I1", "^", "(I1 x, I1 y)")] [InlineData("I1", "<<", "(I1 x, int y)")] [InlineData("I1", ">>", "(I1 x, int y)")] public void DefineAbstractStaticOperator_03(string type, string op, string paramList) { var source1 = @" interface I1 { abstract static " + type + " operator " + op + " " + paramList + @"; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator + (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 31 + type.Length) ); } [Fact] public void DefineAbstractStaticOperator_04() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); abstract static I1 operator > (I1 x, I1 y); abstract static I1 operator < (I1 x, I1 y); abstract static I1 operator >= (I1 x, I1 y); abstract static I1 operator <= (I1 x, I1 y); abstract static I1 operator == (I1 x, I1 y); abstract static I1 operator != (I1 x, I1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(4, 35), // (5,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(5, 35), // (6,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator > (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, ">").WithLocation(6, 33), // (7,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator < (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "<").WithLocation(7, 33), // (8,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator >= (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, ">=").WithLocation(8, 33), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator <= (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "<=").WithLocation(9, 33), // (10,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator == (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "==").WithLocation(10, 33), // (11,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator != (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "!=").WithLocation(11, 33) ); } [Fact] public void DefineAbstractStaticConversion_01() { var source1 = @" interface I1<T> where T : I1<T> { abstract static implicit operator int(T x); abstract static explicit operator T(int x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticConversion_03() { var source1 = @" interface I1<T> where T : I1<T> { abstract static implicit operator int(T x); abstract static explicit operator T(int x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 39), // (5,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator T(int x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T").WithLocation(5, 39) ); } [Fact] public void DefineAbstractStaticProperty_01() { var source1 = @" interface I1 { abstract static int P01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var p01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); Assert.True(p01.IsAbstract); Assert.False(p01.IsVirtual); Assert.False(p01.IsSealed); Assert.True(p01.IsStatic); Assert.False(p01.IsOverride); int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticProperty_02() { var source1 = @" interface I1 { abstract static int P01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(4, 31), // (4,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(4, 36) ); } [Fact] public void DefineAbstractStaticEvent_01() { var source1 = @" interface I1 { abstract static event System.Action E01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var e01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); Assert.True(e01.IsAbstract); Assert.False(e01.IsVirtual); Assert.False(e01.IsSealed); Assert.True(e01.IsStatic); Assert.False(e01.IsOverride); int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticEvent_02() { var source1 = @" interface I1 { abstract static event System.Action E01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "E01").WithLocation(4, 41) ); } [Fact] public void ConstraintChecks_01() { var source1 = @" public interface I1 { abstract static void M01(); } public interface I2 : I1 { } public interface I3 : I2 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var source2 = @" class C1<T1> where T1 : I1 { void Test(C1<I2> x) { } } class C2 { void M<T2>() where T2 : I1 {} void Test(C2 x) { x.M<I2>(); } } class C3<T3> where T3 : I2 { void Test(C3<I2> x, C3<I3> y) { } } class C4 { void M<T4>() where T4 : I2 {} void Test(C4 x) { x.M<I2>(); x.M<I3>(); } } class C5<T5> where T5 : I3 { void Test(C5<I3> y) { } } class C6 { void M<T6>() where T6 : I3 {} void Test(C6 x) { x.M<I3>(); } } class C7<T7> where T7 : I1 { void Test(C7<I1> y) { } } class C8 { void M<T8>() where T8 : I1 {} void Test(C8 x) { x.M<I1>(); } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); var expected = new[] { // (4,22): error CS8920: The interface 'I2' cannot be used as type parameter 'T1' in the generic type or method 'C1<T1>'. The constraint interface 'I1' or its base interface has static abstract members. // void Test(C1<I2> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "x").WithArguments("C1<T1>", "I1", "T1", "I2").WithLocation(4, 22), // (15,11): error CS8920: The interface 'I2' cannot be used as type parameter 'T2' in the generic type or method 'C2.M<T2>()'. The constraint interface 'I1' or its base interface has static abstract members. // x.M<I2>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I2>").WithArguments("C2.M<T2>()", "I1", "T2", "I2").WithLocation(15, 11), // (21,22): error CS8920: The interface 'I2' cannot be used as type parameter 'T3' in the generic type or method 'C3<T3>'. The constraint interface 'I2' or its base interface has static abstract members. // void Test(C3<I2> x, C3<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "x").WithArguments("C3<T3>", "I2", "T3", "I2").WithLocation(21, 22), // (21,32): error CS8920: The interface 'I3' cannot be used as type parameter 'T3' in the generic type or method 'C3<T3>'. The constraint interface 'I2' or its base interface has static abstract members. // void Test(C3<I2> x, C3<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C3<T3>", "I2", "T3", "I3").WithLocation(21, 32), // (32,11): error CS8920: The interface 'I2' cannot be used as type parameter 'T4' in the generic type or method 'C4.M<T4>()'. The constraint interface 'I2' or its base interface has static abstract members. // x.M<I2>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I2>").WithArguments("C4.M<T4>()", "I2", "T4", "I2").WithLocation(32, 11), // (33,11): error CS8920: The interface 'I3' cannot be used as type parameter 'T4' in the generic type or method 'C4.M<T4>()'. The constraint interface 'I2' or its base interface has static abstract members. // x.M<I3>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I3>").WithArguments("C4.M<T4>()", "I2", "T4", "I3").WithLocation(33, 11), // (39,22): error CS8920: The interface 'I3' cannot be used as type parameter 'T5' in the generic type or method 'C5<T5>'. The constraint interface 'I3' or its base interface has static abstract members. // void Test(C5<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C5<T5>", "I3", "T5", "I3").WithLocation(39, 22), // (50,11): error CS8920: The interface 'I3' cannot be used as type parameter 'T6' in the generic type or method 'C6.M<T6>()'. The constraint interface 'I3' or its base interface has static abstract members. // x.M<I3>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I3>").WithArguments("C6.M<T6>()", "I3", "T6", "I3").WithLocation(50, 11), // (56,22): error CS8920: The interface 'I1' cannot be used as type parameter 'T7' in the generic type or method 'C7<T7>'. The constraint interface 'I1' or its base interface has static abstract members. // void Test(C7<I1> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C7<T7>", "I1", "T7", "I1").WithLocation(56, 22), // (67,11): error CS8920: The interface 'I1' cannot be used as type parameter 'T8' in the generic type or method 'C8.M<T8>()'. The constraint interface 'I1' or its base interface has static abstract members. // x.M<I1>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I1>").WithArguments("C8.M<T8>()", "I1", "T8", "I1").WithLocation(67, 11) }; compilation2.VerifyDiagnostics(expected); compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.EmitToImageReference() }); compilation2.VerifyDiagnostics(expected); } [Fact] public void ConstraintChecks_02() { var source1 = @" public interface I1 { abstract static void M01(); } public class C : I1 { public static void M01() {} } public struct S : I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var source2 = @" class C1<T1> where T1 : I1 { void Test(C1<C> x, C1<S> y, C1<T1> z) { } } class C2 { public void M<T2>(C2 x) where T2 : I1 { x.M<T2>(x); } void Test(C2 x) { x.M<C>(x); x.M<S>(x); } } class C3<T3> where T3 : I1 { void Test(C1<T3> z) { } } class C4 { void M<T4>(C2 x) where T4 : I1 { x.M<T4>(x); } } class C5<T5> { internal virtual void M<U5>() where U5 : T5 { } } class C6 : C5<I1> { internal override void M<U6>() { base.M<U6>(); } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyEmitDiagnostics(); compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.EmitToImageReference() }); compilation2.VerifyEmitDiagnostics(); } [Fact] public void VarianceSafety_01() { var source1 = @" interface I2<out T1, in T2> { abstract static T1 P1 { get; } abstract static T2 P2 { get; } abstract static T1 P3 { set; } abstract static T2 P4 { set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (5,21): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.P2'. 'T2' is contravariant. // abstract static T2 P2 { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I2<T1, T2>.P2", "T2", "contravariant", "covariantly").WithLocation(5, 21), // (6,21): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.P3'. 'T1' is covariant. // abstract static T1 P3 { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I2<T1, T2>.P3", "T1", "covariant", "contravariantly").WithLocation(6, 21) ); } [Fact] public void VarianceSafety_02() { var source1 = @" interface I2<out T1, in T2> { abstract static T1 M1(); abstract static T2 M2(); abstract static void M3(T1 x); abstract static void M4(T2 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (5,21): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.M2()'. 'T2' is contravariant. // abstract static T2 M2(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I2<T1, T2>.M2()", "T2", "contravariant", "covariantly").WithLocation(5, 21), // (6,29): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.M3(T1)'. 'T1' is covariant. // abstract static void M3(T1 x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I2<T1, T2>.M3(T1)", "T1", "covariant", "contravariantly").WithLocation(6, 29) ); } [Fact] public void VarianceSafety_03() { var source1 = @" interface I2<out T1, in T2> { abstract static event System.Action<System.Func<T1>> E1; abstract static event System.Action<System.Func<T2>> E2; abstract static event System.Action<System.Action<T1>> E3; abstract static event System.Action<System.Action<T2>> E4; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (5,58): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.E2'. 'T2' is contravariant. // abstract static event System.Action<System.Func<T2>> E2; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "E2").WithArguments("I2<T1, T2>.E2", "T2", "contravariant", "covariantly").WithLocation(5, 58), // (6,60): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.E3'. 'T1' is covariant. // abstract static event System.Action<System.Action<T1>> E3; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "E3").WithArguments("I2<T1, T2>.E3", "T1", "covariant", "contravariantly").WithLocation(6, 60) ); } [Fact] public void VarianceSafety_04() { var source1 = @" interface I2<out T2> { abstract static int operator +(I2<T2> x); } interface I3<out T3> { abstract static int operator +(I3<T3> x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,36): error CS1961: Invalid variance: The type parameter 'T2' must be contravariantly valid on 'I2<T2>.operator +(I2<T2>)'. 'T2' is covariant. // abstract static int operator +(I2<T2> x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "I2<T2>").WithArguments("I2<T2>.operator +(I2<T2>)", "T2", "covariant", "contravariantly").WithLocation(4, 36), // (9,36): error CS1961: Invalid variance: The type parameter 'T3' must be contravariantly valid on 'I3<T3>.operator +(I3<T3>)'. 'T3' is covariant. // abstract static int operator +(I3<T3> x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "I3<T3>").WithArguments("I3<T3>.operator +(I3<T3>)", "T3", "covariant", "contravariantly").WithLocation(9, 36) ); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("!")] [InlineData("~")] [InlineData("true")] [InlineData("false")] public void OperatorSignature_01(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x); } interface I13 { static abstract bool operator " + op + @"(I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,26): error CS0562: The parameter of a unary operator must be the containing type // static bool operator +(T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0562: The parameter of a unary operator must be the containing type // static bool operator +(T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T5 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T71 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T8 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T10 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator false(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11)").WithLocation(47, 18), // (51,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator false(int x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [InlineData("++")] [InlineData("--")] public void OperatorSignature_02(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static T1 operator " + op + @"(T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static T2? operator " + op + @"(T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract T3 operator " + op + @"(T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract T4? operator " + op + @"(T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract T5 operator " + op + @"(T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract T71 operator " + op + @"(T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract T8 operator " + op + @"(T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract T10 operator " + op + @"(T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract int operator " + op + @"(int x); } interface I13 { static abstract I13 operator " + op + @"(I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0559: The parameter type for ++ or -- operator must be the containing type // static T1 operator ++(T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecSignature, op).WithLocation(4, 24), // (9,25): error CS0559: The parameter type for ++ or -- operator must be the containing type // static T2? operator ++(T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecSignature, op).WithLocation(9, 25), // (26,37): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T5 operator ++(T5 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(26, 37), // (32,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T71 operator ++(T71 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(32, 34), // (37,33): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T8 operator ++(T8 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(37, 33), // (44,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T10 operator ++(T10 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(44, 34), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator --(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11)").WithLocation(47, 18), // (51,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract int operator ++(int x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(51, 34) ); } [Theory] [InlineData("++")] [InlineData("--")] public void OperatorSignature_03(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static T1 operator " + op + @"(I1<T1> x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static T2? operator " + op + @"(I2<T2> x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract T3 operator " + op + @"(I3<T3> x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract T4? operator " + op + @"(I4<T4> x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract T5 operator " + op + @"(I6 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract T71 operator " + op + @"(I7<T71, T72> x); } interface I8<T8> where T8 : I9<T8> { static abstract T8 operator " + op + @"(I8<T8> x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract T10 operator " + op + @"(I10<T10> x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract int operator " + op + @"(I12 x); } interface I13<T13> where T13 : struct, I13<T13> { static abstract T13? operator " + op + @"(T13 x); } interface I14<T14> where T14 : struct, I14<T14> { static abstract T14 operator " + op + @"(T14? x); } interface I15<T151, T152> where T151 : I15<T151, T152> where T152 : I15<T151, T152> { static abstract T151 operator " + op + @"(T152 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // static T1 operator ++(I1<T1> x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecRetType, op).WithLocation(4, 24), // (9,25): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // static T2? operator ++(I2<T2> x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecRetType, op).WithLocation(9, 25), // (19,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T4? operator ++(I4<T4> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(19, 34), // (26,37): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T5 operator ++(I6 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(26, 37), // (32,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T71 operator ++(I7<T71, T72> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(32, 34), // (37,33): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T8 operator ++(I8<T8> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(37, 33), // (44,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T10 operator ++(I10<T10> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(44, 34), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator ++(I10<T11>)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(I10<T11>)").WithLocation(47, 18), // (51,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract int operator ++(I12 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(51, 34), // (56,35): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T13? operator ++(T13 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(56, 35), // (61,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T14 operator ++(T14? x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(61, 34), // (66,35): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T151 operator ++(T152 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(66, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x, bool y) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x, bool y) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x, bool y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x, bool y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x, bool y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x, bool y); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x, bool y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x, bool y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x, bool y); } interface I13 { static abstract bool operator " + op + @"(I13 x, bool y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators)).Verify( // (4,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(T1 x, bool y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(T2? x, bool y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T5 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T71 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T8 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T10 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator /(T11, bool)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11, bool)").WithLocation(47, 18), // (51,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(int x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_05([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(bool y, T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(bool y, T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(bool y, T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(bool y, T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(bool y, T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(bool y, T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(bool y, T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(bool y, T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(bool y, int x); } interface I13 { static abstract bool operator " + op + @"(bool y, I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators)).Verify( // (4,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(bool y, T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(bool y, T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T5 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T71 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T8 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T10 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator <=(bool, T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(bool, T11)").WithLocation(47, 18), // (51,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, int x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [InlineData("<<")] [InlineData(">>")] public void OperatorSignature_06(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x, int y) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x, int y) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x, int y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x, int y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x, int y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x, int y); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x, int y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x, int y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x, int y); } interface I13 { static abstract bool operator " + op + @"(I13 x, int y); } interface I14 { static abstract bool operator " + op + @"(I14 x, bool y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,26): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // static bool operator <<(T1 x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // static bool operator <<(T2? x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T5 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T71 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T8 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T10 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator >>(T11, int)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11, int)").WithLocation(47, 18), // (51,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(int x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(51, 35), // (61,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(I14 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(61, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_07([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { abstract static " + op + @" operator T1(T1 y); } interface I2<T2> where T2 : I2<T2> { abstract static " + op + @" operator dynamic(T2 y); } interface I3<T3> where T3 : I3<T3> { static abstract " + op + @" operator T3(bool y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract " + op + @" operator T4?(bool y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract " + op + @" operator T5 (bool y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract " + op + @" operator T71 (bool y); } interface I8<T8> where T8 : I9<T8> { static abstract " + op + @" operator T8(bool y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract " + op + @" operator T10(bool y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract " + op + @" operator int(bool y); } interface I13 { static abstract " + op + @" operator I13(bool y); } interface I14<T14> where T14 : I14<T14> { abstract static " + op + @" operator object(T14 y); } class C15 {} class C16 : C15 {} interface I17<T17> where T17 : C15, I17<T17> { abstract static " + op + @" operator C16(T17 y); } interface I18<T18> where T18 : C16, I18<T18> { abstract static " + op + @" operator C15(T18 y); } interface I19<T19_1, T19_2> where T19_1 : I19<T19_1, T19_2>, T19_2 { abstract static " + op + @" operator T19_1(T19_2 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0555: User-defined operator cannot convert a type to itself // abstract static explicit operator T1(T1 y); Diagnostic(ErrorCode.ERR_IdentityConversion, "T1").WithLocation(4, 39), // (9,39): error CS1964: 'I2<T2>.explicit operator dynamic(T2)': user-defined conversions to or from the dynamic type are not allowed // abstract static explicit operator dynamic(T2 y); Diagnostic(ErrorCode.ERR_BadDynamicConversion, "dynamic").WithArguments("I2<T2>." + op + " operator dynamic(T2)").WithLocation(9, 39), // (26,43): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T5 (bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T5").WithLocation(26, 43), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T71 (bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T71").WithLocation(32, 39), // (37,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T8(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T8").WithLocation(37, 39), // (44,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T10(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T10").WithLocation(44, 39), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.explicit operator T11(bool)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>." + op + " operator T11(bool)").WithLocation(47, 18), // (51,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator int(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "int").WithLocation(51, 39), // (56,39): error CS0552: 'I13.explicit operator I13(bool)': user-defined conversions to or from an interface are not allowed // static abstract explicit operator I13(bool y); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I13").WithArguments("I13." + op + " operator I13(bool)").WithLocation(56, 39) ); } [Theory] [CombinatorialData] public void OperatorSignature_08([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { abstract static " + op + @" operator T1(T1 y); } interface I2<T2> where T2 : I2<T2> { abstract static " + op + @" operator T2(dynamic y); } interface I3<T3> where T3 : I3<T3> { static abstract " + op + @" operator bool(T3 y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract " + op + @" operator bool(T4? y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract " + op + @" operator bool(T5 y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract " + op + @" operator bool(T71 y); } interface I8<T8> where T8 : I9<T8> { static abstract " + op + @" operator bool(T8 y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract " + op + @" operator bool(T10 y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract " + op + @" operator bool(int y); } interface I13 { static abstract " + op + @" operator bool(I13 y); } interface I14<T14> where T14 : I14<T14> { abstract static " + op + @" operator T14(object y); } class C15 {} class C16 : C15 {} interface I17<T17> where T17 : C15, I17<T17> { abstract static " + op + @" operator T17(C16 y); } interface I18<T18> where T18 : C16, I18<T18> { abstract static " + op + @" operator T18(C15 y); } interface I19<T19_1, T19_2> where T19_1 : I19<T19_1, T19_2>, T19_2 { abstract static " + op + @" operator T19_2(T19_1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0555: User-defined operator cannot convert a type to itself // abstract static explicit operator T1(T1 y); Diagnostic(ErrorCode.ERR_IdentityConversion, "T1").WithLocation(4, 39), // (9,39): error CS1964: 'I2<T2>.explicit operator T2(dynamic)': user-defined conversions to or from the dynamic type are not allowed // abstract static explicit operator T2(dynamic y); Diagnostic(ErrorCode.ERR_BadDynamicConversion, "T2").WithArguments("I2<T2>." + op + " operator T2(dynamic)").WithLocation(9, 39), // (26,43): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T5 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(26, 43), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T71 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(32, 39), // (37,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T8 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(37, 39), // (44,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T10 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(44, 39), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.explicit operator bool(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>." + op + " operator bool(T11)").WithLocation(47, 18), // (51,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(int y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(51, 39), // (56,39): error CS0552: 'I13.explicit operator bool(I13)': user-defined conversions to or from an interface are not allowed // static abstract explicit operator bool(I13 y); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "bool").WithArguments("I13." + op + " operator bool(I13)").WithLocation(56, 39) ); } [Fact] public void ConsumeAbstractStaticMethod_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { M01(); M04(); } void M03() { this.M01(); this.M04(); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { I1.M01(); x.M01(); I1.M04(); x.M04(); } static void MT2<T>() where T : I1 { T.M03(); T.M04(); T.M00(); T.M05(); _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.M01()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // M01(); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "M01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // this.M01(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // this.M04(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.M01(); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.M01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // x.M01(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // x.M04(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M03(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M04(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M00(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.M05()' is inaccessible due to its protection level // T.M05(); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 11), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.M01()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01()").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticMethod_02() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = nameof(M01); _ = nameof(M04); } void M03() { _ = nameof(this.M01); _ = nameof(this.M04); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = nameof(I1.M01); _ = nameof(x.M01); _ = nameof(I1.M04); _ = nameof(x.M04); } static void MT2<T>() where T : I1 { _ = nameof(T.M03); _ = nameof(T.M04); _ = nameof(T.M00); _ = nameof(T.M05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = nameof(T.M05); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticMethod_03() { var source1 = @" public interface I1 { abstract static void M01(); abstract static void M04(int x); } class Test { static void M02<T, U>() where T : U where U : I1 { T.M01(); } static string M03<T, U>() where T : U where U : I1 { return nameof(T.M01); } static async void M05<T, U>() where T : U where U : I1 { T.M04(await System.Threading.Tasks.Task.FromResult(1)); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 14 (0xe) .maxstack 0 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""void I1.M01()"" IL_000c: nop IL_000d: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""M01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 12 (0xc) .maxstack 0 IL_0000: constrained. ""T"" IL_0006: call ""void I1.M01()"" IL_000b: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""M01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("T.M01()", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IInvocationOperation (virtual void I1.M01()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'T.M01()') Instance Receiver: null Arguments(0) "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("void I1.M01()", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("M01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticMethod_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.M01(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.M01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_05() { var source1 = @" public interface I1 { abstract static I1 Select(System.Func<int, int> p); } class Test { static void M02<T>() where T : I1 { _ = from t in T select t + 1; _ = from t in I1 select t + 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); // https://github.com/dotnet/roslyn/issues/53796: Confirm whether we want to enable the 'from t in T' scenario. compilation1.VerifyDiagnostics( // (11,23): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = from t in T select t + 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(11, 23), // (12,26): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = from t in I1 select t + 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "select t + 1").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.M01(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.M01(); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.M01(); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_01(string prefixOp, string postfixOp) { var source1 = @" interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); abstract static I1<T> operator" + prefixOp + postfixOp + @" (I1<T> x); static void M02(I1<T> x) { _ = " + prefixOp + "x" + postfixOp + @"; } void M03(I1<T> y) { _ = " + prefixOp + "y" + postfixOp + @"; } } class Test<T> where T : I1<T> { static void MT1(I1<T> a) { _ = " + prefixOp + "a" + postfixOp + @"; } static void MT2() { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (" + prefixOp + "b" + postfixOp + @").ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "x" + postfixOp).WithLocation(8, 13), // (13,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "y" + postfixOp).WithLocation(13, 13), // (21,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "a" + postfixOp).WithLocation(21, 13), (prefixOp + postfixOp).Length == 1 ? // (26,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (-b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, prefixOp + "b" + postfixOp).WithLocation(26, 78) : // (26,78): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b--).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, prefixOp + "b" + postfixOp).WithLocation(26, 78) ); } [Theory] [InlineData("+", "", "op_UnaryPlus", "Plus")] [InlineData("-", "", "op_UnaryNegation", "Minus")] [InlineData("!", "", "op_LogicalNot", "Not")] [InlineData("~", "", "op_OnesComplement", "BitwiseNegation")] [InlineData("++", "", "op_Increment", "Increment")] [InlineData("--", "", "op_Decrement", "Decrement")] [InlineData("", "++", "op_Increment", "Increment")] [InlineData("", "--", "op_Decrement", "Decrement")] public void ConsumeAbstractUnaryOperator_03(string prefixOp, string postfixOp, string metadataName, string opKind) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } class Test { static T M02<T, U>(T x) where T : U where U : I1<T> { return " + prefixOp + "x" + postfixOp + @"; } static T? M03<T, U>(T? y) where T : struct, U where U : I1<T> { return " + prefixOp + "y" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 21 (0x15) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: dup IL_000e: starg.s V_0 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: dup IL_002f: starg.s V_0 IL_0031: stloc.2 IL_0032: br.s IL_0034 IL_0034: ldloc.2 IL_0035: ret } "); break; case ("", "++"): case ("", "--"): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 21 (0x15) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: dup IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T)"" IL_000e: starg.s V_0 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: dup IL_0003: stloc.0 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: brtrue.s IL_0018 IL_000d: ldloca.s V_1 IL_000f: initobj ""T?"" IL_0015: ldloc.1 IL_0016: br.s IL_002f IL_0018: ldloca.s V_0 IL_001a: call ""readonly T T?.GetValueOrDefault()"" IL_001f: constrained. ""T"" IL_0025: call ""T I1<T>." + metadataName + @"(T)"" IL_002a: newobj ""T?..ctor(T)"" IL_002f: starg.s V_0 IL_0031: stloc.2 IL_0032: br.s IL_0034 IL_0034: ldloc.2 IL_0035: ret } "); break; default: verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); break; } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(T)"" IL_000c: dup IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0016 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: br.s IL_002d IL_0016: ldloca.s V_0 IL_0018: call ""readonly T T?.GetValueOrDefault()"" IL_001d: constrained. ""T"" IL_0023: call ""T I1<T>." + metadataName + @"(T)"" IL_0028: newobj ""T?..ctor(T)"" IL_002d: dup IL_002e: starg.s V_0 IL_0030: ret } "); break; case ("", "++"): case ("", "--"): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: dup IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: starg.s V_0 IL_0030: ret } "); break; default: verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(T)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""T I1<T>." + metadataName + @"(T)"" IL_0027: newobj ""T?..ctor(T)"" IL_002c: ret } "); break; } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = postfixOp != "" ? (ExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().First() : tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().First(); Assert.Equal(prefixOp + "x" + postfixOp, node.ToString()); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): case ("", "++"): case ("", "--"): VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IIncrementOrDecrementOperation (" + (prefixOp != "" ? "Prefix" : "Postfix") + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x)) (OperationKind." + opKind + @", Type: T) (Syntax: '" + prefixOp + "x" + postfixOp + @"') Target: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); break; default: VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IUnaryOperation (UnaryOperatorKind." + opKind + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x)) (OperationKind.Unary, Type: T) (Syntax: '" + prefixOp + "x" + postfixOp + @"') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); break; } } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_04(string prefixOp, string postfixOp) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1<T> { _ = " + prefixOp + "x" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = -x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, prefixOp + "x" + postfixOp).WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator- (T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, prefixOp + postfixOp).WithLocation(12, 31) ); } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_06(string prefixOp, string postfixOp) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1<T> { _ = " + prefixOp + "x" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = -x; Diagnostic(ErrorCode.ERR_FeatureInPreview, prefixOp + "x" + postfixOp).WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,31): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator- (T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, prefixOp + postfixOp).WithArguments("abstract", "9.0", "preview").WithLocation(12, 31) ); } [Fact] public void ConsumeAbstractTrueOperator_01() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); static void M02(I1 x) { _ = x ? true : false; } void M03(I1 y) { _ = y ? true : false; } } class Test { static void MT1(I1 a) { _ = a ? true : false; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b ? true : false).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x").WithLocation(9, 13), // (14,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y").WithLocation(14, 13), // (22,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a").WithLocation(22, 13), // (27,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b ? true : false).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b").WithLocation(27, 78) ); } [Fact] public void ConsumeAbstractTrueOperator_03() { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator true (T x); abstract static bool operator false (T x); } class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>.op_True(T)"" IL_000d: brtrue.s IL_0011 IL_000f: br.s IL_0011 IL_0011: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""bool I1<T>.op_True(T)"" IL_000c: pop IL_000d: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalExpressionSyntax>().First(); Assert.Equal("x ? true : false", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IConditionalOperation (OperationKind.Conditional, Type: System.Boolean) (Syntax: 'x ? true : false') Condition: IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean I1<T>.op_True(T x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') WhenTrue: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') WhenFalse: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') "); } [Fact] public void ConsumeAbstractTrueOperator_04() { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1 { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(12, 35), // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(13, 35) ); } [Fact] public void ConsumeAbstractTrueOperator_06() { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1 { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(12, 35), // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); static void M02((int, C<I1>) x) { _ = x " + op + @" x; } void M03((int, C<I1>) y) { _ = y " + op + @" y; } } class Test { static void MT1((int, C<I1>) a) { _ = a " + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b " + op + @" b).ToString()); } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x == x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " x").WithLocation(9, 13), // (14,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y == y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " y").WithLocation(14, 13), // (22,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a == a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " a").WithLocation(22, 13), // (27,98): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(27, 98) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator true (T x); abstract static bool operator false (T x); } class Test { static void M02<T, U>((int, C<T>) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 55 (0x37) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0034 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_False(T)"" IL_002f: ldc.i4.0 IL_0030: ceq IL_0032: br.s IL_0035 IL_0034: ldc.i4.0 IL_0035: pop IL_0036: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_True(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.1 IL_0032: pop IL_0033: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0033 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_False(T)"" IL_002e: ldc.i4.0 IL_002f: ceq IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: pop IL_0035: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_True(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.1 IL_0031: pop IL_0032: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1 { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (21,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(21, 35), // (22,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(22, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1 { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (21,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(21, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" partial interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); static void M02(I1 x) { _ = x " + op + @" 1; } void M03(I1 y) { _ = y " + op + @" 2; } } class Test { static void MT1(I1 a) { _ = a " + op + @" 3; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + @" 4).ToString()); } } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator" + matchingOp + @" (I1 x, int y); } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x - 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " 1").WithLocation(8, 13), // (13,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y - 2; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " 2").WithLocation(13, 13), // (21,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a - 3; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " 3").WithLocation(21, 13), // (26,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b - 4).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b " + op + " 4").WithLocation(26, 78) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_01(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" static void M02(I1 x) { _ = x " + op + op + @" x; } void M03(I1 y) { _ = y " + op + op + @" y; } } class Test { static void MT1(I1 a) { _ = a " + op + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + op + @" b).ToString()); } static void MT3(I1 b, dynamic c) { _ = b " + op + op + @" c; } "; if (!success) { source1 += @" static void MT4<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T, dynamic>>)((T d, dynamic e) => (d " + op + op + @" e).ToString()); } "; } source1 += @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); if (success) { Assert.False(binaryIsAbstract); Assert.False(op == "&" ? falseIsAbstract : trueIsAbstract); var binaryMetadataName = op == "&" ? "op_BitwiseAnd" : "op_BitwiseOr"; var unaryMetadataName = op == "&" ? "op_False" : "op_True"; var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.MT1(I1)", @" { // Code size 22 (0x16) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0009: brtrue.s IL_0015 IL_000b: ldloc.0 IL_000c: ldarg.0 IL_000d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0012: pop IL_0013: br.s IL_0015 IL_0015: ret } "); if (op == "&") { verifier.VerifyIL("Test.MT3(I1, dynamic)", @" { // Code size 97 (0x61) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""bool I1.op_False(I1)"" IL_0007: brtrue.s IL_0060 IL_0009: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_000e: brfalse.s IL_0012 IL_0010: br.s IL_0047 IL_0012: ldc.i4.8 IL_0013: ldc.i4.2 IL_0014: ldtoken ""Test"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.2 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.1 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: dup IL_002f: ldc.i4.1 IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0037: stelem.ref IL_0038: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0042: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_004c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Target"" IL_0051: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0056: ldarg.0 IL_0057: ldarg.1 IL_0058: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, I1, dynamic)"" IL_005d: pop IL_005e: br.s IL_0060 IL_0060: ret } "); } else { verifier.VerifyIL("Test.MT3(I1, dynamic)", @" { // Code size 98 (0x62) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""bool I1.op_True(I1)"" IL_0007: brtrue.s IL_0061 IL_0009: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_000e: brfalse.s IL_0012 IL_0010: br.s IL_0048 IL_0012: ldc.i4.8 IL_0013: ldc.i4.s 36 IL_0015: ldtoken ""Test"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: ldc.i4.2 IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0025: dup IL_0026: ldc.i4.0 IL_0027: ldc.i4.1 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: dup IL_0030: ldc.i4.1 IL_0031: ldc.i4.0 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003e: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0043: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_004d: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Target"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0057: ldarg.0 IL_0058: ldarg.1 IL_0059: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, I1, dynamic)"" IL_005e: pop IL_005f: br.s IL_0061 IL_0061: ret } "); } } else { var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); builder.AddRange( // (10,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x && x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + op + " x").WithLocation(10, 13), // (15,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y && y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + op + " y").WithLocation(15, 13), // (23,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a && a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + op + " a").WithLocation(23, 13), // (28,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b && b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b " + op + op + " b").WithLocation(28, 78) ); if (op == "&" ? falseIsAbstract : trueIsAbstract) { builder.Add( // (33,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = b || c; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "b " + op + op + " c").WithLocation(33, 13) ); } builder.Add( // (38,98): error CS7083: Expression must be implicitly convertible to Boolean or its type 'T' must define operator 'true'. // _ = (System.Linq.Expressions.Expression<System.Action<T, dynamic>>)((T d, dynamic e) => (d || e).ToString()); Diagnostic(ErrorCode.ERR_InvalidDynamicCondition, "d").WithArguments("T", op == "&" ? "false" : "true").WithLocation(38, 98) ); compilation1.VerifyDiagnostics(builder.ToArrayAndFree()); } } [Theory] [CombinatorialData] public void ConsumeAbstractCompoundBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>")] string op) { var source1 = @" interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); static void M02(I1 x) { x " + op + @"= 1; } void M03(I1 y) { y " + op + @"= 2; } } interface I2<T> where T : I2<T> { abstract static T operator" + op + @" (T x, int y); } class Test { static void MT1(I1 a) { a " + op + @"= 3; } static void MT2<T>() where T : I2<T> { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + @"= 4).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x /= 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + "= 1").WithLocation(8, 9), // (13,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // y /= 2; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + "= 2").WithLocation(13, 9), // (26,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // a /= 3; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + "= 3").WithLocation(26, 9), // (31,78): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b /= 4).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "b " + op + "= 4").WithLocation(31, 78) ); } private static string BinaryOperatorKind(string op) { switch (op) { case "+": return "Add"; case "-": return "Subtract"; case "*": return "Multiply"; case "/": return "Divide"; case "%": return "Remainder"; case "<<": return "LeftShift"; case ">>": return "RightShift"; case "&": return "And"; case "|": return "Or"; case "^": return "ExclusiveOr"; case "<": return "LessThan"; case "<=": return "LessThanOrEqual"; case "==": return "Equals"; case "!=": return "NotEquals"; case ">=": return "GreaterThanOrEqual"; case ">": return "GreaterThan"; } throw TestExceptionUtilities.UnexpectedValue(op); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); abstract static bool operator == (I1<T> x, I1<T> y); abstract static bool operator != (I1<T> x, I1<T> y); static void M02((int, I1<T>) x) { _ = x " + op + @" x; } void M03((int, I1<T>) y) { _ = y " + op + @" y; } } class Test { static void MT1<T>((int, I1<T>) a) where T : I1<T> { _ = a " + op + @" a; } static void MT2<T>() where T : I1<T> { _ = (System.Linq.Expressions.Expression<System.Action<(int, T)>>)(((int, T) b) => (b " + op + @" b).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x == x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " x").WithLocation(12, 13), // (17,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y == y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " y").WithLocation(17, 13), // (25,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a == a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " a").WithLocation(25, 13), // (30,92): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, T)>>)(((int, T) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(30, 92) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_03([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>")] string op) { string metadataName = BinaryOperatorName(op); bool isShiftOperator = op is "<<" or ">>"; var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static T0 operator" + op + @" (T0 x, int a); } partial class Test { static void M03<T, U>(T x) where T : U where U : I1<T> { _ = x " + op + @" 1; } static void M05<T, U>(T? y) where T : struct, U where U : I1<T> { _ = y " + op + @" 1; } } "; if (!isShiftOperator) { source1 += @" public partial interface I1<T0> { abstract static T0 operator" + op + @" (int a, T0 x); abstract static T0 operator" + op + @" (I1<T0> x, T0 a); abstract static T0 operator" + op + @" (T0 x, I1<T0> a); } partial class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = 1 " + op + @" x; } static void M04<T, U>(T? y) where T : struct, U where U : I1<T> { _ = 1 " + op + @" y; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { _ = x " + op + @" y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { _ = x " + op + @" y; } } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldarg.0 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(int, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_000e IL_000c: br.s IL_0022 IL_000e: ldc.i4.1 IL_000f: ldloca.s V_0 IL_0011: call ""readonly T T?.GetValueOrDefault()"" IL_0016: constrained. ""T"" IL_001c: call ""T I1<T>." + metadataName + @"(int, T)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: pop IL_000f: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_000e IL_000c: br.s IL_0022 IL_000e: ldloca.s V_0 IL_0010: call ""readonly T T?.GetValueOrDefault()"" IL_0015: ldc.i4.1 IL_0016: constrained. ""T"" IL_001c: call ""T I1<T>." + metadataName + @"(T, int)"" IL_0021: pop IL_0022: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 32 (0x20) .maxstack 2 .locals init (T? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brfalse.s IL_001f IL_000b: ldc.i4.1 IL_000c: ldloca.s V_0 IL_000e: call ""readonly T T?.GetValueOrDefault()"" IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + metadataName + @"(int, T)"" IL_001e: pop IL_001f: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: pop IL_000e: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 32 (0x20) .maxstack 2 .locals init (T? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brfalse.s IL_001f IL_000b: ldloca.s V_0 IL_000d: call ""readonly T T?.GetValueOrDefault()"" IL_0012: ldc.i4.1 IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + metadataName + @"(T, int)"" IL_001e: pop IL_001f: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " 1").Single(); Assert.Equal("x " + op + " 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.Binary, Type: T) (Syntax: 'x " + op + @" 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractComparisonBinaryOperator_03([CombinatorialValues("<", ">", "<=", ">=", "==", "!=")] string op) { string metadataName = BinaryOperatorName(op); var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static bool operator" + op + @" (T0 x, int a); abstract static bool operator" + op + @" (int a, T0 x); abstract static bool operator" + op + @" (I1<T0> x, T0 a); abstract static bool operator" + op + @" (T0 x, I1<T0> a); } partial class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = 1 " + op + @" x; } static void M03<T, U>(T x) where T : U where U : I1<T> { _ = x " + op + @" 1; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { _ = x " + op + @" y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { _ = x " + op + @" y; } } "; string matchingOp = MatchingBinaryOperator(op); source1 += @" public partial interface I1<T0> { abstract static bool operator" + matchingOp + @" (T0 x, int a); abstract static bool operator" + matchingOp + @" (int a, T0 x); abstract static bool operator" + matchingOp + @" (I1<T0> x, T0 a); abstract static bool operator" + matchingOp + @" (T0 x, I1<T0> a); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldarg.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(int, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(T, int)"" IL_000e: pop IL_000f: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(int, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(T, int)"" IL_000d: pop IL_000e: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " 1").Single(); Assert.Equal("x " + op + " 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @") (OperatorMethod: System.Boolean I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x " + op + @" 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractLiftedComparisonBinaryOperator_03([CombinatorialValues("<", ">", "<=", ">=", "==", "!=")] string op) { string metadataName = BinaryOperatorName(op); var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static bool operator" + op + @" (T0 x, T0 a); } partial class Test { static void M04<T, U>(T? x, T? y) where T : struct, U where U : I1<T> { _ = x " + op + @" y; } } "; string matchingOp = MatchingBinaryOperator(op); source1 += @" public partial interface I1<T0> { abstract static bool operator" + matchingOp + @" (T0 x, T0 a); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op is "==" or "!=") { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 61 (0x3d) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool T?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: beq.s IL_0017 IL_0015: br.s IL_003c IL_0017: ldloca.s V_0 IL_0019: call ""readonly bool T?.HasValue.get"" IL_001e: brtrue.s IL_0022 IL_0020: br.s IL_003c IL_0022: ldloca.s V_0 IL_0024: call ""readonly T T?.GetValueOrDefault()"" IL_0029: ldloca.s V_1 IL_002b: call ""readonly T T?.GetValueOrDefault()"" IL_0030: constrained. ""T"" IL_0036: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_003b: pop IL_003c: ret } "); } else { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool T?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: and IL_0014: brtrue.s IL_0018 IL_0016: br.s IL_0032 IL_0018: ldloca.s V_0 IL_001a: call ""readonly T T?.GetValueOrDefault()"" IL_001f: ldloca.s V_1 IL_0021: call ""readonly T T?.GetValueOrDefault()"" IL_0026: constrained. ""T"" IL_002c: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_0031: pop IL_0032: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op is "==" or "!=") { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 56 (0x38) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: bne.un.s IL_0037 IL_0014: ldloca.s V_0 IL_0016: call ""readonly bool T?.HasValue.get"" IL_001b: brfalse.s IL_0037 IL_001d: ldloca.s V_0 IL_001f: call ""readonly T T?.GetValueOrDefault()"" IL_0024: ldloca.s V_1 IL_0026: call ""readonly T T?.GetValueOrDefault()"" IL_002b: constrained. ""T"" IL_0031: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_0036: pop IL_0037: ret } "); } else { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 48 (0x30) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: and IL_0013: brfalse.s IL_002f IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: ldloca.s V_1 IL_001e: call ""readonly T T?.GetValueOrDefault()"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_002e: pop IL_002f: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " y").Single(); Assert.Equal("x " + op + " y", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @", IsLifted) (OperatorMethod: System.Boolean I1<T>." + metadataName + @"(T x, T a)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x " + op + @" y') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T?) (Syntax: 'x') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T?) (Syntax: 'y') "); } [Theory] [InlineData("&", true, true)] [InlineData("|", true, true)] [InlineData("&", true, false)] [InlineData("|", true, false)] [InlineData("&", false, true)] [InlineData("|", false, true)] public void ConsumeAbstractLogicalBinaryOperator_03(string op, bool binaryIsAbstract, bool unaryIsAbstract) { var binaryMetadataName = op == "&" ? "op_BitwiseAnd" : "op_BitwiseOr"; var unaryMetadataName = op == "&" ? "op_False" : "op_True"; var opKind = op == "&" ? "ConditionalAnd" : "ConditionalOr"; if (binaryIsAbstract && unaryIsAbstract) { consumeAbstract(op); } else { consumeMixed(op, binaryIsAbstract, unaryIsAbstract); } void consumeAbstract(string op) { var source1 = @" public interface I1<T0> where T0 : I1<T0> { abstract static T0 operator" + op + @" (T0 a, T0 x); abstract static bool operator true (T0 x); abstract static bool operator false (T0 x); } public interface I2<T0> where T0 : struct, I2<T0> { abstract static T0 operator" + op + @" (T0 a, T0 x); abstract static bool operator true (T0? x); abstract static bool operator false (T0? x); } class Test { static void M03<T, U>(T x, T y) where T : U where U : I1<T> { _ = x " + op + op + @" y; } static void M04<T, U>(T? x, T? y) where T : struct, U where U : I2<T> { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 34 (0x22) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: constrained. ""T"" IL_000a: call ""bool I1<T>." + unaryMetadataName + @"(T)"" IL_000f: brtrue.s IL_0021 IL_0011: ldloc.0 IL_0012: ldarg.1 IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + binaryMetadataName + @"(T, T)"" IL_001e: pop IL_001f: br.s IL_0021 IL_0021: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 69 (0x45) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: constrained. ""T"" IL_000a: call ""bool I2<T>." + unaryMetadataName + @"(T?)"" IL_000f: brtrue.s IL_0044 IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldarg.1 IL_0014: stloc.2 IL_0015: ldloca.s V_1 IL_0017: call ""readonly bool T?.HasValue.get"" IL_001c: ldloca.s V_2 IL_001e: call ""readonly bool T?.HasValue.get"" IL_0023: and IL_0024: brtrue.s IL_0028 IL_0026: br.s IL_0042 IL_0028: ldloca.s V_1 IL_002a: call ""readonly T T?.GetValueOrDefault()"" IL_002f: ldloca.s V_2 IL_0031: call ""readonly T T?.GetValueOrDefault()"" IL_0036: constrained. ""T"" IL_003c: call ""T I2<T>." + binaryMetadataName + @"(T, T)"" IL_0041: pop IL_0042: br.s IL_0044 IL_0044: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + unaryMetadataName + @"(T)"" IL_000e: brtrue.s IL_001e IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: constrained. ""T"" IL_0018: call ""T I1<T>." + binaryMetadataName + @"(T, T)"" IL_001d: pop IL_001e: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 64 (0x40) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I2<T>." + unaryMetadataName + @"(T?)"" IL_000e: brtrue.s IL_003f IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: ldarg.1 IL_0013: stloc.2 IL_0014: ldloca.s V_1 IL_0016: call ""readonly bool T?.HasValue.get"" IL_001b: ldloca.s V_2 IL_001d: call ""readonly bool T?.HasValue.get"" IL_0022: and IL_0023: brfalse.s IL_003f IL_0025: ldloca.s V_1 IL_0027: call ""readonly T T?.GetValueOrDefault()"" IL_002c: ldloca.s V_2 IL_002e: call ""readonly T T?.GetValueOrDefault()"" IL_0033: constrained. ""T"" IL_0039: call ""T I2<T>." + binaryMetadataName + @"(T, T)"" IL_003e: pop IL_003f: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + op + " y").First(); Assert.Equal("x " + op + op + " y", node1.ToString()); VerifyOperationTreeForNode(compilation1, model, node1, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + opKind + @") (OperatorMethod: T I1<T>." + binaryMetadataName + @"(T a, T x)) (OperationKind.Binary, Type: T) (Syntax: 'x " + op + op + @" y') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T) (Syntax: 'y') "); } void consumeMixed(string op, bool binaryIsAbstract, bool unaryIsAbstract) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 a, I1 x)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (unaryIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (unaryIsAbstract ? ";" : " => throw null;") + @" " + (unaryIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (unaryIsAbstract ? ";" : " => throw null;") + @" } class Test { static void M03<T, U>(T x, T y) where T : U where U : I1 { _ = x " + op + op + @" y; } static void M04<T, U>(T? x, T? y) where T : struct, U where U : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch (binaryIsAbstract, unaryIsAbstract) { case (true, false): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000e: brtrue.s IL_0025 IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: box ""T"" IL_0017: constrained. ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T?"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000e: brtrue.s IL_0025 IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: box ""T?"" IL_0017: constrained. ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); break; case (false, true): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: constrained. ""T"" IL_000f: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldarg.1 IL_0018: box ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T?"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: constrained. ""T"" IL_000f: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldarg.1 IL_0018: box ""T?"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); break; default: Assert.True(false); break; } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch (binaryIsAbstract, unaryIsAbstract) { case (true, false): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000d: brtrue.s IL_0022 IL_000f: ldloc.0 IL_0010: ldarg.1 IL_0011: box ""T"" IL_0016: constrained. ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T?"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000d: brtrue.s IL_0022 IL_000f: ldloc.0 IL_0010: ldarg.1 IL_0011: box ""T?"" IL_0016: constrained. ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); break; case (false, true): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: constrained. ""T"" IL_000e: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0013: brtrue.s IL_0022 IL_0015: ldloc.0 IL_0016: ldarg.1 IL_0017: box ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T?"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: constrained. ""T"" IL_000e: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0013: brtrue.s IL_0022 IL_0015: ldloc.0 IL_0016: ldarg.1 IL_0017: box ""T?"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); break; default: Assert.True(false); break; } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + op + " y").First(); Assert.Equal("x " + op + op + " y", node1.ToString()); VerifyOperationTreeForNode(compilation1, model, node1, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + opKind + @") (OperatorMethod: I1 I1." + binaryMetadataName + @"(I1 a, I1 x)) (OperationKind.Binary, Type: I1) (Syntax: 'x " + op + op + @" y') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: I1, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: I1, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T) (Syntax: 'y') "); } } [Theory] [InlineData("+", "op_Addition", "Add")] [InlineData("-", "op_Subtraction", "Subtract")] [InlineData("*", "op_Multiply", "Multiply")] [InlineData("/", "op_Division", "Divide")] [InlineData("%", "op_Modulus", "Remainder")] [InlineData("&", "op_BitwiseAnd", "And")] [InlineData("|", "op_BitwiseOr", "Or")] [InlineData("^", "op_ExclusiveOr", "ExclusiveOr")] [InlineData("<<", "op_LeftShift", "LeftShift")] [InlineData(">>", "op_RightShift", "RightShift")] public void ConsumeAbstractCompoundBinaryOperator_03(string op, string metadataName, string operatorKind) { bool isShiftOperator = op.Length == 2; var source1 = @" public interface I1<T0> where T0 : I1<T0> { "; if (!isShiftOperator) { source1 += @" abstract static int operator" + op + @" (int a, T0 x); abstract static I1<T0> operator" + op + @" (I1<T0> x, T0 a); abstract static T0 operator" + op + @" (T0 x, I1<T0> a); "; } source1 += @" abstract static T0 operator" + op + @" (T0 x, int a); } class Test { "; if (!isShiftOperator) { source1 += @" static void M02<T, U>(int a, T x) where T : U where U : I1<T> { a " + op + @"= x; } static void M04<T, U>(int? a, T? y) where T : struct, U where U : I1<T> { a " + op + @"= y; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { x " + op + @"= y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { x " + op + @"= y; } "; } source1 += @" static void M03<T, U>(T x) where T : U where U : I1<T> { x " + op + @"= 1; } static void M05<T, U>(T? y) where T : struct, U where U : I1<T> { y " + op + @"= 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(int, T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""int I1<T>." + metadataName + @"(int, T)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?, T?)", @" { // Code size 66 (0x42) .maxstack 2 .locals init (int? V_0, T? V_1, int? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool int?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: and IL_0014: brtrue.s IL_0021 IL_0016: ldloca.s V_2 IL_0018: initobj ""int?"" IL_001e: ldloc.2 IL_001f: br.s IL_003f IL_0021: ldloca.s V_0 IL_0023: call ""readonly int int?.GetValueOrDefault()"" IL_0028: ldloca.s V_1 IL_002a: call ""readonly T T?.GetValueOrDefault()"" IL_002f: constrained. ""T"" IL_0035: call ""int I1<T>." + metadataName + @"(int, T)"" IL_003a: newobj ""int?..ctor(int)"" IL_003f: starg.s V_0 IL_0041: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""I1<T> I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: starg.s V_0 IL_0010: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 50 (0x32) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002f IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: ldc.i4.1 IL_001f: constrained. ""T"" IL_0025: call ""T I1<T>." + metadataName + @"(T, int)"" IL_002a: newobj ""T?..ctor(T)"" IL_002f: starg.s V_0 IL_0031: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(int, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(int, T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?, T?)", @" { // Code size 65 (0x41) .maxstack 2 .locals init (int? V_0, T? V_1, int? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool int?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: and IL_0013: brtrue.s IL_0020 IL_0015: ldloca.s V_2 IL_0017: initobj ""int?"" IL_001d: ldloc.2 IL_001e: br.s IL_003e IL_0020: ldloca.s V_0 IL_0022: call ""readonly int int?.GetValueOrDefault()"" IL_0027: ldloca.s V_1 IL_0029: call ""readonly T T?.GetValueOrDefault()"" IL_002e: constrained. ""T"" IL_0034: call ""int I1<T>." + metadataName + @"(int, T)"" IL_0039: newobj ""int?..ctor(int)"" IL_003e: starg.s V_0 IL_0040: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""I1<T> I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: starg.s V_0 IL_000f: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0016 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: br.s IL_002e IL_0016: ldloca.s V_0 IL_0018: call ""readonly T T?.GetValueOrDefault()"" IL_001d: ldc.i4.1 IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T, int)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: starg.s V_0 IL_0030: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(n => n.ToString() == "x " + op + "= 1").Single(); Assert.Equal("x " + op + "= 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" ICompoundAssignmentOperation (BinaryOperatorKind." + operatorKind + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.CompoundAssignment, Type: T) (Syntax: 'x " + op + @"= 1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } class Test { static void M02<T, U>((int, T) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0011: bne.un.s IL_002c IL_0013: ldloc.0 IL_0014: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001f: constrained. ""T"" IL_0025: call ""bool I1<T>.op_Equality(T, T)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.0 IL_002d: pop IL_002e: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0011: bne.un.s IL_002c IL_0013: ldloc.0 IL_0014: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001f: constrained. ""T"" IL_0025: call ""bool I1<T>.op_Inequality(T, T)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.1 IL_002d: pop IL_002e: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0010: bne.un.s IL_002b IL_0012: ldloc.0 IL_0013: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001e: constrained. ""T"" IL_0024: call ""bool I1<T>.op_Equality(T, T)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0010: bne.un.s IL_002b IL_0012: ldloc.0 IL_0013: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001e: constrained. ""T"" IL_0024: call ""bool I1<T>.op_Inequality(T, T)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.1 IL_002c: pop IL_002d: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, T)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, T)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1 { _ = x " + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x - y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " y").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator- (I1 x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 32) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_04(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" } "; var source2 = @" class Test { static void M02<T>(T x, T y) where T : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); if (success) { compilation2.VerifyDiagnostics(); } else { compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x && y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + op + " y").WithLocation(6, 13) ); } var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); if (binaryIsAbstract) { builder.Add( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator& (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 32) ); } if (trueIsAbstract) { builder.Add( // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(13, 35) ); } if (falseIsAbstract) { builder.Add( // (14,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(14, 35) ); } compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation).Verify(builder.ToArrayAndFree()); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("*")] [InlineData("/")] [InlineData("%")] [InlineData("&")] [InlineData("|")] [InlineData("^")] [InlineData("<<")] [InlineData(">>")] public void ConsumeAbstractCompoundBinaryOperator_04(string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + op + @" (T x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1<T> { x " + op + @"= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // x *= y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + "= y").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator* (T x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 31) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } "; var source2 = @" class Test { static void M02<T>((int, T) x) where T : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator == (T x, T y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "==").WithLocation(12, 35), // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator != (T x, T y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "!=").WithLocation(13, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_06([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1 { _ = x " + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x - y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " y").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator- (I1 x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 32) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_06(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" } "; var source2 = @" class Test { static void M02<T>(T x, T y) where T : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); if (success) { compilation2.VerifyDiagnostics(); } else { compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x && y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + op + " y").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); } var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); if (binaryIsAbstract) { builder.Add( // (12,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator& (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 32) ); } if (trueIsAbstract) { builder.Add( // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } if (falseIsAbstract) { builder.Add( // (14,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(14, 35) ); } compilation3.VerifyDiagnostics(builder.ToArrayAndFree()); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("*")] [InlineData("/")] [InlineData("%")] [InlineData("&")] [InlineData("|")] [InlineData("^")] [InlineData("<<")] [InlineData(">>")] public void ConsumeAbstractCompoundBinaryOperator_06(string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + op + @" (T x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1<T> { x " + op + @"= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x <<= y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + "= y").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,31): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator<< (T x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 31) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } "; var source2 = @" class Test { static void M02<T>((int, T) x) where T : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator == (T x, T y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(12, 35), // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator != (T x, T y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { _ = P01; _ = P04; } void M03() { _ = this.P01; _ = this.P04; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { _ = I1.P01; _ = x.P01; _ = I1.P04; _ = x.P04; } static void MT2<T>() where T : I1 { _ = T.P03; _ = T.P04; _ = T.P00; _ = T.P05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01.ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = P01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 13), // (14,13): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = this.P01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 13), // (15,13): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = this.P04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 13), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = I1.P01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 13), // (28,13): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = x.P01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 13), // (30,13): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = x.P04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 13), // (35,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 13), // (36,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 13), // (37,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 13), // (38,15): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = T.P05; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 15), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01.ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticPropertySet_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { P01 = 1; P04 = 1; } void M03() { this.P01 = 1; this.P04 = 1; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { I1.P01 = 1; x.P01 = 1; I1.P04 = 1; x.P04 = 1; } static void MT2<T>() where T : I1 { T.P03 = 1; T.P04 = 1; T.P00 = 1; T.P05 = 1; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 = 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 = 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 = 1; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 = 1").WithLocation(40, 71), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { P01 += 1; P04 += 1; } void M03() { this.P01 += 1; this.P04 += 1; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { I1.P01 += 1; x.P01 += 1; I1.P04 += 1; x.P04 += 1; } static void MT2<T>() where T : I1 { T.P03 += 1; T.P04 += 1; T.P00 += 1; T.P05 += 1; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 += 1; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 += 1").WithLocation(40, 71), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticProperty_02() { var source1 = @" interface I1 { abstract static int P01 { get; set; } static void M02() { _ = nameof(P01); _ = nameof(P04); } void M03() { _ = nameof(this.P01); _ = nameof(this.P04); } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { _ = nameof(I1.P01); _ = nameof(x.P01); _ = nameof(I1.P04); _ = nameof(x.P04); } static void MT2<T>() where T : I1 { _ = nameof(T.P03); _ = nameof(T.P04); _ = nameof(T.P00); _ = nameof(T.P05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (14,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 20), // (15,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 20), // (28,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 20), // (30,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 20), // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = nameof(T.P05); Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""int I1.P01.get"" IL_000c: pop IL_000d: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: constrained. ""T"" IL_0006: call ""int I1.P01.get"" IL_000b: pop IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Right; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertySet_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 15 (0xf) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""void I1.P01.set"" IL_000d: nop IL_000e: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: constrained. ""T"" IL_0007: call ""void I1.P01.set"" IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertyCompound_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { T.P01 += 1; } static string M03<T, U>() where T : U where U : I1 { return nameof(T.P01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""int I1.P01.get"" IL_000c: ldc.i4.1 IL_000d: add IL_000e: constrained. ""T"" IL_0014: call ""void I1.P01.set"" IL_0019: nop IL_001a: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""P01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: constrained. ""T"" IL_0006: call ""int I1.P01.get"" IL_000b: ldc.i4.1 IL_000c: add IL_000d: constrained. ""T"" IL_0013: call ""void I1.P01.set"" IL_0018: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""P01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertyGet_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = T.P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertySet_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 = 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9), // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = T.P01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = T.P01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 13), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticPropertySet_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 = 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 = 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticEventAdd_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used interface I1 { abstract static event System.Action P01; static void M02() { P01 += null; P04 += null; } void M03() { this.P01 += null; this.P04 += null; } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { I1.P01 += null; x.P01 += null; I1.P04 += null; x.P04 += null; } static void MT2<T>() where T : I1 { T.P03 += null; T.P04 += null; T.P00 += null; T.P05 += null; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += null); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01 += null").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (14,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // this.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "this.P01 += null").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01 += null").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (28,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x.P01 += null").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += null); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 += null").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticEventRemove_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used interface I1 { abstract static event System.Action P01; static void M02() { P01 -= null; P04 -= null; } void M03() { this.P01 -= null; this.P04 -= null; } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { I1.P01 -= null; x.P01 -= null; I1.P04 -= null; x.P04 -= null; } static void MT2<T>() where T : I1 { T.P03 -= null; T.P04 -= null; T.P00 -= null; T.P05 -= null; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 -= null); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01 -= null").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (14,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // this.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "this.P01 -= null").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01 -= null").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (28,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x.P01 -= null").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 -= null); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 -= null").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticEvent_02() { var source1 = @" interface I1 { abstract static event System.Action P01; static void M02() { _ = nameof(P01); _ = nameof(P04); } void M03() { _ = nameof(this.P01); _ = nameof(this.P04); } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { _ = nameof(I1.P01); _ = nameof(x.P01); _ = nameof(I1.P04); _ = nameof(x.P04); } static void MT2<T>() where T : I1 { _ = nameof(T.P03); _ = nameof(T.P04); _ = nameof(T.P00); _ = nameof(T.P05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (14,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 20), // (15,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 20), // (28,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 20), // (30,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 20), // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = nameof(T.P05); Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticEvent_03() { var source1 = @" public interface I1 { abstract static event System.Action E01; } class Test { static void M02<T, U>() where T : U where U : I1 { T.E01 += null; T.E01 -= null; } static string M03<T, U>() where T : U where U : I1 { return nameof(T.E01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 28 (0x1c) .maxstack 1 IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: call ""void I1.E01.add"" IL_000d: nop IL_000e: ldnull IL_000f: constrained. ""T"" IL_0015: call ""void I1.E01.remove"" IL_001a: nop IL_001b: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""E01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 25 (0x19) .maxstack 1 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: call ""void I1.E01.add"" IL_000c: ldnull IL_000d: constrained. ""T"" IL_0013: call ""void I1.E01.remove"" IL_0018: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""E01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.E01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IEventReferenceOperation: event System.Action I1.E01 (Static) (OperationKind.EventReference, Type: System.Action) (Syntax: 'T.E01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "E01").Single().ToTestDisplayString()); Assert.Equal("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "E01").Single().ToTestDisplayString()); Assert.Contains("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("event System.Action I1.E01", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "E01").Single().ToTestDisplayString()); Assert.Equal("event System.Action I1.E01", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "E01").Single().ToTestDisplayString()); Assert.Contains("event System.Action I1.E01", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("event System.Action I1.E01", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("E01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticEventAdd_04() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01 += null").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "P01").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventRemove_04() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 -= null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 -= null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01 -= null").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "P01").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventAdd_06() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventRemove_06() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 -= null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 -= null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 -= null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticIndexedProperty_03() { var ilSource = @" .class interface public auto ansi abstract I1 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) // Methods .method public hidebysig specialname newslot abstract virtual static int32 get_Item ( int32 x ) cil managed { } // end of method I1::get_Item .method public hidebysig specialname newslot abstract virtual static void set_Item ( int32 x, int32 'value' ) cil managed { } // end of method I1::set_Item // Properties .property int32 Item( int32 x ) { .get int32 I1::get_Item(int32) .set void I1::set_Item(int32, int32) } } // end of class I1 "; var source1 = @" class Test { static void M02<T>() where T : I1 { T.Item[0] += 1; } static string M03<T>() where T : I1 { return nameof(T.Item); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.Item[0] += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(6, 9), // (11,23): error CS0119: 'T' is a type parameter, which is not valid in the given context // return nameof(T.Item); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(11, 23) ); var source2 = @" class Test { static void M02<T>() where T : I1 { T[0] += 1; } static void M03<T>() where T : I1 { T.set_Item(0, T.get_Item(0) + 1); } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (6,9): error CS0119: 'T' is a type, which is not valid in the given context // T[0] += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type").WithLocation(6, 9), // (11,11): error CS0571: 'I1.this[int].set': cannot explicitly call operator or accessor // T.set_Item(0, T.get_Item(0) + 1); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Item").WithArguments("I1.this[int].set").WithLocation(11, 11), // (11,25): error CS0571: 'I1.this[int].get': cannot explicitly call operator or accessor // T.set_Item(0, T.get_Item(0) + 1); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Item").WithArguments("I1.this[int].get").WithLocation(11, 25) ); } [Fact] public void ConsumeAbstractStaticIndexedProperty_04() { var ilSource = @" .class interface public auto ansi abstract I1 { // Methods .method public hidebysig specialname newslot abstract virtual static int32 get_Item ( int32 x ) cil managed { } // end of method I1::get_Item .method public hidebysig specialname newslot abstract virtual static void set_Item ( int32 x, int32 'value' ) cil managed { } // end of method I1::set_Item // Properties .property int32 Item( int32 x ) { .get int32 I1::get_Item(int32) .set void I1::set_Item(int32, int32) } } // end of class I1 "; var source1 = @" class Test { static void M02<T>() where T : I1 { T.Item[0] += 1; } static string M03<T>() where T : I1 { return nameof(T.Item); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,11): error CS1545: Property, indexer, or event 'I1.Item[int]' is not supported by the language; try directly calling accessor methods 'I1.get_Item(int)' or 'I1.set_Item(int, int)' // T.Item[0] += 1; Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Item").WithArguments("I1.Item[int]", "I1.get_Item(int)", "I1.set_Item(int, int)").WithLocation(6, 11), // (11,25): error CS1545: Property, indexer, or event 'I1.Item[int]' is not supported by the language; try directly calling accessor methods 'I1.get_Item(int)' or 'I1.set_Item(int, int)' // return nameof(T.Item); Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Item").WithArguments("I1.Item[int]", "I1.get_Item(int)", "I1.set_Item(int, int)").WithLocation(11, 25) ); var source2 = @" class Test { static void M02<T>() where T : I1 { T.set_Item(0, T.get_Item(0) + 1); } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation2, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T>()", @" { // Code size 29 (0x1d) .maxstack 3 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: ldc.i4.0 IL_0003: constrained. ""T"" IL_0009: call ""int I1.get_Item(int)"" IL_000e: ldc.i4.1 IL_000f: add IL_0010: constrained. ""T"" IL_0016: call ""void I1.set_Item(int, int)"" IL_001b: nop IL_001c: ret } "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = (System.Action)M01; _ = (System.Action)M04; } void M03() { _ = (System.Action)this.M01; _ = (System.Action)this.M04; } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = (System.Action)I1.M01; _ = (System.Action)x.M01; _ = (System.Action)I1.M04; _ = (System.Action)x.M04; } static void MT2<T>() where T : I1 { _ = (System.Action)T.M03; _ = (System.Action)T.M04; _ = (System.Action)T.M00; _ = (System.Action)T.M05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.Action)T.M01).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (System.Action)M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(System.Action)M01").WithLocation(8, 13), // (14,28): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)this.M01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 28), // (15,28): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)this.M04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 28), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (System.Action)I1.M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(System.Action)I1.M01").WithLocation(27, 13), // (28,28): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)x.M01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 28), // (30,28): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)x.M04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 28), // (35,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 28), // (36,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 28), // (37,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 28), // (38,30): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = (System.Action)T.M05; Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 30), // (40,87): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.Action)T.M01).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01").WithLocation(40, 87) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_03() { var source1 = @" public interface I1 { abstract static void M01(); } class Test { static System.Action M02<T, U>() where T : U where U : I1 { return T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 24 (0x18) .maxstack 2 .locals init (System.Action V_0) IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: ldftn ""void I1.M01()"" IL_000e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0012: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = (System.Action)T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "(System.Action)T.M01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = (System.Action)T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,28): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 28) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,28): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 28), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = new System.Action(M01); _ = new System.Action(M04); } void M03() { _ = new System.Action(this.M01); _ = new System.Action(this.M04); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = new System.Action(I1.M01); _ = new System.Action(x.M01); _ = new System.Action(I1.M04); _ = new System.Action(x.M04); } static void MT2<T>() where T : I1 { _ = new System.Action(T.M03); _ = new System.Action(T.M04); _ = new System.Action(T.M00); _ = new System.Action(T.M05); _ = (System.Linq.Expressions.Expression<System.Action>)(() => new System.Action(T.M01).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,31): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = new System.Action(M01); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "M01").WithLocation(8, 31), // (14,31): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(this.M01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 31), // (15,31): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(this.M04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 31), // (27,31): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = new System.Action(I1.M01); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.M01").WithLocation(27, 31), // (28,31): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(x.M01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 31), // (30,31): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(x.M04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 31), // (35,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 31), // (36,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 31), // (37,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 31), // (38,33): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = new System.Action(T.M05); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 33), // (40,89): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => new System.Action(T.M01).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01").WithLocation(40, 89) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_03() { var source1 = @" public interface I1 { abstract static void M01(); } class Test { static System.Action M02<T, U>() where T : U where U : I1 { return new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 24 (0x18) .maxstack 2 .locals init (System.Action V_0) IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: ldftn ""void I1.M01()"" IL_000e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0012: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.M01").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_01() { var source1 = @" unsafe interface I1 { abstract static void M01(); static void M02() { _ = (delegate*<void>)&M01; _ = (delegate*<void>)&M04; } void M03() { _ = (delegate*<void>)&this.M01; _ = (delegate*<void>)&this.M04; } static void M04() {} protected abstract static void M05(); } unsafe class Test { static void MT1(I1 x) { _ = (delegate*<void>)&I1.M01; _ = (delegate*<void>)&x.M01; _ = (delegate*<void>)&I1.M04; _ = (delegate*<void>)&x.M04; } static void MT2<T>() where T : I1 { _ = (delegate*<void>)&T.M03; _ = (delegate*<void>)&T.M04; _ = (delegate*<void>)&T.M00; _ = (delegate*<void>)&T.M05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (delegate*<void>)&M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(delegate*<void>)&M01").WithLocation(8, 13), // (14,13): error CS8757: No overload for 'M01' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&this.M01; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&this.M01").WithArguments("M01", "delegate*<void>").WithLocation(14, 13), // (15,13): error CS8757: No overload for 'M04' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&this.M04; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&this.M04").WithArguments("M04", "delegate*<void>").WithLocation(15, 13), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (delegate*<void>)&I1.M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(delegate*<void>)&I1.M01").WithLocation(27, 13), // (28,13): error CS8757: No overload for 'M01' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&x.M01; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&x.M01").WithArguments("M01", "delegate*<void>").WithLocation(28, 13), // (30,13): error CS8757: No overload for 'M04' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&x.M04; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&x.M04").WithArguments("M04", "delegate*<void>").WithLocation(30, 13), // (35,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 31), // (36,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 31), // (37,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 31), // (38,33): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = (delegate*<void>)&T.M05; Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 33), // (40,88): error CS1944: An expression tree may not contain an unsafe pointer operation // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "(delegate*<void>)&T.M01").WithLocation(40, 88), // (40,106): error CS8810: '&' on method groups cannot be used in expression trees // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); Diagnostic(ErrorCode.ERR_AddressOfMethodGroupInExpressionTree, "T.M01").WithLocation(40, 106) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_03() { var source1 = @" public interface I1 { abstract static void M01(); } unsafe class Test { static delegate*<void> M02<T, U>() where T : U where U : I1 { return &T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 18 (0x12) .maxstack 1 .locals init (delegate*<void> V_0) IL_0000: nop IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: constrained. ""T"" IL_0006: ldftn ""void I1.M01()"" IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionFunctionPointer_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" unsafe class Test { static void M02<T>() where T : I1 { _ = (delegate*<void>)&T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "(delegate*<void>)&T.M01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" unsafe class Test { static void M02<T>() where T : I1 { _ = (delegate*<void>)&T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public void M01() {} } " + typeKeyword + @" C3 : I1 { static void M01() {} } " + typeKeyword + @" C4 : I1 { void I1.M01() {} } " + typeKeyword + @" C5 : I1 { public static int M01() => throw null; } " + typeKeyword + @" C6 : I1 { static int I1.M01() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01()' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01()").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01()'. 'C2.M01()' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01()", "C2.M01()").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01()'. 'C3.M01()' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01()", "C3.M01()").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01()' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01()").WithLocation(24, 10), // (26,13): error CS0539: 'C4.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01()").WithLocation(26, 13), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01()'. 'C5.M01()' cannot implement 'I1.M01()' because it does not have the matching return type of 'void'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01()", "C5.M01()", "void").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01()' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01()").WithLocation(36, 10), // (38,19): error CS0539: 'C6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01() => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01()").WithLocation(38, 19) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract void M01(); } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static void M01() {} } " + typeKeyword + @" C3 : I1 { void M01() {} } " + typeKeyword + @" C4 : I1 { static void I1.M01() {} } " + typeKeyword + @" C5 : I1 { public int M01() => throw null; } " + typeKeyword + @" C6 : I1 { int I1.M01() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01()' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01()").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01()'. 'C2.M01()' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01()", "C2.M01()").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01()'. 'C3.M01()' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01()", "C3.M01()").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01()' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01()").WithLocation(24, 10), // (26,20): error CS0539: 'C4.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01()").WithLocation(26, 20), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01()'. 'C5.M01()' cannot implement 'I1.M01()' because it does not have the matching return type of 'void'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01()", "C5.M01()", "void").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01()' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01()").WithLocation(36, 10), // (38,12): error CS0539: 'C6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01() => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01()").WithLocation(38, 12) ); } [Fact] public void ImplementAbstractStaticMethod_03() { var source1 = @" public interface I1 { abstract static void M01(); } interface I2 : I1 {} interface I3 : I1 { public virtual void M01() {} } interface I4 : I1 { static void M01() {} } interface I5 : I1 { void I1.M01() {} } interface I6 : I1 { static void I1.M01() {} } interface I7 : I1 { abstract static void M01(); } interface I8 : I1 { abstract static void I1.M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,25): warning CS0108: 'I3.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // public virtual void M01() {} Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01()", "I1.M01()").WithLocation(12, 25), // (17,17): warning CS0108: 'I4.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // static void M01() {} Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01()", "I1.M01()").WithLocation(17, 17), // (22,13): error CS0539: 'I5.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01()").WithLocation(22, 13), // (27,20): error CS0106: The modifier 'static' is not valid for this item // static void I1.M01() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 20), // (27,20): error CS0539: 'I6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01()").WithLocation(27, 20), // (32,26): warning CS0108: 'I7.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // abstract static void M01(); Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01()", "I1.M01()").WithLocation(32, 26), // (37,29): error CS0106: The modifier 'static' is not valid for this item // abstract static void I1.M01(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 29), // (37,29): error CS0539: 'I8.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static void I1.M01(); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01()").WithLocation(37, 29) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); abstract static void M02(); } "; var source2 = typeKeyword + @" Test: I1 { static void I1.M01() {} public static void M02() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,20): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 20) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,20): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 20), // (10,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 26), // (11,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M02(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = typeKeyword + @" Test1: I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01()' cannot implement interface member 'I1.M01()' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01()", "I1.M01()", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01()' cannot implement interface member 'I1.M01()' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01()", "I1.M01()", "Test1").WithLocation(2, 12), // (9,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = typeKeyword + @" Test1: I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,20): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 20) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,20): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 20), // (9,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C : I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, cM01.MethodKind); Assert.Equal("void C.M01()", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C : I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.Equal("void C.I1.M01()", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticMethod_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static void M01(); } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C2.I1.M01()", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticMethod_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig static abstract virtual void M01 () cil managed { } // end of method I1::M01 } // end of class I1 .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static void I1.M01 () cil managed { .override method void I1::M01() .maxstack 8 IL_0000: ret } // end of method C1::I1.M01 .method public hidebysig static void M01 () cil managed { IL_0000: ret } // end of method C1::M01 .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } // end of method C1::.ctor } // end of class C1 .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static void M01 () cil managed { IL_0000: ret } // end of method C2::M01 .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1.I1.M01()", c1M01.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); Assert.Equal("void C2.M01()", c5.FindImplementationForInterfaceMember(m01).ToTestDisplayString()); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticMethod_11() { // Ignore invalid metadata (non-abstract static virtual method). var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig virtual static void M01 () cil managed { IL_0000: ret } // end of method I1::M01 } // end of class I1 "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static void I1.M01() {} } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,19): error CS0539: 'C1.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01()").WithLocation(4, 19) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Fact] public void ImplementAbstractStaticMethod_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void M01 () cil managed { } // end of method I1::M01 } // end of class I1 .class interface public auto ansi abstract I2 implements I1 { // Methods .method private hidebysig static void I1.M01 () cil managed { .override method void I1::M01() IL_0000: ret } // end of method I2::I1.M01 } // end of class I2 "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01()' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01()").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticMethod_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static void M01(); } class C1 { public static void M01() {} } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("void C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1.M01"); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Ordinary, c2M01.MethodKind); Assert.Equal("void C1.M01()", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C1.M01()"" IL_0005: ret } "); } [Fact] public void ImplementAbstractStaticMethod_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void modopt(I1) M01 () cil managed { } // end of method I1::M01 } // end of class I1 "; var source1 = @" class C1 : I1 { public static void M01() {} } class C2 : I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("void modopt(I1) C1.I1.M01()", c1M01.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1.M01"); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("void modopt(I1) C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C1.M01()"" IL_0005: ret } "); } [Fact] public void ImplementAbstractStaticMethod_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static void M01(); abstract static void M02(); } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static void I1.M02() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<MethodSymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>("M01"); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<MethodSymbol>().Single(); var c2M02 = c3.BaseType().GetMember<MethodSymbol>("I1.M02"); Assert.Equal("void C2.I1.M02()", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Fact] public void ImplementAbstractStaticMethod_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static void M01(); } public class C1 : I1 { public static void M01() {} } public class C2 : C1 { new public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C2.M01()"" IL_0005: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<MethodSymbol>("M01"); Assert.Equal("void C2.M01()", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C3.I1.M01()", c3M01.ToTestDisplayString()); Assert.Same(m01, c3M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_17(bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(System.Int32 x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(System.Int32 x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_18(bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(T x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(T x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_19(bool genericFirst) { // Same as ImplementAbstractStaticMethod_17 only implementation is explicit in source. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" static void I1.M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.I1.M01(System.Int32 x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_20(bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implementation is explicit in source. var generic = @" static void I1<T>.M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.I1<T>.M01(T x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_21(bool genericFirst) { // Same as ImplementAbstractStaticMethod_17 only implicit implementation is in an intermediate base. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T> : C1<T>, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C11<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "void C11<T>.I1.M01(System.Int32 x)" : "void C1<T>.M01(System.Int32 x)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_22(bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implicit implementation is in an intermediate base. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T> : C1<T>, I1<T> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C11<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "void C11<T>.I1<T>.M01(T x)" : "void C1<T>.M01(T x)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } private static string UnaryOperatorName(string op) => OperatorFacts.UnaryOperatorNameFromSyntaxKindIfAny(SyntaxFactory.ParseToken(op).Kind()); private static string BinaryOperatorName(string op) => op switch { ">>" => WellKnownMemberNames.RightShiftOperatorName, _ => OperatorFacts.BinaryOperatorNameFromSyntaxKindIfAny(SyntaxFactory.ParseToken(op).Kind()) }; [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = UnaryOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public C2 operator " + op + @"(C2 x) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static C3 operator " + op + @"(C3 x) => throw null; } " + typeKeyword + @" C4 : I1<C4> { C4 I1<C4>.operator " + op + @"(C4 x) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static int operator " + op + @" (C5 x) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static int I1<C6>.operator " + op + @" (C6 x) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static C7 " + opName + @"(C7 x) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static C8 I1<C8>." + opName + @"(C8 x) => throw null; } public interface I2<T> where T : I2<T> { abstract static T " + opName + @"(T x); } " + typeKeyword + @" C9 : I2<C9> { public static C9 operator " + op + @"(C9 x) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static C10 I2<C10>.operator " + op + @"(C10 x) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_BadIncDecRetType or (int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.operator +(C1)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>.operator " + op + "(C1)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.operator +(C2)'. 'C2.operator +(C2)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>.operator " + op + "(C2)", "C2.operator " + op + "(C2)").WithLocation(12, 10), // (14,24): error CS0558: User-defined operator 'C2.operator +(C2)' must be declared static and public // public C2 operator +(C2 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C2.operator " + op + "(C2)").WithLocation(14, 24), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.operator +(C3)'. 'C3.operator +(C3)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>.operator " + op + "(C3)", "C3.operator " + op + "(C3)").WithLocation(18, 10), // (20,24): error CS0558: User-defined operator 'C3.operator +(C3)' must be declared static and public // static C3 operator +(C3 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C3.operator " + op + "(C3)").WithLocation(20, 24), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.operator +(C4)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>.operator " + op + "(C4)").WithLocation(24, 10), // (26,24): error CS8930: Explicit implementation of a user-defined operator 'C4.operator +(C4)' must be declared static // C4 I1<C4>.operator +(C4 x) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("C4.operator " + op + "(C4)").WithLocation(26, 24), // (26,24): error CS0539: 'C4.operator +(C4)' in explicit interface declaration is not found among members of the interface that can be implemented // C4 I1<C4>.operator +(C4 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C4.operator " + op + "(C4)").WithLocation(26, 24), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.operator +(C5)'. 'C5.operator +(C5)' cannot implement 'I1<C5>.operator +(C5)' because it does not have the matching return type of 'C5'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>.operator " + op + "(C5)", "C5.operator " + op + "(C5)", "C5").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.operator +(C6)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>.operator " + op + "(C6)").WithLocation(36, 10), // (38,32): error CS0539: 'C6.operator +(C6)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C6>.operator + (C6 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C6.operator " + op + "(C6)").WithLocation(38, 32), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.operator +(C7)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>.operator " + op + "(C7)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.operator +(C8)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>.operator " + op + "(C8)").WithLocation(48, 10), // (50,22): error CS0539: 'C8.op_UnaryPlus(C8)' in explicit interface declaration is not found among members of the interface that can be implemented // static C8 I1<C8>.op_UnaryPlus(C8 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8)").WithLocation(50, 22), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_UnaryPlus(C9)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_UnaryPlus(C10)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10)").WithLocation(65, 11), // (67,33): error CS0539: 'C10.operator +(C10)' in explicit interface declaration is not found among members of the interface that can be implemented // static C10 I2<C10>.operator +(C10 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C10.operator " + op + "(C10)").WithLocation(67, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = BinaryOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public C2 operator " + op + @"(C2 x, int y) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static C3 operator " + op + @"(C3 x, int y) => throw null; } " + typeKeyword + @" C4 : I1<C4> { C4 I1<C4>.operator " + op + @"(C4 x, int y) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static int operator " + op + @" (C5 x, int y) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static int I1<C6>.operator " + op + @" (C6 x, int y) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static C7 " + opName + @"(C7 x, int y) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static C8 I1<C8>." + opName + @"(C8 x, int y) => throw null; } public interface I2<T> where T : I2<T> { abstract static T " + opName + @"(T x, int y); } " + typeKeyword + @" C9 : I2<C9> { public static C9 operator " + op + @"(C9 x, int y) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static C10 I2<C10>.operator " + op + @"(C10 x, int y) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.operator >>(C1, int)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>.operator " + op + "(C1, int)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.operator >>(C2, int)'. 'C2.operator >>(C2, int)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>.operator " + op + "(C2, int)", "C2.operator " + op + "(C2, int)").WithLocation(12, 10), // (14,24): error CS0558: User-defined operator 'C2.operator >>(C2, int)' must be declared static and public // public C2 operator >>(C2 x, int y) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C2.operator " + op + "(C2, int)").WithLocation(14, 24), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.operator >>(C3, int)'. 'C3.operator >>(C3, int)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>.operator " + op + "(C3, int)", "C3.operator " + op + "(C3, int)").WithLocation(18, 10), // (20,24): error CS0558: User-defined operator 'C3.operator >>(C3, int)' must be declared static and public // static C3 operator >>(C3 x, int y) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C3.operator " + op + "(C3, int)").WithLocation(20, 24), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.operator >>(C4, int)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>.operator " + op + "(C4, int)").WithLocation(24, 10), // (26,24): error CS8930: Explicit implementation of a user-defined operator 'C4.operator >>(C4, int)' must be declared static // C4 I1<C4>.operator >>(C4 x, int y) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("C4.operator " + op + "(C4, int)").WithLocation(26, 24), // (26,24): error CS0539: 'C4.operator >>(C4, int)' in explicit interface declaration is not found among members of the interface that can be implemented // C4 I1<C4>.operator >>(C4 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C4.operator " + op + "(C4, int)").WithLocation(26, 24), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.operator >>(C5, int)'. 'C5.operator >>(C5, int)' cannot implement 'I1<C5>.operator >>(C5, int)' because it does not have the matching return type of 'C5'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>.operator " + op + "(C5, int)", "C5.operator " + op + "(C5, int)", "C5").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.operator >>(C6, int)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>.operator " + op + "(C6, int)").WithLocation(36, 10), // (38,32): error CS0539: 'C6.operator >>(C6, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C6>.operator >> (C6 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C6.operator " + op + "(C6, int)").WithLocation(38, 32), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.operator >>(C7, int)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>.operator " + op + "(C7, int)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.operator >>(C8, int)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>.operator " + op + "(C8, int)").WithLocation(48, 10), // (50,22): error CS0539: 'C8.op_RightShift(C8, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static C8 I1<C8>.op_RightShift(C8 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8, int)").WithLocation(50, 22), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_RightShift(C9, int)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9, int)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_RightShift(C10, int)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10, int)").WithLocation(65, 11), // (67,33): error CS0539: 'C10.operator >>(C10, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static C10 I2<C10>.operator >>(C10 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C10.operator " + op + "(C10, int)").WithLocation(67, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_03([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } interface I2 : I1 {} interface I3 : I1 { I1 operator " + op + @"(I1 x) => default; } interface I4 : I1 { static I1 operator " + op + @"(I1 x) => default; } interface I5 : I1 { I1 I1.operator " + op + @"(I1 x) => default; } interface I6 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } interface I7 : I1 { abstract static I1 operator " + op + @"(I1 x); } public interface I11<T> where T : I11<T> { abstract static T operator " + op + @"(T x); } interface I8<T> : I11<T> where T : I8<T> { T operator " + op + @"(T x) => default; } interface I9<T> : I11<T> where T : I9<T> { static T operator " + op + @"(T x) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static T operator " + op + @"(T x); } interface I12<T> : I11<T> where T : I12<T> { static T I11<T>.operator " + op + @"(T x) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static T I11<T>.operator " + op + @"(T x); } interface I14 : I1 { abstract static I1 I1.operator " + op + @"(I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ErrorCode badSignatureError = op.Length != 2 ? ErrorCode.ERR_BadUnaryOperatorSignature : ErrorCode.ERR_BadIncDecSignature; ErrorCode badAbstractSignatureError = op.Length != 2 ? ErrorCode.ERR_BadAbstractUnaryOperatorSignature : ErrorCode.ERR_BadAbstractIncDecSignature; compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (12,17): error CS0558: User-defined operator 'I3.operator +(I1)' must be declared static and public // I1 operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I3.operator " + op + "(I1)").WithLocation(12, 17), // (12,17): error CS0562: The parameter of a unary operator must be the containing type // I1 operator +(I1 x) => default; Diagnostic(badSignatureError, op).WithLocation(12, 17), // (17,24): error CS0562: The parameter of a unary operator must be the containing type // static I1 operator +(I1 x) => default; Diagnostic(badSignatureError, op).WithLocation(17, 24), // (22,20): error CS8930: Explicit implementation of a user-defined operator 'I5.operator +(I1)' must be declared static // I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("I5.operator " + op + "(I1)").WithLocation(22, 20), // (22,20): error CS0539: 'I5.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I5.operator " + op + "(I1)").WithLocation(22, 20), // (27,27): error CS0539: 'I6.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I6.operator " + op + "(I1)").WithLocation(27, 27), // (32,33): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // abstract static I1 operator +(I1 x); Diagnostic(badAbstractSignatureError, op).WithLocation(32, 33), // (42,16): error CS0558: User-defined operator 'I8<T>.operator +(T)' must be declared static and public // T operator +(T x) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I8<T>.operator " + op + "(T)").WithLocation(42, 16), // (42,16): error CS0562: The parameter of a unary operator must be the containing type // T operator +(T x) => default; Diagnostic(badSignatureError, op).WithLocation(42, 16), // (47,23): error CS0562: The parameter of a unary operator must be the containing type // static T operator +(T x) => default; Diagnostic(badSignatureError, op).WithLocation(47, 23), // (57,30): error CS0539: 'I12<T>.operator +(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static T I11<T>.operator +(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I12<T>.operator " + op + "(T)").WithLocation(57, 30), // (62,39): error CS0106: The modifier 'abstract' is not valid for this item // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(62, 39), // (62,39): error CS0501: 'I13<T>.operator +(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I13<T>.operator " + op + "(T)").WithLocation(62, 39), // (62,39): error CS0539: 'I13<T>.operator +(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I13<T>.operator " + op + "(T)").WithLocation(62, 39), // (67,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(67, 36), // (67,36): error CS0501: 'I14.operator +(I1)' must declare a body because it is not marked abstract, extern, or partial // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I14.operator " + op + "(I1)").WithLocation(67, 36), // (67,36): error CS0539: 'I14.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I14.operator " + op + "(I1)").WithLocation(67, 36) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_03([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } interface I2 : I1 {} interface I3 : I1 { I1 operator " + op + @"(I1 x, int y) => default; } interface I4 : I1 { static I1 operator " + op + @"(I1 x, int y) => default; } interface I5 : I1 { I1 I1.operator " + op + @"(I1 x, int y) => default; } interface I6 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } interface I7 : I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public interface I11<T> where T : I11<T> { abstract static T operator " + op + @"(T x, int y); } interface I8<T> : I11<T> where T : I8<T> { T operator " + op + @"(T x, int y) => default; } interface I9<T> : I11<T> where T : I9<T> { static T operator " + op + @"(T x, int y) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static T operator " + op + @"(T x, int y); } interface I12<T> : I11<T> where T : I12<T> { static T I11<T>.operator " + op + @"(T x, int y) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static T I11<T>.operator " + op + @"(T x, int y); } interface I14 : I1 { abstract static I1 I1.operator " + op + @"(I1 x, int y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); bool isShift = op == "<<" || op == ">>"; ErrorCode badSignatureError = isShift ? ErrorCode.ERR_BadShiftOperatorSignature : ErrorCode.ERR_BadBinaryOperatorSignature; ErrorCode badAbstractSignatureError = isShift ? ErrorCode.ERR_BadAbstractShiftOperatorSignature : ErrorCode.ERR_BadAbstractBinaryOperatorSignature; var expected = new[] { // (12,17): error CS0563: One of the parameters of a binary operator must be the containing type // I1 operator |(I1 x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(12, 17), // (17,24): error CS0563: One of the parameters of a binary operator must be the containing type // static I1 operator |(I1 x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(17, 24), // (22,20): error CS8930: Explicit implementation of a user-defined operator 'I5.operator |(I1, int)' must be declared static // I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("I5.operator " + op + "(I1, int)").WithLocation(22, 20), // (22,20): error CS0539: 'I5.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I5.operator " + op + "(I1, int)").WithLocation(22, 20), // (27,27): error CS0539: 'I6.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I6.operator " + op + "(I1, int)").WithLocation(27, 27), // (32,33): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // abstract static I1 operator |(I1 x, int y); Diagnostic(badAbstractSignatureError, op).WithLocation(32, 33), // (42,16): error CS0563: One of the parameters of a binary operator must be the containing type // T operator |(T x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(42, 16), // (47,23): error CS0563: One of the parameters of a binary operator must be the containing type // static T operator |(T x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(47, 23), // (57,30): error CS0539: 'I12<T>.operator |(T, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static T I11<T>.operator |(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I12<T>.operator " + op + "(T, int)").WithLocation(57, 30), // (62,39): error CS0106: The modifier 'abstract' is not valid for this item // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(62, 39), // (62,39): error CS0501: 'I13<T>.operator |(T, int)' must declare a body because it is not marked abstract, extern, or partial // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I13<T>.operator " + op + "(T, int)").WithLocation(62, 39), // (62,39): error CS0539: 'I13<T>.operator |(T, int)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I13<T>.operator " + op + "(T, int)").WithLocation(62, 39), // (67,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(67, 36), // (67,36): error CS0501: 'I14.operator |(I1, int)' must declare a body because it is not marked abstract, extern, or partial // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I14.operator " + op + "(I1, int)").WithLocation(67, 36), // (67,36): error CS0539: 'I14.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I14.operator " + op + "(I1, int)").WithLocation(67, 36) }; if (op is "==" or "!=") { expected = expected.Concat( new[] { // (12,17): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // I1 operator ==(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(12, 17), // (17,24): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static I1 operator ==(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(17, 24), // (42,16): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // T operator ==(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(42, 16), // (47,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static T operator ==(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(47, 23), } ).ToArray(); } else { expected = expected.Concat( new[] { // (12,17): error CS0558: User-defined operator 'I3.operator |(I1, int)' must be declared static and public // I1 operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I3.operator " + op + "(I1, int)").WithLocation(12, 17), // (42,16): error CS0558: User-defined operator 'I8<T>.operator |(T, int)' must be declared static and public // T operator |(T x, int y) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I8<T>.operator " + op + "(T, int)").WithLocation(42, 16) } ).ToArray(); } compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify(expected); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_04([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public interface I2<T> where T : I2<T> { abstract static T operator " + op + @"(T x); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static Test2 operator " + op + @"(Test2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15), // (14,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator +(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(14, 33), // (19,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator +(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(19, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public interface I2<T> where T : I2<T> { abstract static T operator " + op + @"(T x, int y); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static Test2 operator " + op + @"(Test2 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15), // (14,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator +(I1 x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(14, 33), // (19,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator +(T x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(19, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_05([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static Test1 operator " + op + @"(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (2,12): error CS8929: 'Test1.operator +(Test1)' cannot implement interface member 'I1<Test1>.operator +(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1)", "I1<Test1>.operator " + op + "(Test1)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (2,12): error CS8929: 'Test1.operator +(Test1)' cannot implement interface member 'I1<Test1>.operator +(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1)", "I1<Test1>.operator " + op + "(Test1)", "Test1").WithLocation(2, 12), // (9,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator +(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_05([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static Test1 operator " + op + @"(Test1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (2,12): error CS8929: 'Test1.operator >>(Test1, int)' cannot implement interface member 'I1<Test1>.operator >>(Test1, int)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1, int)", "I1<Test1>.operator " + op + "(Test1, int)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (2,12): error CS8929: 'Test1.operator >>(Test1, int)' cannot implement interface member 'I1<Test1>.operator >>(Test1, int)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1, int)", "I1<Test1>.operator " + op + "(Test1, int)", "Test1").WithLocation(2, 12), // (9,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator >>(T x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_06([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator +(I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_06([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator +(I1 x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_07([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } " + typeKeyword + @" C : I1<C> { public static C operator " + op + @"(C x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("C C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_07([CombinatorialValues("true", "false")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static bool operator " + op + @"(T x); } partial " + typeKeyword + @" C : I1<C> { public static bool operator " + op + @"(C x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1<T> where T : I1<T> { abstract static bool operator " + matchingOp + @"(T x); } partial " + typeKeyword + @" C { public static bool operator " + matchingOp + @"(C x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("System.Boolean C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_07([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() partial " + typeKeyword + @" C : I1<C> { public static C operator " + op + @"(C x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + matchingOp + @"(T x, int y); } partial " + typeKeyword + @" C { public static C operator " + matchingOp + @"(C x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.Equal(matchingOp is null ? 1 : 2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("C C." + opName + "(C x, System.Int32 y)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_08([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } " + typeKeyword + @" C : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.Equal("default", node.ToString()); Assert.Equal("I1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("I1 C.I1." + opName + "(I1 x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("I1 C.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_08([CombinatorialValues("true", "false")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1 { abstract static bool operator " + op + @"(I1 x); } partial " + typeKeyword + @" C : I1 { static bool I1.operator " + op + @"(I1 x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1 { abstract static bool operator " + matchingOp + @"(I1 x); } partial " + typeKeyword + @" C { static bool I1.operator " + matchingOp + @"(I1 x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("default", node.ToString()); Assert.Equal("System.Boolean", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("System.Boolean C.I1." + opName + "(I1 x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers(opName).OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("System.Boolean C.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_08([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } partial " + typeKeyword + @" C : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator " + matchingOp + @"(I1 x, int y); } partial " + typeKeyword + @" C { static I1 I1.operator " + matchingOp + @"(I1 x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("default", node.ToString()); Assert.Equal("I1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("I1 C.I1." + opName + "(I1 x, System.Int32 y)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers(opName).OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(matchingOp is null ? 1 : 2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("I1 C.I1." + opName + "(I1 x, System.Int32 y)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_09([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public class C2 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_09([CombinatorialValues("true", "false")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public partial interface I1 { abstract static bool operator " + op + @"(I1 x); } public partial class C2 : I1 { static bool I1.operator " + op + @"(I1 x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1 { abstract static bool operator " + matchingOp + @"(I1 x); } public partial class C2 { static bool I1.operator " + matchingOp + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Boolean C2.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_09([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public partial interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public partial class C2 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator " + matchingOp + @"(I1 x, int y); } public partial class C2 { static I1 I1.operator " + matchingOp + @"(I1 x, int y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2.I1." + opName + "(I1 x, System.Int32 y)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_10([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x) cil managed { .override method class I1 I1::" + opName + @"(class I1) IL_0000: ldnull IL_0001: ret } .method public hidebysig static specialname class I1 " + opName + @" (class I1 x) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static specialname class I1 " + opName + @" (class I1 x) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Equal(MethodKind.UserDefinedOperator, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C1.I1." + opName + "(I1 x)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2." + opName + "(I1 x)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_10([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x, int32 y) cil managed { .override method class I1 I1::" + opName + @"(class I1, int32) IL_0000: ldnull IL_0001: ret } .method public hidebysig static specialname class I1 " + opName + @" (class I1 x, int32 y) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static specialname class I1 " + opName + @" (class I1 x, int32 y) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Equal(MethodKind.UserDefinedOperator, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C1.I1." + opName + "(I1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2." + opName + "(I1 x, System.Int32 y)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_11([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname virtual static class I1 " + opName + @" ( class I1 x ) cil managed { IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,27): error CS0539: 'C1.operator ~(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator ~(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C1.operator " + op + "(I1)").WithLocation(4, 27) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("I1 I1." + opName + "(I1 x)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_11([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,27): error CS0539: 'C1.operator <(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator <(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C1.operator " + op + "(I1, int)").WithLocation(4, 27) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("I1 I1." + opName + "(I1 x, System.Int32 y)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_12([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x ) cil managed { } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x) cil managed { .override method class I1 I1::" + opName + @"(class I1) IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.operator ~(I1)' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.operator " + op + "(I1)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_12([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x, int32 y) cil managed { .override method class I1 I1::" + opName + @"(class I1, int32) IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.operator /(I1, int)' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.operator " + op + "(I1, int)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_13([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public class C2 : C1, I1<C2> { } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); } public partial class C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var i1 = c2.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.False(c2M01.HasSpecialName); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.False(c1M01.HasRuntimeSpecialName); Assert.True(c1M01.HasSpecialName); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.True(c2M01.HasSpecialName); Assert.Equal("C2 C1." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1<C2>." + opName + "(C2, C1)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C2 C1." + opName + @"(C2, C1)"" IL_0007: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_14([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static !T modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static C1 operator " + op + @"(C1 x) => default; } class C2 : I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("C1 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("C1 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("C1 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("C2 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""C1 C1." + opName + @"(C1)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_14([CombinatorialValues("true", "false")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static bool modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static bool operator " + op + @"(C1 x) => default; public static bool operator " + (op == "true" ? "false" : "true") + @"(C1 x) => default; } class C2 : I1<C2> { static bool I1<C2>.operator " + op + @"(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("System.Boolean modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("System.Boolean C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("System.Boolean C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("System.Boolean modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""bool C1." + opName + @"(C1)"" IL_0006: ret } "); } private static string MatchingBinaryOperator(string op) { return op switch { "<" => ">", ">" => "<", "<=" => ">=", ">=" => "<=", "==" => "!=", "!=" => "==", _ => null }; } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_14([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static !T modopt(I1`1) " + opName + @" ( !T x, int32 y ) cil managed { } } "; string matchingOp = MatchingBinaryOperator(op); string additionalMethods = ""; if (matchingOp is object) { additionalMethods = @" public static C1 operator " + matchingOp + @"(C1 x, int y) => default; "; } var source1 = @" #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() class C1 : I1<C1> { public static C1 operator " + op + @"(C1 x, int y) => default; " + additionalMethods + @" } class C2 : I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x, int y) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("C1 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("C1 C1." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("C1 C1." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("C2 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x, System.Int32 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1, int)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C1 C1." + opName + @"(C1, int)"" IL_0007: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_15([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public partial class C2 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M02 = c3.BaseType().GetMembers("I1." + opName).OfType<MethodSymbol>().Single(); Assert.Equal("I1 C2.I1." + opName + "(I1 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Fact] public void ImplementAbstractStaticUnaryTrueFalseOperator_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static bool operator true(I1 x); abstract static bool operator false(I1 x); } public partial class C2 : I1 { static bool I1.operator true(I1 x) => default; static bool I1.operator false(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("op_True").OfType<MethodSymbol>().Single(); var m02 = c3.Interfaces().Single().GetMembers("op_False").OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMembers("I1.op_True").OfType<MethodSymbol>().Single(); Assert.Equal("System.Boolean C2.I1.op_True(I1 x)", c2M01.ToTestDisplayString()); Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); var c2M02 = c3.BaseType().GetMembers("I1.op_False").OfType<MethodSymbol>().Single(); Assert.Equal("System.Boolean C2.I1.op_False(I1 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_15([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); abstract static T operator " + op + @"(T x, C2 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public partial class C2 : C1, I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x, C2 y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); abstract static T operator " + matchingOp + @"(T x, C2 y); } public partial class C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } public partial class C2 { static C2 I1<C2>.operator " + matchingOp + @"(C2 x, C2 y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().First(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C2 C1." + opName + "(C2 x, C1 y)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().ElementAt(1); var c2M02 = c3.BaseType().GetMembers("I1<C2>." + opName).OfType<MethodSymbol>().First(); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C2 y)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_16([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A new implicit implementation is properly considered. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 : I1<C2> { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public partial class C2 : C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); } public partial class C1 : I1<C2> { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } public partial class C2 : C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1<C2>." + opName + "(C2, C1)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C2 C2." + opName + @"(C2, C1)"" IL_0007: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C2 C2." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C2 C3.I1<C2>." + opName + "(C2 x, C1 y)", c3M01.ToTestDisplayString()); Assert.Equal(m01, c3M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_18([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, U y) => default; "; var nonGeneric = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, int y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> { public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, U y) => default; public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>." + opName + "(C1<T, U> x, U y)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>." + opName + "(C1<T, U> x, U y)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_20([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // Same as ImplementAbstractStaticBinaryOperator_18 only implementation is explicit in source. var generic = @" static C1<T, U> I1<C1<T, U>, U>.operator " + op + @"(C1<T, U> x, U y) => default; "; var nonGeneric = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, int y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> : I1<C1<T, U>, U> { public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, int y) => default; static C1<T, U> I1<C1<T, U>, U>.operator " + matchingOp + @"(C1<T, U> x, U y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>.I1<C1<T, U>, U>." + opName + "(C1<T, U> x, U y)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_22([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implicit implementation is in an intermediate base. var generic = @" public static C11<T, U> operator " + op + @"(C11<T, U> x, C1<T, U> y) => default; "; var nonGeneric = @" public static C11<T, U> operator " + op + @"(C11<T, int> x, C1<T, U> y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T, U> : C1<T, U>, I1<C11<T, U>, C1<T, U>> { } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> { public static C11<T, U> operator " + matchingOp + @"(C11<T, U> x, C1<T, U> y) => default; public static C11<T, U> operator " + matchingOp + @"(C11<T, int> x, C1<T, U> y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C11<int, int>, I1<C11<int, int>, C1<int, int>> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "C11<T, U> C11<T, U>.I1<C11<T, U>, C1<T, U>>." + opName + "(C11<T, U> x, C1<T, U> y)" : "C11<T, U> C1<T, U>." + opName + "(C11<T, U> x, C1<T, U> y)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } class C1 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } class C2 : I1 { private static I1 I1.operator " + op + @"(I1 x) => default; } class C3 : I1 { protected static I1 I1.operator " + op + @"(I1 x) => default; } class C4 : I1 { internal static I1 I1.operator " + op + @"(I1 x) => default; } class C5 : I1 { protected internal static I1 I1.operator " + op + @"(I1 x) => default; } class C6 : I1 { private protected static I1 I1.operator " + op + @"(I1 x) => default; } class C7 : I1 { public static I1 I1.operator " + op + @"(I1 x) => default; } class C8 : I1 { static partial I1 I1.operator " + op + @"(I1 x) => default; } class C9 : I1 { async static I1 I1.operator " + op + @"(I1 x) => default; } class C10 : I1 { unsafe static I1 I1.operator " + op + @"(I1 x) => default; } class C11 : I1 { static readonly I1 I1.operator " + op + @"(I1 x) => default; } class C12 : I1 { extern static I1 I1.operator " + op + @"(I1 x); } class C13 : I1 { abstract static I1 I1.operator " + op + @"(I1 x) => default; } class C14 : I1 { virtual static I1 I1.operator " + op + @"(I1 x) => default; } class C15 : I1 { sealed static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.WRN_ExternMethodNoImplementation or (int)ErrorCode.ERR_OpTFRetType or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (16,35): error CS0106: The modifier 'private' is not valid for this item // private static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private").WithLocation(16, 35), // (22,37): error CS0106: The modifier 'protected' is not valid for this item // protected static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected").WithLocation(22, 37), // (28,36): error CS0106: The modifier 'internal' is not valid for this item // internal static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("internal").WithLocation(28, 36), // (34,46): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected internal").WithLocation(34, 46), // (40,45): error CS0106: The modifier 'private protected' is not valid for this item // private protected static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private protected").WithLocation(40, 45), // (46,34): error CS0106: The modifier 'public' is not valid for this item // public static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("public").WithLocation(46, 34), // (52,12): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // static partial I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(52, 12), // (58,33): error CS0106: The modifier 'async' is not valid for this item // async static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("async").WithLocation(58, 33), // (70,36): error CS0106: The modifier 'readonly' is not valid for this item // static readonly I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("readonly").WithLocation(70, 36), // (82,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(82, 36), // (88,35): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("virtual").WithLocation(88, 35), // (94,34): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("sealed").WithLocation(94, 34) ); } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } struct C1 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C2 : I1 { private static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C3 : I1 { protected static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C4 : I1 { internal static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C5 : I1 { protected internal static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C6 : I1 { private protected static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C7 : I1 { public static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C8 : I1 { static partial I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C9 : I1 { async static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C10 : I1 { unsafe static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C11 : I1 { static readonly I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C12 : I1 { extern static I1 I1.operator " + op + @"(I1 x, int y); } struct C13 : I1 { abstract static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C14 : I1 { virtual static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C15 : I1 { sealed static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.WRN_ExternMethodNoImplementation or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (16,35): error CS0106: The modifier 'private' is not valid for this item // private static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private").WithLocation(16, 35), // (22,37): error CS0106: The modifier 'protected' is not valid for this item // protected static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected").WithLocation(22, 37), // (28,36): error CS0106: The modifier 'internal' is not valid for this item // internal static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("internal").WithLocation(28, 36), // (34,46): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected internal").WithLocation(34, 46), // (40,45): error CS0106: The modifier 'private protected' is not valid for this item // private protected static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private protected").WithLocation(40, 45), // (46,34): error CS0106: The modifier 'public' is not valid for this item // public static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("public").WithLocation(46, 34), // (52,12): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // static partial I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(52, 12), // (58,33): error CS0106: The modifier 'async' is not valid for this item // async static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("async").WithLocation(58, 33), // (70,36): error CS0106: The modifier 'readonly' is not valid for this item // static readonly I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("readonly").WithLocation(70, 36), // (82,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(82, 36), // (88,35): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("virtual").WithLocation(88, 35), // (94,34): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("sealed").WithLocation(94, 34) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1<T> where T : struct { abstract static I1<T> operator " + op + @"(I1<T> x); } class C1 { static I1<int> I1<int>.operator " + op + @"(I1<int> x) => default; } class C2 : I1<C2> { static I1<C2> I1<C2>.operator " + op + @"(I1<C2> x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OpTFRetType or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (9,20): error CS0540: 'C1.I1<int>.operator -(I1<int>)': containing type does not implement interface 'I1<int>' // static I1<int> I1<int>.operator -(I1<int> x) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<int>").WithArguments("C1.I1<int>.operator " + op + "(I1<int>)", "I1<int>").WithLocation(9, 20), // (12,7): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // class C2 : I1<C2> Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 7), // (14,19): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 19), // (14,35): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, op).WithArguments("I1<T>", "T", "C2").WithLocation(14, 35), // (14,44): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("I1<T>", "T", "C2").WithLocation(14, 44 + op.Length - 1) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1<T> where T : class { abstract static I1<T> operator " + op + @"(I1<T> x, int y); } struct C1 { static I1<string> I1<string>.operator " + op + @"(I1<string> x, int y) => default; } struct C2 : I1<C2> { static I1<C2> I1<C2>.operator " + op + @"(I1<C2> x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (9,23): error CS0540: 'C1.I1<string>.operator %(I1<string>, int)': containing type does not implement interface 'I1<string>' // static I1<string> I1<string>.operator %(I1<string> x, int y) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<string>").WithArguments("C1.I1<string>.operator " + op + "(I1<string>, int)", "I1<string>").WithLocation(9, 23), // (12,8): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // struct C2 : I1<C2> Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 8), // (14,19): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 19), // (14,35): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, op).WithArguments("I1<T>", "T", "C2").WithLocation(14, 35), // (14,44): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "x").WithArguments("I1<T>", "T", "C2").WithLocation(14, 44 + op.Length - 1) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public int M01 { get; set; } } " + typeKeyword + @" C3 : I1 { static int M01 { get; set; } } " + typeKeyword + @" C4 : I1 { int I1.M01 { get; set; } } " + typeKeyword + @" C5 : I1 { public static long M01 { get; set; } } " + typeKeyword + @" C6 : I1 { static long I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,12): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 12), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'int'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,20): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static long I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 20) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract int M01 { get; set; } } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static int M01 { get; set; } } " + typeKeyword + @" C3 : I1 { int M01 { get; set; } } " + typeKeyword + @" C4 : I1 { static int I1.M01 { get; set; } } " + typeKeyword + @" C5 : I1 { public long M01 { get; set; } } " + typeKeyword + @" C6 : I1 { long I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,19): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 19), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'int'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,13): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // long I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 13) ); } [Fact] public void ImplementAbstractStaticProperty_03() { var source1 = @" public interface I1 { abstract static int M01 { get; set; } } interface I2 : I1 {} interface I3 : I1 { public virtual int M01 { get => 0; set{} } } interface I4 : I1 { static int M01 { get; set; } } interface I5 : I1 { int I1.M01 { get => 0; set{} } } interface I6 : I1 { static int I1.M01 { get => 0; set{} } } interface I7 : I1 { abstract static int M01 { get; set; } } interface I8 : I1 { abstract static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,24): warning CS0108: 'I3.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // public virtual int M01 { get => 0; set{} } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01", "I1.M01").WithLocation(12, 24), // (17,16): warning CS0108: 'I4.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // static int M01 { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01", "I1.M01").WithLocation(17, 16), // (22,12): error CS0539: 'I5.M01' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01").WithLocation(22, 12), // (27,19): error CS0106: The modifier 'static' is not valid for this item // static int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 19), // (27,19): error CS0539: 'I6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01").WithLocation(27, 19), // (32,25): warning CS0108: 'I7.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01", "I1.M01").WithLocation(32, 25), // (37,28): error CS0106: The modifier 'static' is not valid for this item // abstract static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 28), // (37,28): error CS0539: 'I8.M01' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01").WithLocation(37, 28) ); foreach (var m01 in compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers()) { Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } abstract static int M02 { get; set; } } "; var source2 = typeKeyword + @" Test: I1 { static int I1.M01 { get; set; } public static int M02 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,19): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 19) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,19): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 19), // (10,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 25), // (11,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int M02 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 25) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } "; var source2 = typeKeyword + @" Test1: I1 { public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.set' cannot implement interface member 'I1.M01.set' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.set", "I1.M01.set", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.get' cannot implement interface member 'I1.M01.get' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.get", "I1.M01.get", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.set' cannot implement interface member 'I1.M01.set' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.set", "I1.M01.set", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.get' cannot implement interface member 'I1.M01.get' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.get", "I1.M01.get", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12), // (9,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(9, 31), // (9,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(9, 36) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } "; var source2 = typeKeyword + @" Test1: I1 { static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,19): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 19) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,19): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 19), // (9,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(9, 31), // (9,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(9, 36) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C : I1 { public static int M01 { get => 0; set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.False(cM01Get.HasRuntimeSpecialName); Assert.True(cM01Get.HasSpecialName); Assert.Equal("System.Int32 C.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.False(cM01Set.HasRuntimeSpecialName); Assert.True(cM01Set.HasSpecialName); Assert.Equal("void C.M01.set", cM01Set.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticReadonlyProperty_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; } } " + typeKeyword + @" C : I1 { public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Null(m01.SetMethod); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C.M01.set", cM01Set.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C : I1 { static int I1.M01 { get => 0; set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.I1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.False(cM01Get.HasRuntimeSpecialName); Assert.True(cM01Get.HasSpecialName); Assert.Equal("System.Int32 C.I1.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.False(cM01Set.HasRuntimeSpecialName); Assert.True(cM01Set.HasSpecialName); Assert.Equal("void C.I1.M01.set", cM01Set.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<PropertySymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var cM01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.I1.M01 { get; set; }", cM01.ToTestDisplayString()); Assert.Same(cM01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(cM01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, cM01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, cM01.SetMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig specialname static int32 I1.get_M01 () cil managed { .override method int32 I1::get_M01() IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static void I1.set_M01 ( int32 'value' ) cil managed { .override method void I1::set_M01(int32) IL_0000: ret } .property instance int32 I1.M01() { .get int32 C1::I1.get_M01() .set void C1::I1.set_M01(int32) } .method public hidebysig specialname static int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname static void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 C1::get_M01() .set void C1::set_M01(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig specialname static int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname static void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 C2::get_M01() .set void C2::set_M01(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = (PropertySymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1.I1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.Same(c1M01.GetMethod, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c2.FindImplementationForInterfaceMember(m01.SetMethod)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c4.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c4.FindImplementationForInterfaceMember(m01.SetMethod)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (PropertySymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.Same(c2M01.GetMethod, c5.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c2M01.SetMethod, c5.FindImplementationForInterfaceMember(m01.SetMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticProperty_11() { // Ignore invalid metadata (non-abstract static virtual method). scenario1(); scenario2(); scenario3(); void scenario1() { var ilSource = @" .class interface public auto ansi abstract I1 { .method private hidebysig specialname static virtual int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static virtual void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,18): error CS0539: 'C1.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01").WithLocation(4, 18) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c.FindImplementationForInterfaceMember(m01)); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); } } void scenario2() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method private hidebysig specialname static virtual void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source2 = @" public class C1 : I1 { static int I1.M01 { get; } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, sourceSymbolValidator: validate2, symbolValidator: validate2, verify: Verification.Skipped).VerifyDiagnostics(); void validate2(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.I1.M01 { get; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.I1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(cM01.SetMethod); Assert.Null(c.FindImplementationForInterfaceMember(m01Set)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,29): error CS0550: 'C1.I1.M01.set' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("C1.I1.M01.set", "I1.M01").WithLocation(4, 29) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static int M01 { get; } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation5, sourceSymbolValidator: validate5, symbolValidator: validate5, verify: Verification.Skipped).VerifyDiagnostics(); void validate5(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } } var source6 = @" public class C1 : I1 { public static int M01 { set{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.get' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.get").WithLocation(2, 19) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); var source7 = @" public class C1 : I1 { static int I1.M01 { set{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.get' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.get").WithLocation(2, 19), // (4,18): error CS0551: Explicit interface implementation 'C1.I1.M01' is missing accessor 'I1.M01.get' // static int I1.M01 { set{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "M01").WithArguments("C1.I1.M01", "I1.M01.get").WithLocation(4, 18), // (4,24): error CS0550: 'C1.I1.M01.set' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { set{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("C1.I1.M01.set", "I1.M01").WithLocation(4, 24) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); } void scenario3() { var ilSource = @" .class interface public auto ansi abstract I1 { .method private hidebysig specialname static virtual int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source2 = @" public class C1 : I1 { static int I1.M01 { set{} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, sourceSymbolValidator: validate2, symbolValidator: validate2, verify: Verification.Skipped).VerifyDiagnostics(); void validate2(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.I1.M01 { set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.I1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(cM01.GetMethod); Assert.Null(c.FindImplementationForInterfaceMember(m01Get)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,24): error CS0550: 'C1.I1.M01.get' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C1.I1.M01.get", "I1.M01").WithLocation(4, 24) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.SetMethod, c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static int M01 { set{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation5, sourceSymbolValidator: validate5, symbolValidator: validate5, verify: Verification.Skipped).VerifyDiagnostics(); void validate5(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } var source6 = @" public class C1 : I1 { public static int M01 { get; } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.set' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.set").WithLocation(2, 19) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); var source7 = @" public class C1 : I1 { static int I1.M01 { get; } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.set' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.set").WithLocation(2, 19), // (4,18): error CS0551: Explicit interface implementation 'C1.I1.M01' is missing accessor 'I1.M01.set' // static int I1.M01 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "M01").WithArguments("C1.I1.M01", "I1.M01.set").WithLocation(4, 18), // (4,24): error CS0550: 'C1.I1.M01.get' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C1.I1.M01.get", "I1.M01").WithLocation(4, 24) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig specialname static int32 I1.get_M01 () cil managed { .override method int32 I1::get_M01() IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static void I1.set_M01 ( int32 'value' ) cil managed { .override method void I1::set_M01(int32) IL_0000: ret } .property instance int32 I1.M01() { .get int32 I2::I1.get_M01() .set void I2::I1.set_M01(int32) } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.SetMethod)); var i2M01 = i2.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, i2M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, i2M01.SetMethod.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticProperty_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static int M01 { get; set; } } class C1 { public static int M01 { get; set; } } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Get = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.GetMethod); var c2M01Set = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.SetMethod); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Get.MethodKind); Assert.False(c2M01Get.HasRuntimeSpecialName); Assert.False(c2M01Get.HasSpecialName); Assert.Equal("System.Int32 C2.I1.get_M01()", c2M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c2M01Get.ExplicitInterfaceImplementations.Single()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Set.MethodKind); Assert.False(c2M01Set.HasRuntimeSpecialName); Assert.False(c2M01Set.HasSpecialName); Assert.Equal("void C2.I1.set_M01(System.Int32 value)", c2M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c2M01Set.ExplicitInterfaceImplementations.Single()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c2M01); var c1M01 = module.GlobalNamespace.GetMember<PropertySymbol>("C1.M01"); var c1M01Get = c1M01.GetMethod; var c1M01Set = c1M01.SetMethod; Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c1M01Get.MethodKind); Assert.False(c1M01Get.HasRuntimeSpecialName); Assert.True(c1M01Get.HasSpecialName); Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c1M01Set.MethodKind); Assert.False(c1M01Set.HasRuntimeSpecialName); Assert.True(c1M01Set.HasSpecialName); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); } else { Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.PropertyGet, c2M01Get.MethodKind); Assert.False(c2M01Get.HasRuntimeSpecialName); Assert.True(c2M01Get.HasSpecialName); Assert.Same(c2M01.GetMethod, c2M01Get); Assert.Empty(c2M01Get.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.PropertySet, c2M01Set.MethodKind); Assert.False(c2M01Set.HasRuntimeSpecialName); Assert.True(c2M01Set.HasSpecialName); Assert.Same(c2M01.SetMethod, c2M01Set); Assert.Empty(c2M01Set.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.get_M01", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C1.M01.get"" IL_0005: ret } "); verifier.VerifyIL("C2.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.set"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticProperty_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void modopt(I1) set_M01 ( int32 modopt(I1) 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void modopt(I1) I1::set_M01(int32 modopt(I1)) } } .class interface public auto ansi abstract I2 { .method public hidebysig specialname abstract virtual static int32 modopt(I2) get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 modopt(I2) 'value' ) cil managed { } .property int32 modopt(I2) M01() { .get int32 modopt(I2) I2::get_M01() .set void I2::set_M01(int32 modopt(I2)) } } "; var source1 = @" class C1 : I1 { public static int M01 { get; set; } } class C2 : I1 { static int I1.M01 { get; set; } } class C3 : I2 { static int I2.M01 { get; set; } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = (PropertySymbol)c1.FindImplementationForInterfaceMember(m01); var c1M01Get = c1M01.GetMethod; var c1M01Set = c1M01.SetMethod; Assert.Equal("System.Int32 C1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Equal(MethodKind.PropertyGet, c1M01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", c1M01Get.ToTestDisplayString()); Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Same(c1M01Get, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Equal(MethodKind.PropertySet, c1M01Set.MethodKind); Assert.Equal("void C1.M01.set", c1M01Set.ToTestDisplayString()); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Same(m01.GetMethod, c1M01Get.ExplicitInterfaceImplementations.Single()); c1M01Set = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Set.MethodKind); Assert.Equal("void modopt(I1) C1.I1.set_M01(System.Int32 modopt(I1) value)", c1M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c1M01Set.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); } else { Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); Assert.Same(c1M01Set, c1.FindImplementationForInterfaceMember(m01.SetMethod)); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Get = c2M01.GetMethod; var c2M01Set = c2M01.SetMethod; Assert.Equal("System.Int32 C2.I1.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c2M01Get.MethodKind); Assert.Equal("System.Int32 C2.I1.M01.get", c2M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c2M01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Get, c2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c2M01Set.MethodKind); Assert.Equal("void modopt(I1) C2.I1.M01.set", c2M01Set.ToTestDisplayString()); Assert.Equal("System.Int32 modopt(I1) value", c2M01Set.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.SetMethod, c2M01Set.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Set, c2.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(c2M01, c2.GetMembers().OfType<PropertySymbol>().Single()); Assert.Equal(2, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var c3 = module.GlobalNamespace.GetTypeMember("C3"); m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c3M01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); var c3M01Get = c3M01.GetMethod; var c3M01Set = c3M01.SetMethod; Assert.Equal("System.Int32 modopt(I2) C3.I2.M01 { get; set; }", c3M01.ToTestDisplayString()); Assert.True(c3M01.IsStatic); Assert.False(c3M01.IsAbstract); Assert.False(c3M01.IsVirtual); Assert.Same(m01, c3M01.ExplicitInterfaceImplementations.Single()); Assert.True(c3M01Get.IsStatic); Assert.False(c3M01Get.IsAbstract); Assert.False(c3M01Get.IsVirtual); Assert.False(c3M01Get.IsMetadataVirtual()); Assert.False(c3M01Get.IsMetadataFinal); Assert.False(c3M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c3M01Get.MethodKind); Assert.Equal("System.Int32 modopt(I2) C3.I2.M01.get", c3M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c3M01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(c3M01Get, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.True(c3M01Set.IsStatic); Assert.False(c3M01Set.IsAbstract); Assert.False(c3M01Set.IsVirtual); Assert.False(c3M01Set.IsMetadataVirtual()); Assert.False(c3M01Set.IsMetadataFinal); Assert.False(c3M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c3M01Set.MethodKind); Assert.Equal("void C3.I2.M01.set", c3M01Set.ToTestDisplayString()); Assert.Equal("System.Int32 modopt(I2) value", c3M01Set.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.SetMethod, c3M01Set.ExplicitInterfaceImplementations.Single()); Assert.Same(c3M01Set, c3.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(c3M01, c3.GetMembers().OfType<PropertySymbol>().Single()); Assert.Equal(2, c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); } verifier.VerifyIL("C1.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.set"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStatiProperty_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static int M01 { get; set; } abstract static int M02 { get; set; } } public class C1 { public static int M01 { get; set; } } public class C2 : C1, I1 { static int I1.M02 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<PropertySymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<PropertySymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<PropertySymbol>("M01"); Assert.Equal("System.Int32 C1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); var c1M01Get = c1M01.GetMethod; Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); var c1M01Set = c1M01.SetMethod; Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01Get = c3.FindImplementationForInterfaceMember(m01.GetMethod); Assert.Equal("System.Int32 C2.I1.get_M01()", c2M01Get.ToTestDisplayString()); var c2M01Set = c3.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal("void C2.I1.set_M01(System.Int32 value)", c2M01Set.ToTestDisplayString()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c3.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<PropertySymbol>().Single(); var c2M02 = c3.BaseType().GetMember<PropertySymbol>("I1.M02"); Assert.Equal("System.Int32 C2.I1.M02 { get; set; }", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c2M02.GetMethod, c3.FindImplementationForInterfaceMember(m02.GetMethod)); Assert.Same(c2M02.SetMethod, c3.FindImplementationForInterfaceMember(m02.SetMethod)); } } [Fact] public void ImplementAbstractStaticProperty_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1 : I1 { public static int M01 { get; set; } } public class C2 : C1 { new public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.get_M01", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C2.M01.get"" IL_0005: ret } "); verifier.VerifyIL("C3.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.set"" IL_0006: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c2M01 = c3.BaseType().GetMember<PropertySymbol>("M01"); var c2M01Get = c2M01.GetMethod; var c2M01Set = c2M01.SetMethod; Assert.Equal("System.Int32 C2.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.Empty(c2M01Get.ExplicitInterfaceImplementations); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); Assert.Empty(c2M01Set.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); // Forwarding methods for accessors aren't tied to a property Assert.Null(c3M01); var c3M01Get = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.GetMethod); Assert.Equal("System.Int32 C3.I1.get_M01()", c3M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c3M01Get.ExplicitInterfaceImplementations.Single()); var c3M01Set = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal("void C3.I1.set_M01(System.Int32 value)", c3M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c3M01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c2M01Get, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c2M01Set, c3.FindImplementationForInterfaceMember(m01.SetMethod)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_19(bool genericFirst) { // An "ambiguity" in implicit/explicit implementation declared in generic base class. var generic = @" public static T M01 { get; set; } "; var nonGeneric = @" static int I1.M01 { get; set; } "; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<PropertySymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1<T>.I1.M01 { get; set; }", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_20(bool genericFirst) { // Same as ImplementAbstractStaticProperty_19 only interface is generic too. var generic = @" static T I1<T>.M01 { get; set; } "; var nonGeneric = @" public static int M01 { get; set; } "; var source1 = @" public interface I1<T> { abstract static T M01 { get; set; } } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<PropertySymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("T C1<T>.I1<T>.M01 { get; set; }", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public event System.Action M01; } " + typeKeyword + @" C3 : I1 { static event System.Action M01; } " + typeKeyword + @" C4 : I1 { event System.Action I1.M01 { add{} remove{}} } " + typeKeyword + @" C5 : I1 { public static event System.Action<int> M01; } " + typeKeyword + @" C6 : I1 { static event System.Action<int> I1.M01 { add{} remove{}} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,28): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.M01 { add{} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 28), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'Action'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "System.Action").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,40): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action<int> I1.M01 { add{} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 40) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract event System.Action M01; } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static event System.Action M01; } " + typeKeyword + @" C3 : I1 { event System.Action M01; } " + typeKeyword + @" C4 : I1 { static event System.Action I1.M01 { add{} remove{} } } " + typeKeyword + @" C5 : I1 { public event System.Action<int> M01; } " + typeKeyword + @" C6 : I1 { event System.Action<int> I1.M01 { add{} remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,35): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 35), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'Action'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "System.Action").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,33): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action<int> I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 33) ); } [Fact] public void ImplementAbstractStaticEvent_03() { var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract static event System.Action M01; } interface I2 : I1 {} interface I3 : I1 { public virtual event System.Action M01 { add{} remove{} } } interface I4 : I1 { static event System.Action M01; } interface I5 : I1 { event System.Action I1.M01 { add{} remove{} } } interface I6 : I1 { static event System.Action I1.M01 { add{} remove{} } } interface I7 : I1 { abstract static event System.Action M01; } interface I8 : I1 { abstract static event System.Action I1.M01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,40): warning CS0108: 'I3.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // public virtual event System.Action M01 { add{} remove{} } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01", "I1.M01").WithLocation(12, 40), // (17,32): warning CS0108: 'I4.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // static event System.Action M01; Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01", "I1.M01").WithLocation(17, 32), // (22,28): error CS0539: 'I5.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01").WithLocation(22, 28), // (27,35): error CS0106: The modifier 'static' is not valid for this item // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 35), // (27,35): error CS0539: 'I6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01").WithLocation(27, 35), // (32,41): warning CS0108: 'I7.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // abstract static event System.Action M01; Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01", "I1.M01").WithLocation(32, 41), // (37,44): error CS0106: The modifier 'static' is not valid for this item // abstract static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 44), // (37,44): error CS0539: 'I8.M01' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static event System.Action I1.M01; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01").WithLocation(37, 44) ); foreach (var m01 in compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers()) { Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; abstract static event System.Action M02; } "; var source2 = typeKeyword + @" Test: I1 { static event System.Action I1.M01 { add{} remove => throw null; } public static event System.Action M02; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,35): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static event System.Action I1.M01 { add{} remove => throw null; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 35), // (5,39): warning CS0067: The event 'Test.M02' is never used // public static event System.Action M02; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "M02").WithArguments("Test.M02").WithLocation(5, 39) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,35): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static event System.Action I1.M01 { add{} remove => throw null; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 35), // (5,39): warning CS0067: The event 'Test.M02' is never used // public static event System.Action M02; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "M02").WithArguments("Test.M02").WithLocation(5, 39), // (10,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 41), // (11,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action M02; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } "; var source2 = typeKeyword + @" Test1: I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.remove' cannot implement interface member 'I1.M01.remove' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.remove", "I1.M01.remove", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.add' cannot implement interface member 'I1.M01.add' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.add", "I1.M01.add", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.remove' cannot implement interface member 'I1.M01.remove' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.remove", "I1.M01.remove", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.add' cannot implement interface member 'I1.M01.add' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.add", "I1.M01.add", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12), // (9,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } "; var source2 = typeKeyword + @" Test1: I1 { static event System.Action I1.M01 { add => throw null; remove => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static event System.Action I1.M01 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 35) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static event System.Action I1.M01 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 35), // (9,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C : I1 { public static event System.Action M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; var m01Remove = m01.RemoveMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.False(cM01Add.HasRuntimeSpecialName); Assert.True(cM01Add.HasSpecialName); Assert.Equal("void C.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.False(cM01Remove.HasRuntimeSpecialName); Assert.True(cM01Remove.HasSpecialName); Assert.Equal("void C.M01.remove", cM01Remove.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Add.ExplicitInterfaceImplementations); Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C : I1 { static event System.Action I1.M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; var m01Remove = m01.RemoveMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C.I1.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.False(cM01Add.HasRuntimeSpecialName); Assert.True(cM01Add.HasSpecialName); Assert.Equal("void C.I1.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.False(cM01Remove.HasRuntimeSpecialName); Assert.True(cM01Remove.HasSpecialName); Assert.Equal("void C.I1.M01.remove", cM01Remove.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static event System.Action M01; } public class C1 { public static event System.Action M01 { add => throw null; remove {} } } public class C2 : C1, I1 { static event System.Action I1.M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<EventSymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var cM01 = (EventSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C2.I1.M01", cM01.ToTestDisplayString()); Assert.Same(cM01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(cM01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, cM01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, cM01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig specialname static void I1.add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::add_M01(class [mscorlib]System.Action) IL_0000: ret } .method private hidebysig specialname static void I1.remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::remove_M01(class [mscorlib]System.Action) IL_0000: ret } .event [mscorlib]System.Action I1.M01 { .addon void C1::I1.add_M01(class [mscorlib]System.Action) .removeon void C1::I1.remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void C1::add_M01(class [mscorlib]System.Action) .removeon void C1::remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig specialname static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void C2::add_M01(class [mscorlib]System.Action) .removeon void C2::remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c1M01 = (EventSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C1.I1.M01", c1M01.ToTestDisplayString()); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c2.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c4.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c4.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (EventSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C2.M01", c2M01.ToTestDisplayString()); Assert.Same(c2M01.AddMethod, c5.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c2M01.RemoveMethod, c5.FindImplementationForInterfaceMember(m01.RemoveMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticEvent_11() { // Ignore invalid metadata (non-abstract static virtual method). scenario1(); scenario2(); scenario3(); void scenario1() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname static virtual void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static virtual void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,34): error CS0539: 'C1.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c.FindImplementationForInterfaceMember(m01)); Assert.Null(c.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c.FindImplementationForInterfaceMember(m01.RemoveMethod)); } } void scenario2() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname static virtual void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { add {} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add {} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C1.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.Equal("void C1.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.Equal("void C1.M01.remove", cM01Remove.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.RemoveMethod)); if (module is PEModuleSymbol) { Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01Add.ExplicitInterfaceImplementations); } Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,46): error CS0550: 'C1.I1.M01.remove' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "remove").WithArguments("C1.I1.M01.remove", "I1.M01").WithLocation(4, 46) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static event System.Action M01 { add{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics( // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { add{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation5.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source6 = @" public class C1 : I1 { public static event System.Action M01 { remove{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.add' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.add").WithLocation(2, 19), // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source7 = @" public class C1 : I1 { static event System.Action I1.M01 { remove{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.add' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.add").WithLocation(2, 19), // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34), // (4,40): error CS0550: 'C1.I1.M01.remove' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "remove").WithArguments("C1.I1.M01.remove", "I1.M01").WithLocation(4, 40) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } void scenario3() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname static virtual void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { remove {} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add {} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var m01Remove = m01.RemoveMethod; Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C1.M01", cM01.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.Equal("void C1.M01.remove", cM01Remove.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.Equal("void C1.M01.add", cM01Add.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.AddMethod)); if (module is PEModuleSymbol) { Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Add.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,40): error CS0550: 'C1.I1.M01.add' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "add").WithArguments("C1.I1.M01.add", "I1.M01").WithLocation(4, 40) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static event System.Action M01 { remove{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics( // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation5.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); var source6 = @" public class C1 : I1 { public static event System.Action M01 { add{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.remove' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.remove").WithLocation(2, 19), // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source7 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.remove' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.remove").WithLocation(2, 19), // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34), // (4,40): error CS0550: 'C1.I1.M01.add' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "add").WithArguments("C1.I1.M01.add", "I1.M01").WithLocation(4, 40) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig specialname static void I1.add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::add_M01(class [mscorlib]System.Action) IL_0000: ret } .method private hidebysig specialname static void I1.remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::remove_M01(class [mscorlib]System.Action) IL_0000: ret } .event [mscorlib]System.Action I1.M01 { .addon void I2::I1.add_M01(class [mscorlib]System.Action) .removeon void I2::I1.remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.RemoveMethod)); var i2M01 = i2.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, i2M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, i2M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticEvent_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static event System.Action M01; } class C1 { public static event System.Action M01 { add => throw null; remove{} } } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Add = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.AddMethod); var c2M01Remove = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Add.MethodKind); Assert.False(c2M01Add.HasRuntimeSpecialName); Assert.False(c2M01Add.HasSpecialName); Assert.Equal("void C2.I1.add_M01(System.Action value)", c2M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c2M01Add.ExplicitInterfaceImplementations.Single()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Remove.MethodKind); Assert.False(c2M01Remove.HasRuntimeSpecialName); Assert.False(c2M01Remove.HasSpecialName); Assert.Equal("void C2.I1.remove_M01(System.Action value)", c2M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c2M01Remove.ExplicitInterfaceImplementations.Single()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c2M01); var c1M01 = module.GlobalNamespace.GetMember<EventSymbol>("C1.M01"); var c1M01Add = c1M01.AddMethod; var c1M01Remove = c1M01.RemoveMethod; Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c1M01Add.MethodKind); Assert.False(c1M01Add.HasRuntimeSpecialName); Assert.True(c1M01Add.HasSpecialName); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c1M01Remove.MethodKind); Assert.False(c1M01Remove.HasRuntimeSpecialName); Assert.True(c1M01Remove.HasSpecialName); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); } else { Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Equal("event System.Action C1.M01", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.EventAdd, c2M01Add.MethodKind); Assert.False(c2M01Add.HasRuntimeSpecialName); Assert.True(c2M01Add.HasSpecialName); Assert.Same(c2M01.AddMethod, c2M01Add); Assert.Empty(c2M01Add.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.EventRemove, c2M01Remove.MethodKind); Assert.False(c2M01Remove.HasRuntimeSpecialName); Assert.True(c2M01Remove.HasSpecialName); Assert.Same(c2M01.RemoveMethod, c2M01Remove); Assert.Empty(c2M01Remove.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C2.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.remove"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticEvent_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action`1<int32 modopt(I1)> 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action`1<int32 modopt(I1)> 'value' ) cil managed { } .event class [mscorlib]System.Action`1<int32 modopt(I1)> M01 { .addon void I1::add_M01(class [mscorlib]System.Action`1<int32 modopt(I1)>) .removeon void I1::remove_M01(class [mscorlib]System.Action`1<int32 modopt(I1)>) } } .class interface public auto ansi abstract I2 { .method public hidebysig specialname abstract virtual static void add_M02 ( class [mscorlib]System.Action modopt(I1) 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void modopt(I2) remove_M02 ( class [mscorlib]System.Action 'value' ) cil managed { } .event class [mscorlib]System.Action M02 { .addon void I2::add_M02(class [mscorlib]System.Action modopt(I1)) .removeon void modopt(I2) I2::remove_M02(class [mscorlib]System.Action) } } "; var source1 = @" class C1 : I1 { public static event System.Action<int> M01 { add => throw null; remove{} } } class C2 : I1 { static event System.Action<int> I1.M01 { add => throw null; remove{} } } #pragma warning disable CS0067 // The event 'C3.M02' is never used class C3 : I2 { public static event System.Action M02; } class C4 : I2 { static event System.Action I2.M02 { add => throw null; remove{} } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); var c1M01Add = c1M01.AddMethod; var c1M01Remove = c1M01.RemoveMethod; Assert.Equal("event System.Action<System.Int32> C1.M01", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Equal(MethodKind.EventAdd, c1M01Add.MethodKind); Assert.Equal("void C1.M01.add", c1M01Add.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32> value", c1M01Add.Parameters.Single().ToTestDisplayString()); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c1M01Remove.MethodKind); Assert.Equal("void C1.M01.remove", c1M01Remove.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32> value", c1M01Remove.Parameters.Single().ToTestDisplayString()); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { c1M01Add = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Add.MethodKind); Assert.Equal("void C1.I1.add_M01(System.Action<System.Int32 modopt(I1)> value)", c1M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c1M01Add.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); c1M01Remove = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Remove.MethodKind); Assert.Equal("void C1.I1.remove_M01(System.Action<System.Int32 modopt(I1)> value)", c1M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c1M01Remove.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); // Forwarding methods aren't tied to an event Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01Add, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01Remove, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Add = c2M01.AddMethod; var c2M01Remove = c2M01.RemoveMethod; Assert.Equal("event System.Action<System.Int32 modopt(I1)> C2.I1.M01", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c2M01Add.MethodKind); Assert.Equal("void C2.I1.M01.add", c2M01Add.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32 modopt(I1)> value", c2M01Add.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.AddMethod, c2M01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Add, c2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c2M01Remove.MethodKind); Assert.Equal("void C2.I1.M01.remove", c2M01Remove.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32 modopt(I1)> value", c2M01Remove.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c2M01Remove.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Remove, c2.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(c2M01, c2.GetMembers().OfType<EventSymbol>().Single()); Assert.Equal(2, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m02 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c3M02 = c3.GetMembers().OfType<EventSymbol>().Single(); var c3M02Add = c3M02.AddMethod; var c3M02Remove = c3M02.RemoveMethod; Assert.Equal("event System.Action C3.M02", c3M02.ToTestDisplayString()); Assert.Empty(c3M02.ExplicitInterfaceImplementations); Assert.True(c3M02.IsStatic); Assert.False(c3M02.IsAbstract); Assert.False(c3M02.IsVirtual); Assert.Equal(MethodKind.EventAdd, c3M02Add.MethodKind); Assert.Equal("void C3.M02.add", c3M02Add.ToTestDisplayString()); Assert.Equal("System.Action value", c3M02Add.Parameters.Single().ToTestDisplayString()); Assert.Empty(c3M02Add.ExplicitInterfaceImplementations); Assert.True(c3M02Add.IsStatic); Assert.False(c3M02Add.IsAbstract); Assert.False(c3M02Add.IsVirtual); Assert.False(c3M02Add.IsMetadataVirtual()); Assert.False(c3M02Add.IsMetadataFinal); Assert.False(c3M02Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c3M02Remove.MethodKind); Assert.Equal("void C3.M02.remove", c3M02Remove.ToTestDisplayString()); Assert.Equal("System.Void", c3M02Remove.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Empty(c3M02Remove.ExplicitInterfaceImplementations); Assert.True(c3M02Remove.IsStatic); Assert.False(c3M02Remove.IsAbstract); Assert.False(c3M02Remove.IsVirtual); Assert.False(c3M02Remove.IsMetadataVirtual()); Assert.False(c3M02Remove.IsMetadataFinal); Assert.False(c3M02Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { c3M02Add = (MethodSymbol)c3.FindImplementationForInterfaceMember(m02.AddMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c3M02Add.MethodKind); Assert.Equal("void C3.I2.add_M02(System.Action modopt(I1) value)", c3M02Add.ToTestDisplayString()); Assert.Same(m02.AddMethod, c3M02Add.ExplicitInterfaceImplementations.Single()); Assert.True(c3M02Add.IsStatic); Assert.False(c3M02Add.IsAbstract); Assert.False(c3M02Add.IsVirtual); Assert.False(c3M02Add.IsMetadataVirtual()); Assert.False(c3M02Add.IsMetadataFinal); Assert.False(c3M02Add.IsMetadataNewSlot()); c3M02Remove = (MethodSymbol)c3.FindImplementationForInterfaceMember(m02.RemoveMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c3M02Remove.MethodKind); Assert.Equal("void modopt(I2) C3.I2.remove_M02(System.Action value)", c3M02Remove.ToTestDisplayString()); Assert.Same(m02.RemoveMethod, c3M02Remove.ExplicitInterfaceImplementations.Single()); Assert.True(c3M02Remove.IsStatic); Assert.False(c3M02Remove.IsAbstract); Assert.False(c3M02Remove.IsVirtual); Assert.False(c3M02Remove.IsMetadataVirtual()); Assert.False(c3M02Remove.IsMetadataFinal); Assert.False(c3M02Remove.IsMetadataNewSlot()); // Forwarding methods aren't tied to an event Assert.Null(c3.FindImplementationForInterfaceMember(m02)); } else { Assert.Same(c3M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c3M02Add, c3.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.Same(c3M02Remove, c3.FindImplementationForInterfaceMember(m02.RemoveMethod)); } var c4 = module.GlobalNamespace.GetTypeMember("C4"); var c4M02 = (EventSymbol)c4.FindImplementationForInterfaceMember(m02); var c4M02Add = c4M02.AddMethod; var c4M02Remove = c4M02.RemoveMethod; Assert.Equal("event System.Action C4.I2.M02", c4M02.ToTestDisplayString()); // Signatures of accessors are lacking custom modifiers due to https://github.com/dotnet/roslyn/issues/53390. Assert.True(c4M02.IsStatic); Assert.False(c4M02.IsAbstract); Assert.False(c4M02.IsVirtual); Assert.Same(m02, c4M02.ExplicitInterfaceImplementations.Single()); Assert.True(c4M02Add.IsStatic); Assert.False(c4M02Add.IsAbstract); Assert.False(c4M02Add.IsVirtual); Assert.False(c4M02Add.IsMetadataVirtual()); Assert.False(c4M02Add.IsMetadataFinal); Assert.False(c4M02Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c4M02Add.MethodKind); Assert.Equal("void C4.I2.M02.add", c4M02Add.ToTestDisplayString()); Assert.Equal("System.Action value", c4M02Add.Parameters.Single().ToTestDisplayString()); Assert.Equal("System.Void", c4M02Add.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Same(m02.AddMethod, c4M02Add.ExplicitInterfaceImplementations.Single()); Assert.Same(c4M02Add, c4.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.True(c4M02Remove.IsStatic); Assert.False(c4M02Remove.IsAbstract); Assert.False(c4M02Remove.IsVirtual); Assert.False(c4M02Remove.IsMetadataVirtual()); Assert.False(c4M02Remove.IsMetadataFinal); Assert.False(c4M02Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c4M02Remove.MethodKind); Assert.Equal("void C4.I2.M02.remove", c4M02Remove.ToTestDisplayString()); Assert.Equal("System.Action value", c4M02Remove.Parameters.Single().ToTestDisplayString()); Assert.Equal("System.Void", c4M02Remove.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Same(m02.RemoveMethod, c4M02Remove.ExplicitInterfaceImplementations.Single()); Assert.Same(c4M02Remove, c4.FindImplementationForInterfaceMember(m02.RemoveMethod)); Assert.Same(c4M02, c4.GetMembers().OfType<EventSymbol>().Single()); Assert.Equal(2, c4.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); } verifier.VerifyIL("C1.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C1.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.remove"" IL_0006: ret } "); verifier.VerifyIL("C3.I2.add_M02", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C3.M02.add"" IL_0006: ret } "); verifier.VerifyIL("C3.I2.remove_M02", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C3.M02.remove"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticEvent_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static event System.Action M01; abstract static event System.Action M02; } public class C1 { public static event System.Action M01 { add => throw null; remove{} } } public class C2 : C1, I1 { static event System.Action I1.M02 { add => throw null; remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<EventSymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<EventSymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<EventSymbol>("M01"); Assert.Equal("event System.Action C1.M01", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); var c1M01Add = c1M01.AddMethod; Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); var c1M01Remove = c1M01.RemoveMethod; Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01Add = c3.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal("void C2.I1.add_M01(System.Action value)", c2M01Add.ToTestDisplayString()); var c2M01Remove = c3.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal("void C2.I1.remove_M01(System.Action value)", c2M01Remove.ToTestDisplayString()); // Forwarding methods for accessors aren't tied to an event Assert.Null(c3.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<EventSymbol>().Single(); var c2M02 = c3.BaseType().GetMember<EventSymbol>("I1.M02"); Assert.Equal("event System.Action C2.I1.M02", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c2M02.AddMethod, c3.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.Same(c2M02.RemoveMethod, c3.FindImplementationForInterfaceMember(m02.RemoveMethod)); } } [Fact] public void ImplementAbstractStaticEvent_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static event System.Action M01; } public class C1 : I1 { public static event System.Action M01 { add{} remove => throw null; } } public class C2 : C1 { new public static event System.Action M01 { add{} remove => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C3.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.remove"" IL_0006: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<EventSymbol>("M01"); var c2M01Add = c2M01.AddMethod; var c2M01Remove = c2M01.RemoveMethod; Assert.Equal("event System.Action C2.M01", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.Empty(c2M01Add.ExplicitInterfaceImplementations); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); Assert.Empty(c2M01Remove.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (EventSymbol)c3.FindImplementationForInterfaceMember(m01); // Forwarding methods for accessors aren't tied to an event Assert.Null(c3M01); var c3M01Add = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal("void C3.I1.add_M01(System.Action value)", c3M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c3M01Add.ExplicitInterfaceImplementations.Single()); var c3M01Remove = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal("void C3.I1.remove_M01(System.Action value)", c3M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c3M01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c2M01Add, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c2M01Remove, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_19(bool genericFirst) { // An "ambiguity" in implicit/explicit implementation declared in generic base class. var generic = @" public static event System.Action<T> M01 { add{} remove{} } "; var nonGeneric = @" static event System.Action<int> I1.M01 { add{} remove{} } "; var source1 = @" public interface I1 { abstract static event System.Action<int> M01; } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<EventSymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action<System.Int32> C1<T>.I1.M01", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_20(bool genericFirst) { // Same as ImplementAbstractStaticEvent_19 only interface is generic too. var generic = @" static event System.Action<T> I1<T>.M01 { add{} remove{} } "; var nonGeneric = @" public static event System.Action<int> M01 { add{} remove{} } "; var source1 = @" public interface I1<T> { abstract static event System.Action<T> M01; } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<EventSymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action<T> C1<T>.I1<T>.M01", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } private static string ConversionOperatorName(string op) => op switch { "implicit" => WellKnownMemberNames.ImplicitConversionName, "explicit" => WellKnownMemberNames.ExplicitConversionName, _ => throw TestExceptionUtilities.UnexpectedValue(op) }; [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = ConversionOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public " + op + @" operator int(C2 x) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static " + op + @" operator int(C3 x) => throw null; } " + typeKeyword + @" C4 : I1<C4> { " + op + @" I1<C4>.operator int(C4 x) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static " + op + @" operator long(C5 x) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static " + op + @" I1<C6>.operator long(C6 x) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static int " + opName + @"(C7 x) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static int I1<C8>." + opName + @"(C8 x) => throw null; } public interface I2<T> where T : I2<T> { abstract static int " + opName + @"(T x); } " + typeKeyword + @" C9 : I2<C9> { public static " + op + @" operator int(C9 x) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static " + op + @" I2<C10>.operator int(C10 x) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.explicit operator int(C1)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>." + op + " operator int(C1)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.explicit operator int(C2)'. 'C2.explicit operator int(C2)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>." + op + " operator int(C2)", "C2." + op + " operator int(C2)").WithLocation(12, 10), // (14,30): error CS0558: User-defined operator 'C2.explicit operator int(C2)' must be declared static and public // public explicit operator int(C2 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "int").WithArguments("C2." + op + " operator int(C2)").WithLocation(14, 30), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.explicit operator int(C3)'. 'C3.explicit operator int(C3)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>." + op + " operator int(C3)", "C3." + op + " operator int(C3)").WithLocation(18, 10), // (20,30): error CS0558: User-defined operator 'C3.explicit operator int(C3)' must be declared static and public // static explicit operator int(C3 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "int").WithArguments("C3." + op + " operator int(C3)").WithLocation(20, 30), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.explicit operator int(C4)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>." + op + " operator int(C4)").WithLocation(24, 10), // (26,30): error CS8930: Explicit implementation of a user-defined operator 'C4.explicit operator int(C4)' must be declared static // explicit I1<C4>.operator int(C4 x) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, "int").WithArguments("C4." + op + " operator int(C4)").WithLocation(26, 30), // (26,30): error CS0539: 'C4.explicit operator int(C4)' in explicit interface declaration is not found among members of the interface that can be implemented // explicit I1<C4>.operator int(C4 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C4." + op + " operator int(C4)").WithLocation(26, 30), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.explicit operator int(C5)'. 'C5.explicit operator long(C5)' cannot implement 'I1<C5>.explicit operator int(C5)' because it does not have the matching return type of 'int'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>." + op + " operator int(C5)", "C5." + op + " operator long(C5)", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.explicit operator int(C6)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>." + op + " operator int(C6)").WithLocation(36, 10), // (38,37): error CS0539: 'C6.explicit operator long(C6)' in explicit interface declaration is not found among members of the interface that can be implemented // static explicit I1<C6>.operator long(C6 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "long").WithArguments("C6." + op + " operator long(C6)").WithLocation(38, 37), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.explicit operator int(C7)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>." + op + " operator int(C7)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.explicit operator int(C8)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>." + op + " operator int(C8)").WithLocation(48, 10), // (50,23): error CS0539: 'C8.op_Explicit(C8)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C8>.op_Explicit(C8 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8)").WithLocation(50, 23), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_Explicit(C9)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_Explicit(C10)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10)").WithLocation(65, 11), // (67,38): error CS0539: 'C10.explicit operator int(C10)' in explicit interface declaration is not found among members of the interface that can be implemented // static explicit I2<C10>.operator int(C10 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C10." + op + " operator int(C10)").WithLocation(67, 38) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_03([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } interface I2<T> : I1<T> where T : I1<T> {} interface I3<T> : I1<T> where T : I1<T> { " + op + @" operator int(T x) => default; } interface I4<T> : I1<T> where T : I1<T> { static " + op + @" operator int(T x) => default; } interface I5<T> : I1<T> where T : I1<T> { " + op + @" I1<T>.operator int(T x) => default; } interface I6<T> : I1<T> where T : I1<T> { static " + op + @" I1<T>.operator int(T x) => default; } interface I7<T> : I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public interface I11<T> where T : I11<T> { abstract static " + op + @" operator int(T x); } interface I8<T> : I11<T> where T : I8<T> { " + op + @" operator int(T x) => default; } interface I9<T> : I11<T> where T : I9<T> { static " + op + @" operator int(T x) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static " + op + @" operator int(T x); } interface I12<T> : I11<T> where T : I12<T> { static " + op + @" I11<T>.operator int(T x) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static " + op + @" I11<T>.operator int(T x); } interface I14<T> : I1<T> where T : I1<T> { abstract static " + op + @" I1<T>.operator int(T x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,23): error CS0556: User-defined conversion must convert to or from the enclosing type // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(12, 23), // (12,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(12, 23), // (17,30): error CS0556: User-defined conversion must convert to or from the enclosing type // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(17, 30), // (17,30): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(17, 30), // (22,29): error CS8930: Explicit implementation of a user-defined operator 'I5<T>.implicit operator int(T)' must be declared static // implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, "int").WithArguments("I5<T>." + op + " operator int(T)").WithLocation(22, 29), // (22,29): error CS0539: 'I5<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I5<T>." + op + " operator int(T)").WithLocation(22, 29), // (27,36): error CS0539: 'I6<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I6<T>." + op + " operator int(T)").WithLocation(27, 36), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "int").WithLocation(32, 39), // (42,23): error CS0556: User-defined conversion must convert to or from the enclosing type // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(42, 23), // (42,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(42, 23), // (47,30): error CS0556: User-defined conversion must convert to or from the enclosing type // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(47, 30), // (47,30): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(47, 30), // (57,37): error CS0539: 'I12<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I11<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I12<T>." + op + " operator int(T)").WithLocation(57, 37), // (62,46): error CS0106: The modifier 'abstract' is not valid for this item // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(62, 46), // (62,46): error CS0501: 'I13<T>.implicit operator int(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "int").WithArguments("I13<T>." + op + " operator int(T)").WithLocation(62, 46), // (62,46): error CS0539: 'I13<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I13<T>." + op + " operator int(T)").WithLocation(62, 46), // (67,45): error CS0106: The modifier 'abstract' is not valid for this item // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(67, 45), // (67,45): error CS0501: 'I14<T>.implicit operator int(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "int").WithArguments("I14<T>." + op + " operator int(T)").WithLocation(67, 45), // (67,45): error CS0539: 'I14<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I14<T>." + op + " operator int(T)").WithLocation(67, 45) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_04([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I2<T> where T : I2<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1 : I2<Test1> { static " + op + @" I2<Test1>.operator int(Test1 x) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static " + op + @" operator int(Test2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,21): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static explicit I2<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I2<Test1>.").WithArguments("static abstract members in interfaces").WithLocation(4, 21) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,21): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static explicit I2<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I2<Test1>.").WithArguments("static abstract members in interfaces").WithLocation(4, 21), // (14,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(14, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_05([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static " + op + @" operator int(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.explicit operator int(Test1)' cannot implement interface member 'I1<Test1>.explicit operator int(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1." + op + " operator int(Test1)", "I1<Test1>." + op + " operator int(Test1)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.explicit operator int(Test1)' cannot implement interface member 'I1<Test1>.explicit operator int(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1." + op + " operator int(Test1)", "I1<Test1>." + op + " operator int(Test1)", "Test1").WithLocation(2, 12), // (9,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(9, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_06([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1 : I1<Test1> { static " + op + @" I1<Test1>.operator int(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,40): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static explicit I1<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 40) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,40): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static explicit I1<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 40), // (9,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(9, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_07([CombinatorialValues("implicit", "explicit")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); abstract static " + op + @" operator long(T x); } " + typeKeyword + @" C : I1<C> { public static " + op + @" operator long(C x) => default; public static " + op + @" operator int(C x) => default; } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = i1.GetMembers().OfType<MethodSymbol>().First(); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("System.Int32 C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } var m02 = i1.GetMembers().OfType<MethodSymbol>().ElementAt(1); var cM02 = (MethodSymbol)c.FindImplementationForInterfaceMember(m02); Assert.True(cM02.IsStatic); Assert.False(cM02.IsAbstract); Assert.False(cM02.IsVirtual); Assert.False(cM02.IsMetadataVirtual()); Assert.False(cM02.IsMetadataFinal); Assert.False(cM02.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, cM02.MethodKind); Assert.False(cM02.HasRuntimeSpecialName); Assert.True(cM02.HasSpecialName); Assert.Equal("System.Int64 C." + opName + "(C x)", cM02.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m02, cM02.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM02.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_08([CombinatorialValues("implicit", "explicit")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" interface I1<T> where T : I1<T> { abstract static " + op + @" operator C(T x); abstract static " + op + @" operator int(T x); } " + typeKeyword + @" C : I1<C> { static " + op + @" I1<C>.operator int(C x) => int.MaxValue; static " + op + @" I1<C>.operator C(C x) => default; } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.Equal("default", node.ToString()); Assert.Equal("C", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<ConversionOperatorDeclarationSyntax>()); Assert.Equal("C C.I1<C>." + opName + "(C x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<MethodSymbol>().First(); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("C C.I1<C>." + opName + "(C x)", cM01.ToTestDisplayString()); Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); var m02 = c.Interfaces().Single().GetMembers().OfType<MethodSymbol>().ElementAt(1); var cM02 = (MethodSymbol)c.FindImplementationForInterfaceMember(m02); Assert.True(cM02.IsStatic); Assert.False(cM02.IsAbstract); Assert.False(cM02.IsVirtual); Assert.False(cM02.IsMetadataVirtual()); Assert.False(cM02.IsMetadataFinal); Assert.False(cM02.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM02.MethodKind); Assert.False(cM02.HasRuntimeSpecialName); Assert.False(cM02.HasSpecialName); Assert.Equal("System.Int32 C.I1<C>." + opName + "(C x)", cM02.ToTestDisplayString()); Assert.Equal(m02, cM02.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_09([CombinatorialValues("implicit", "explicit")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = ConversionOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.I1<C2>." + opName + "(C2 x)", cM01.ToTestDisplayString()); Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_10([CombinatorialValues("implicit", "explicit")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 " + opName + @" ( !T x ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements class I1`1<class C1> { .method private hidebysig static int32 'I1<C1>." + opName + @"' ( class C1 x ) cil managed { .override method int32 class I1`1<class C1>::" + opName + @"(!0) IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig static specialname int32 " + opName + @" ( class C1 x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2053 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: nop IL_0007: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements class I1`1<class C1> { .method public hidebysig static specialname int32 " + opName + @" ( class C1 x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1<C1> { } public class C5 : C2, I1<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Equal(MethodKind.Conversion, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2." + opName + "(C1 x)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.Conversion, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_11([CombinatorialValues("implicit", "explicit")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname virtual static int32 " + opName + @" ( !T x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } } "; var source1 = @" public class C1 : I1<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1<C1> { static " + op + @" I1<C1>.operator int(C1 x) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,37): error CS0539: 'C1.implicit operator int(C1)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I1<C1>.operator int(C1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C1." + op + " operator int(C1)").WithLocation(4, 37) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("System.Int32 I1<C1>." + opName + "(C1 x)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_12([CombinatorialValues("implicit", "explicit")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 " + opName + @" ( !T x ) cil managed { } } .class interface public auto ansi abstract I2`1<(class I1`1<!T>) T> implements class I1`1<!T> { .method private hidebysig static int32 'I1<!T>." + opName + @"' ( !T x ) cil managed { .override method int32 class I1`1<!T>::" + opName + @"(!0) IL_0000: ldc.i4.0 IL_0001: ret } } "; var source1 = @" public class C1 : I2<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1<C1>.explicit operator int(C1)' // public class C1 : I2<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C1>").WithArguments("C1", "I1<C1>." + op + " operator int(C1)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_13([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static " + op + @" operator C1<T>(T x); } public partial class C1<T> { public static " + op + @" operator C1<T>(T x) => default; } public class C2 : C1<C2>, I1<C2> { } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var i1 = c2.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.False(c2M01.HasSpecialName); Assert.Equal("C1<C2> C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.False(c1M01.HasRuntimeSpecialName); Assert.True(c1M01.HasSpecialName); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Conversion, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.True(c2M01.HasSpecialName); Assert.Equal("C1<C2> C1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1<C2>." + opName + "(C2)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""C1<C2> C1<C2>." + opName + @"(C2)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_14([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static " + op + @" operator int(C1 x) => default; } class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("System.Int32 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("System.Int32 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.Equal("System.Int32 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("System.Int32 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int C1." + opName + @"(C1)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_15([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static " + op + @" operator C1<T>(T x); abstract static " + op + @" operator T(int x); } public partial class C1<T> { public static " + op + @" operator C1<T>(T x) => default; } public class C2 : C1<C2>, I1<C2> { static " + op + @" I1<C2>.operator C2(int x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = ConversionOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().First(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C1<C2> C1<C2>." + opName + "(C2 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<C2> C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Equal(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().ElementAt(1); var c2M02 = c3.BaseType().GetMembers("I1<C2>." + opName).OfType<MethodSymbol>().First(); Assert.Equal("C2 C2.I1<C2>." + opName + "(System.Int32 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_18([CombinatorialValues("implicit", "explicit")] string op, bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static " + op + @" operator U(C1<T, U> x) => default; "; var nonGeneric = @" public static " + op + @" operator int(C1<T, U> x) => default; "; var source1 = @" public interface I1<T, U> where T : I1<T, U> { abstract static " + op + @" operator U(T x); } public class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>." + opName + "(C1<T, U> x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>." + opName + "(C1<T, U> x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_20([CombinatorialValues("implicit", "explicit")] string op, bool genericFirst) { // Same as ImplementAbstractStaticConversionOperator_18 only implementation is explicit in source. var generic = @" static " + op + @" I1<C1<T, U>, U>.operator U(C1<T, U> x) => default; "; var nonGeneric = @" public static " + op + @" operator int(C1<T, U> x) => default; "; var source1 = @" public interface I1<T, U> where T : I1<T, U> { abstract static " + op + @" operator U(T x); } public class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>.I1<C1<T, U>, U>." + opName + "(C1<T, U> x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class C1 : I1<C1> { static " + op + @" I1<C1>.operator int(C1 x) => default; } class C2 : I1<C2> { private static " + op + @" I1<C2>.operator int(C2 x) => default; } class C3 : I1<C3> { protected static " + op + @" I1<C3>.operator int(C3 x) => default; } class C4 : I1<C4> { internal static " + op + @" I1<C4>.operator int(C4 x) => default; } class C5 : I1<C5> { protected internal static " + op + @" I1<C5>.operator int(C5 x) => default; } class C6 : I1<C6> { private protected static " + op + @" I1<C6>.operator int(C6 x) => default; } class C7 : I1<C7> { public static " + op + @" I1<C7>.operator int(C7 x) => default; } class C9 : I1<C9> { async static " + op + @" I1<C9>.operator int(C9 x) => default; } class C10 : I1<C10> { unsafe static " + op + @" I1<C10>.operator int(C10 x) => default; } class C11 : I1<C11> { static readonly " + op + @" I1<C11>.operator int(C11 x) => default; } class C12 : I1<C12> { extern static " + op + @" I1<C12>.operator int(C12 x); } class C13 : I1<C13> { abstract static " + op + @" I1<C13>.operator int(C13 x) => default; } class C14 : I1<C14> { virtual static " + op + @" I1<C14>.operator int(C14 x) => default; } class C15 : I1<C15> { sealed static " + op + @" I1<C15>.operator int(C15 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.WRN_ExternMethodNoImplementation).Verify( // (16,45): error CS0106: The modifier 'private' is not valid for this item // private static explicit I1<C2>.operator int(C2 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("private").WithLocation(16, 45), // (22,47): error CS0106: The modifier 'protected' is not valid for this item // protected static explicit I1<C3>.operator int(C3 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("protected").WithLocation(22, 47), // (28,46): error CS0106: The modifier 'internal' is not valid for this item // internal static explicit I1<C4>.operator int(C4 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("internal").WithLocation(28, 46), // (34,56): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static explicit I1<C5>.operator int(C5 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("protected internal").WithLocation(34, 56), // (40,55): error CS0106: The modifier 'private protected' is not valid for this item // private protected static explicit I1<C6>.operator int(C6 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("private protected").WithLocation(40, 55), // (46,44): error CS0106: The modifier 'public' is not valid for this item // public static explicit I1<C7>.operator int(C7 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("public").WithLocation(46, 44), // (52,43): error CS0106: The modifier 'async' is not valid for this item // async static explicit I1<C9>.operator int(C9 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("async").WithLocation(52, 43), // (64,47): error CS0106: The modifier 'readonly' is not valid for this item // static readonly explicit I1<C11>.operator int(C11 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("readonly").WithLocation(64, 47), // (76,47): error CS0106: The modifier 'abstract' is not valid for this item // abstract static explicit I1<C13>.operator int(C13 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(76, 47), // (82,46): error CS0106: The modifier 'virtual' is not valid for this item // virtual static explicit I1<C14>.operator int(C14 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("virtual").WithLocation(82, 46), // (88,45): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit I1<C15>.operator int(C15 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(88, 45) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : struct, I1<T> { abstract static " + op + @" operator int(T x); } class C1 { static " + op + @" I1<int>.operator int(int x) => default; } class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,21): error CS0540: 'C1.I1<int>.implicit operator int(int)': containing type does not implement interface 'I1<int>' // static implicit I1<int>.operator int(int x) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<int>").WithArguments("C1.I1<int>." + op + " operator int(int)", "I1<int>").WithLocation(9, 21), // (9,21): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion from 'int' to 'I1<int>'. // static implicit I1<int>.operator int(int x) => default; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "I1<int>").WithArguments("I1<T>", "I1<int>", "T", "int").WithLocation(9, 21), // (12,7): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // class C2 : I1<C2> Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 7), // (14,21): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static implicit I1<C2>.operator int(C2 x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 21) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { string cast = (op == "explicit" ? "(int)" : ""); var source1 = @" interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); static int M02(I1<T> x) { return " + cast + @"x; } int M03(I1<T> y) { return " + cast + @"y; } } class Test<T> where T : I1<T> { static int MT1(I1<T> a) { return " + cast + @"a; } static void MT2() { _ = (System.Linq.Expressions.Expression<System.Func<T, int>>)((T b) => " + cast + @"b); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (8,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)x; Diagnostic(error, cast + "x").WithArguments("I1<T>", "int").WithLocation(8, 16), // (13,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)y; Diagnostic(error, cast + "y").WithArguments("I1<T>", "int").WithLocation(13, 16), // (21,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)a; Diagnostic(error, cast + "a").WithArguments("I1<T>", "int").WithLocation(21, 16), // (26,80): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Func<T, int>>)((T b) => (int)b); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, cast + "b").WithLocation(26, 80) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1 { abstract static implicit operator bool(I1 x); static void M02((int, C<I1>) x) { _ = x " + op + @" x; } void M03((int, C<I1>) y) { _ = y " + op + @" y; } } class Test { static void MT1((int, C<I1>) a) { _ = a " + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b " + op + @" b).ToString()); } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0552: 'I1.implicit operator bool(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator bool(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "bool").WithArguments("I1.implicit operator bool(I1)").WithLocation(4, 39), // (9,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = x == x; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x " + op + " x").WithArguments("I1", "bool").WithLocation(9, 13), // (14,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = y == y; Diagnostic(ErrorCode.ERR_NoImplicitConv, "y " + op + " y").WithArguments("I1", "bool").WithLocation(14, 13), // (22,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = a == a; Diagnostic(ErrorCode.ERR_NoImplicitConv, "a " + op + " a").WithArguments("I1", "bool").WithLocation(22, 13), // (27,98): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(27, 98) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_03([CombinatorialValues("implicit", "explicit")] string op) { string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class Test { static int M02<T, U>(T x) where T : U where U : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int? M03<T, U>(T y) where T : U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"y; } static int? M04<T, U>(T? y) where T : struct, U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"y; } static int? M05<T, U>() where T : struct, U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"(T?)new T(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 23 (0x17) .maxstack 1 .locals init (int? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: newobj ""int?..ctor(int)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (T? V_0, int? V_1, int? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""int?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""int I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""int?..ctor(int)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 27 (0x1b) .maxstack 1 .locals init (int? V_0) IL_0000: nop IL_0001: call ""T System.Activator.CreateInstance<T>()"" IL_0006: constrained. ""T"" IL_000c: call ""int I1<T>." + metadataName + @"(T)"" IL_0011: newobj ""int?..ctor(int)"" IL_0016: stloc.0 IL_0017: br.s IL_0019 IL_0019: ldloc.0 IL_001a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""int I1<T>." + metadataName + @"(T)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""int I1<T>." + metadataName + @"(T)"" IL_000c: newobj ""int?..ctor(int)"" IL_0011: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (T? V_0, int? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""int?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""int I1<T>." + metadataName + @"(T)"" IL_0027: newobj ""int?..ctor(int)"" IL_002c: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 22 (0x16) .maxstack 1 IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: constrained. ""T"" IL_000b: call ""int I1<T>." + metadataName + @"(T)"" IL_0010: newobj ""int?..ctor(int)"" IL_0015: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().First(); Assert.Equal("return " + (needCast ? "(int)" : "") + @"x;", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return " + (needCast ? "(int)" : "") + @"x;') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 I1<T>." + metadataName + @"(T x)) (OperationKind.Conversion, Type: System.Int32" + (needCast ? "" : ", IsImplicit") + @") (Syntax: '" + (needCast ? "(int)" : "") + @"x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 I1<T>." + metadataName + @"(T x)) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool (T x); } class Test { static void M02<T, U>((int, C<T>) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_Implicit(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.0 IL_0032: pop IL_0033: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_Implicit(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.1 IL_0032: pop IL_0033: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_Implicit(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.0 IL_0031: pop IL_0032: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_Implicit(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.1 IL_0031: pop IL_0032: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_04([CombinatorialValues("implicit", "explicit")] string op) { bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = @" class Test { static int M02<T>(T x) where T : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,16): error CS8919: Target runtime doesn't support static abstract members in interfaces. // return (int)x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, (needCast ? "(int)" : "") + "x").WithLocation(6, 16) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(12, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool(T x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (21,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static implicit operator bool(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "bool").WithLocation(21, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_06([CombinatorialValues("implicit", "explicit")] string op) { bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = @" class Test { static int M02<T>(T x) where T : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,16): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // return x; Diagnostic(ErrorCode.ERR_FeatureInPreview, (needCast ? "(int)" : "") + "x").WithArguments("static abstract members in interfaces").WithLocation(6, 16) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(12, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool(T x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (21,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator bool(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "bool").WithArguments("abstract", "9.0", "preview").WithLocation(21, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_07([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_03 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } class Test { static T M02<T, U>(int x) where T : U where U : I1<T> { return " + (needCast ? "(T)" : "") + @"x; } static T? M03<T, U>(int y) where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"y; } static T? M04<T, U>(int? y) where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"y; } static T? M05<T, U>() where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"(T?)0; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(int)", @" { // Code size 23 (0x17) .maxstack 1 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: newobj ""T?..ctor(T)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (int? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool int?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly int int?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(int)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 23 (0x17) .maxstack 1 .locals init (T? V_0) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: newobj ""T?..ctor(T)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: newobj ""T?..ctor(T)"" IL_0011: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (int? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool int?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly int int?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""T I1<T>." + metadataName + @"(int)"" IL_0027: newobj ""T?..ctor(T)"" IL_002c: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: newobj ""T?..ctor(T)"" IL_0011: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().First(); Assert.Equal("return " + (needCast ? "(T)" : "") + @"x;", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return " + (needCast ? "(T)" : "") + @"x;') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: T I1<T>." + metadataName + @"(System.Int32 x)) (OperationKind.Conversion, Type: T" + (needCast ? "" : ", IsImplicit") + @") (Syntax: '" + (needCast ? "(T)" : "") + @"x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: T I1<T>." + metadataName + @"(System.Int32 x)) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_08([CombinatorialValues("implicit", "explicit")] string op) { // Don't look in interfaces of the effective base string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class C1<T> : I1<C1<T>> { static " + op + @" I1<C1<T>>.operator int(C1<T> x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int M03<T>(C1<T> y) where T : I1<C1<T>> { return " + (needCast ? "(int)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (16,16): error CS0030: Cannot convert type 'T' to 'int' // return (int)x; Diagnostic(error, (needCast ? "(int)" : "") + "x").WithArguments("T", "int").WithLocation(16, 16), // (21,16): error CS0030: Cannot convert type 'C1<T>' to 'int' // return (int)y; Diagnostic(error, (needCast ? "(int)" : "") + "y").WithArguments("C1<T>", "int").WithLocation(21, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_09([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_08 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } class C1<T> : I1<C1<T>> { static " + op + @" I1<C1<T>>.operator C1<T>(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1<T> { return " + (needCast ? "(T)" : "") + @"x; } static C1<T> M03<T>(int y) where T : I1<C1<T>> { return " + (needCast ? "(C1<T>)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (16,16): error CS0030: Cannot convert type 'int' to 'T' // return (T)x; Diagnostic(error, (needCast ? "(T)" : "") + "x").WithArguments("int", "T").WithLocation(16, 16), // (21,16): error CS0030: Cannot convert type 'int' to 'C1<T>' // return (C1<T>)y; Diagnostic(error, (needCast ? "(C1<T>)" : "") + "y").WithArguments("int", "C1<T>").WithLocation(21, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_10([CombinatorialValues("implicit", "explicit")] string op) { // Look in derived interfaces string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public interface I2<T> : I1<T> where T : I1<T> {} class Test { static int M02<T, U>(T x) where T : U where U : I2<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_11([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_10 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } public interface I2<T> : I1<T> where T : I1<T> {} class Test { static T M02<T, U>(int x) where T : U where U : I2<T> { return " + (needCast ? "(T)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_12([CombinatorialValues("implicit", "explicit")] string op) { // Ignore duplicate candidates string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T, U> where T : I1<T, U> where U : I1<T, U> { abstract static " + op + @" operator U(T x); } class Test { static U M02<T, U>(T x) where T : I1<T, U> where U : I1<T, U> { return " + (needCast ? "(U)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (U V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""U I1<T, U>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_13([CombinatorialValues("implicit", "explicit")] string op) { // Look in effective base string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public class C1<T> { public static " + op + @" operator int(C1<T> x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: call ""int C1<T>." + metadataName + @"(C1<T>)"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Fact] public void ConsumeAbstractConversionOperator_14() { // Same as ConsumeAbstractConversionOperator_13 only direction of conversion is flipped var source1 = @" public class C1<T> { public static explicit operator C1<T>(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1<T> { return (T)x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""C1<T> C1<T>.op_Explicit(int)"" IL_0007: unbox.any ""T"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_15([CombinatorialValues("implicit", "explicit")] string op) { // If there is a non-trivial class constraint, interfaces are not looked at. string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C1 : I1<C1> { public static " + op + @" operator int(C1 x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1, I1<C1> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: call ""int C1." + metadataName + @"(C1)"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Fact] public void ConsumeAbstractConversionOperator_16() { // Same as ConsumeAbstractConversionOperator_15 only direction of conversion is flipped var source1 = @" public interface I1<T> where T : I1<T> { abstract static explicit operator T(int x); } public class C1 : I1<C1> { public static explicit operator C1(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1, I1<C1> { return (T)x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""C1 C1.op_Explicit(int)"" IL_0007: unbox.any ""T"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_17([CombinatorialValues("implicit", "explicit")] string op) { // If there is a non-trivial class constraint, interfaces are not looked at. bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C1 { } class Test { static int M02<T, U>(T x) where T : U where U : C1, I1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int M03<T, U>(T y) where T : U where U : I1<T> { return " + (needCast ? "(int)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (15,16): error CS0030: Cannot convert type 'T' to 'int' // return (int)x; Diagnostic((op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv), (needCast ? "(int)" : "") + "x").WithArguments("T", "int").WithLocation(15, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_18([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_17 only direction of conversion is flipped bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } public class C1 { } class Test { static T M02<T, U>(int x) where T : U where U : C1, I1<T> { return " + (needCast ? "(T)" : "") + @"x; } static T M03<T, U>(int y) where T : U where U : I1<T> { return " + (needCast ? "(T)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (15,16): error CS0030: Cannot convert type 'int' to 'T' // return (T)x; Diagnostic((op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv), (needCast ? "(T)" : "") + "x").WithArguments("int", "T").WithLocation(15, 16) ); } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_01() { var source1 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } public class Derived : Base<int>, Interface<int, int> { } class YetAnother : Interface<int, int> { public static void Method(int i) { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var b = module.GlobalNamespace.GetTypeMember("Base"); var bI = b.Interfaces().Single(); var biMethods = bI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", biMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", biMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", biMethods[2].OriginalDefinition.ToTestDisplayString()); var bM1 = b.FindImplementationForInterfaceMember(biMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", bM1.ToTestDisplayString()); var bM2 = b.FindImplementationForInterfaceMember(biMethods[1]); Assert.Equal("void Base<T>.Method(T i)", bM2.ToTestDisplayString()); Assert.Same(bM2, b.FindImplementationForInterfaceMember(biMethods[2])); var bM1Impl = ((MethodSymbol)bM1).ExplicitInterfaceImplementations; var bM2Impl = ((MethodSymbol)bM2).ExplicitInterfaceImplementations; if (module is PEModuleSymbol) { Assert.Equal(biMethods[0], bM1Impl.Single()); Assert.Equal(2, bM2Impl.Length); Assert.Equal(biMethods[1], bM2Impl[0]); Assert.Equal(biMethods[2], bM2Impl[1]); } else { Assert.Empty(bM1Impl); Assert.Empty(bM2Impl); } var d = module.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Same(bM1, dM1.OriginalDefinition); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Same(bM2, dM2.OriginalDefinition); Assert.Same(bM2, d.FindImplementationForInterfaceMember(diMethods[2]).OriginalDefinition); } } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_02() { var source0 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); var source1 = @" public class Derived : Base<int>, Interface<int, int> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation0.EmitToImageReference() }); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var d = module.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", dM1.OriginalDefinition.ToTestDisplayString()); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Equal("void Base<T>.Method(T i)", dM2.OriginalDefinition.ToTestDisplayString()); Assert.Same(dM2, d.FindImplementationForInterfaceMember(diMethods[2])); var dM1Impl = ((MethodSymbol)dM1).ExplicitInterfaceImplementations; var dM2Impl = ((MethodSymbol)dM2).ExplicitInterfaceImplementations; Assert.Equal(diMethods[0], dM1Impl.Single()); Assert.Equal(2, dM2Impl.Length); Assert.Equal(diMethods[1], dM2Impl[0]); Assert.Equal(diMethods[2], dM2Impl[1]); } } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_03() { var source0 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateEmptyCompilation("").ToMetadataReference() }); compilation0.VerifyDiagnostics(); var source1 = @" public class Derived : Base<int>, Interface<int, int> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation0.ToMetadataReference() }); var d = compilation1.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.IsType<RetargetingNamedTypeSymbol>(dB.OriginalDefinition); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", dM1.OriginalDefinition.ToTestDisplayString()); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Equal("void Base<T>.Method(T i)", dM2.OriginalDefinition.ToTestDisplayString()); Assert.Equal(dM2, d.FindImplementationForInterfaceMember(diMethods[2])); var dM1Impl = ((MethodSymbol)dM1).ExplicitInterfaceImplementations; var dM2Impl = ((MethodSymbol)dM2).ExplicitInterfaceImplementations; Assert.Empty(dM1Impl); Assert.Empty(dM2Impl); } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_04() { var source2 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } class Other : Interface<int, int> { static void Interface<int, int>.Method(int i) { } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (9,15): error CS0535: 'Other' does not implement interface member 'Interface<int, int>.Method(int)' // class Other : Interface<int, int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<int, int>").WithArguments("Other", "Interface<int, int>.Method(int)").WithLocation(9, 15), // (9,15): error CS0535: 'Other' does not implement interface member 'Interface<int, int>.Method(int)' // class Other : Interface<int, int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<int, int>").WithArguments("Other", "Interface<int, int>.Method(int)").WithLocation(9, 15), // (11,37): warning CS0473: Explicit interface implementation 'Other.Interface<int, int>.Method(int)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // static void Interface<int, int>.Method(int i) { } Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Other.Interface<int, int>.Method(int)").WithLocation(11, 37) ); } [Fact] public void UnmanagedCallersOnly_01() { var source2 = @" using System.Runtime.InteropServices; public interface I1 { [UnmanagedCallersOnly] abstract static void M1(); [UnmanagedCallersOnly] abstract static int operator +(I1 x); [UnmanagedCallersOnly] abstract static int operator +(I1 x, I1 y); } public interface I2<T> where T : I2<T> { [UnmanagedCallersOnly] abstract static implicit operator int(T i); [UnmanagedCallersOnly] abstract static explicit operator T(int i); } "; var compilation2 = CreateCompilation(new[] { source2, UnmanagedCallersOnlyAttributeDefinition }, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (6,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static void M1(); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(6, 6), // (7,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static int operator +(I1 x); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 6), // (8,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static int operator +(I1 x, I1 y); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(8, 6), // (13,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static implicit operator int(T i); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(13, 6), // (14,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static explicit operator T(int i); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(14, 6) ); } [Fact] [WorkItem(54113, "https://github.com/dotnet/roslyn/issues/54113")] public void UnmanagedCallersOnly_02() { var ilSource = @" .class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72 69 74 65 64 00 ) .field public class [mscorlib]System.Type[] CallConvs .field public string EntryPoint .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void M1 () cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static int32 op_UnaryPlus ( class I1 x ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static int32 op_Addition ( class I1 x, class I1 y ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } } .class interface public auto ansi abstract I2`1<(class I2`1<!T>) T> { .method public hidebysig specialname abstract virtual static int32 op_Implicit ( !T i ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static !T op_Explicit ( int32 i ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } } "; var source1 = @" class Test { static void M02<T>(T x, T y) where T : I1 { T.M1(); _ = +x; _ = x + y; } static int M03<T>(T x) where T : I2<T> { _ = (T)x; return x; } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); // Conversions aren't flagged due to https://github.com/dotnet/roslyn/issues/54113. compilation1.VerifyDiagnostics( // (6,11): error CS0570: 'I1.M1()' is not supported by the language // T.M1(); Diagnostic(ErrorCode.ERR_BindToBogus, "M1").WithArguments("I1.M1()").WithLocation(6, 11), // (7,13): error CS0570: 'I1.operator +(I1)' is not supported by the language // _ = +x; Diagnostic(ErrorCode.ERR_BindToBogus, "+x").WithArguments("I1.operator +(I1)").WithLocation(7, 13), // (8,13): error CS0570: 'I1.operator +(I1, I1)' is not supported by the language // _ = x + y; Diagnostic(ErrorCode.ERR_BindToBogus, "x + y").WithArguments("I1.operator +(I1, I1)").WithLocation(8, 13) ); } [Fact] public void UnmanagedCallersOnly_03() { var source2 = @" using System.Runtime.InteropServices; public interface I1<T> where T : I1<T> { abstract static void M1(); abstract static int operator +(T x); abstract static int operator +(T x, T y); abstract static implicit operator int(T i); abstract static explicit operator T(int i); } class C : I1<C> { [UnmanagedCallersOnly] public static void M1() {} [UnmanagedCallersOnly] public static int operator +(C x) => 0; [UnmanagedCallersOnly] public static int operator +(C x, C y) => 0; [UnmanagedCallersOnly] public static implicit operator int(C i) => 0; [UnmanagedCallersOnly] public static explicit operator C(int i) => null; } "; var compilation2 = CreateCompilation(new[] { source2, UnmanagedCallersOnlyAttributeDefinition }, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (15,47): error CS8932: 'UnmanagedCallersOnly' method 'C.M1()' cannot implement interface member 'I1<C>.M1()' in type 'C' // [UnmanagedCallersOnly] public static void M1() {} Diagnostic(ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod, "M1").WithArguments("C.M1()", "I1<C>.M1()", "C").WithLocation(15, 47), // (16,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static int operator +(C x) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(16, 6), // (17,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static int operator +(C x, C y) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(17, 6), // (18,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static implicit operator int(C i) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(18, 6), // (19,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static explicit operator C(int i) => null; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(19, 6) ); } [Fact] public void UnmanagedCallersOnly_04() { var source2 = @" using System.Runtime.InteropServices; public interface I1<T> where T : I1<T> { abstract static void M1(); abstract static int operator +(T x); abstract static int operator +(T x, T y); abstract static implicit operator int(T i); abstract static explicit operator T(int i); } class C : I1<C> { [UnmanagedCallersOnly] static void I1<C>.M1() {} [UnmanagedCallersOnly] static int I1<C>.operator +(C x) => 0; [UnmanagedCallersOnly] static int I1<C>.operator +(C x, C y) => 0; [UnmanagedCallersOnly] static implicit I1<C>.operator int(C i) => 0; [UnmanagedCallersOnly] static explicit I1<C>.operator C(int i) => null; } "; var compilation2 = CreateCompilation(new[] { source2, UnmanagedCallersOnlyAttributeDefinition }, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (15,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static void I1<C>.M1() {} Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(15, 6), // (16,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static int I1<C>.operator +(C x) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(16, 6), // (17,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static int I1<C>.operator +(C x, C y) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(17, 6), // (18,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static implicit I1<C>.operator int(C i) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(18, 6), // (19,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static explicit I1<C>.operator C(int i) => null; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(19, 6) ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; 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.Symbols { public class StaticAbstractMembersInInterfacesTests : CSharpTestBase { [Fact] public void MethodModifiers_01() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } private static void ValidateMethodModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<MethodSymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<MethodSymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<MethodSymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<MethodSymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<MethodSymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<MethodSymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<MethodSymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<MethodSymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<MethodSymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } [Fact] public void MethodModifiers_02() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_03() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_04() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_05() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static void M02() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static void M04() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static void M09() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_06() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static void M02() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static void M04() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static void M09() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void SealedStaticConstructor_01() { var source1 = @" interface I1 { sealed static I1() {} } partial interface I2 { partial sealed static I2(); } partial interface I2 { partial static I2() {} } partial interface I3 { partial static I3(); } partial interface I3 { partial sealed static I3() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,19): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I1").WithArguments("sealed").WithLocation(4, 19), // (9,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I2(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(9, 5), // (9,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I2(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(9, 5), // (9,27): error CS0106: The modifier 'sealed' is not valid for this item // partial sealed static I2(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(9, 27), // (14,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I2() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(14, 5), // (14,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I2() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(14, 5), // (14,20): error CS0111: Type 'I2' already defines a member called 'I2' with the same parameter types // partial static I2() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I2").WithArguments("I2", "I2").WithLocation(14, 20), // (19,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I3(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(19, 5), // (19,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I3(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(19, 5), // (24,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(24, 5), // (24,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(24, 5), // (24,27): error CS0106: The modifier 'sealed' is not valid for this item // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(24, 27), // (24,27): error CS0111: Type 'I3' already defines a member called 'I3' with the same parameter types // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I3").WithArguments("I3", "I3").WithLocation(24, 27) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>(".cctor"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); } [Fact] public void SealedStaticConstructor_02() { var source1 = @" partial interface I2 { sealed static partial I2(); } partial interface I2 { static partial I2() {} } partial interface I3 { static partial I3(); } partial interface I3 { sealed static partial I3() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,19): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // sealed static partial I2(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(4, 19), // (4,27): error CS0501: 'I2.I2()' must declare a body because it is not marked abstract, extern, or partial // sealed static partial I2(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I2").WithArguments("I2.I2()").WithLocation(4, 27), // (4,27): error CS0542: 'I2': member names cannot be the same as their enclosing type // sealed static partial I2(); Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I2").WithArguments("I2").WithLocation(4, 27), // (9,12): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // static partial I2() {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(9, 12), // (9,20): error CS0542: 'I2': member names cannot be the same as their enclosing type // static partial I2() {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I2").WithArguments("I2").WithLocation(9, 20), // (9,20): error CS0111: Type 'I2' already defines a member called 'I2' with the same parameter types // static partial I2() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I2").WithArguments("I2", "I2").WithLocation(9, 20), // (9,20): error CS0161: 'I2.I2()': not all code paths return a value // static partial I2() {} Diagnostic(ErrorCode.ERR_ReturnExpected, "I2").WithArguments("I2.I2()").WithLocation(9, 20), // (14,12): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // static partial I3(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(14, 12), // (14,20): error CS0501: 'I3.I3()' must declare a body because it is not marked abstract, extern, or partial // static partial I3(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I3").WithArguments("I3.I3()").WithLocation(14, 20), // (14,20): error CS0542: 'I3': member names cannot be the same as their enclosing type // static partial I3(); Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I3").WithArguments("I3").WithLocation(14, 20), // (19,19): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(19, 19), // (19,27): error CS0542: 'I3': member names cannot be the same as their enclosing type // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I3").WithArguments("I3").WithLocation(19, 27), // (19,27): error CS0111: Type 'I3' already defines a member called 'I3' with the same parameter types // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I3").WithArguments("I3", "I3").WithLocation(19, 27), // (19,27): error CS0161: 'I3.I3()': not all code paths return a value // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_ReturnExpected, "I3").WithArguments("I3.I3()").WithLocation(19, 27) ); } [Fact] public void AbstractStaticConstructor_01() { var source1 = @" interface I1 { abstract static I1(); } interface I2 { abstract static I2() {} } interface I3 { static I3(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "I1").WithArguments("abstract").WithLocation(4, 21), // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I2() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("abstract").WithLocation(9, 21), // (14,12): error CS0501: 'I3.I3()' must declare a body because it is not marked abstract, extern, or partial // static I3(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I3").WithArguments("I3.I3()").WithLocation(14, 12) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>(".cctor"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); } [Fact] public void PartialSealedStatic_01() { var source1 = @" partial interface I1 { sealed static partial void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Null(m01.PartialImplementationPart); } [Fact] public void PartialSealedStatic_02() { var source1 = @" partial interface I1 { sealed static partial void M01(); } partial interface I1 { sealed static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ValidatePartialSealedStatic_02(compilation1); } private static void ValidatePartialSealedStatic_02(CSharpCompilation compilation1) { compilation1.VerifyDiagnostics(); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialSealedStatic_03() { var source1 = @" partial interface I1 { static partial void M01(); } partial interface I1 { sealed static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ValidatePartialSealedStatic_02(compilation1); } [Fact] public void PartialSealedStatic_04() { var source1 = @" partial interface I1 { sealed static partial void M01(); } partial interface I1 { static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ValidatePartialSealedStatic_02(compilation1); } [Fact] public void PartialAbstractStatic_01() { var source1 = @" partial interface I1 { abstract static partial void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Null(m01.PartialImplementationPart); } [Fact] public void PartialAbstractStatic_02() { var source1 = @" partial interface I1 { abstract static partial void M01(); } partial interface I1 { abstract static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34), // (8,34): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(8, 34), // (8,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(8, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialAbstractStatic_03() { var source1 = @" partial interface I1 { abstract static partial void M01(); } partial interface I1 { static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialAbstractStatic_04() { var source1 = @" partial interface I1 { static partial void M01(); } partial interface I1 { abstract static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,34): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(8, 34), // (8,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(8, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PrivateAbstractStatic_01() { var source1 = @" interface I1 { private abstract static void M01(); private abstract static bool P01 { get; } private abstract static event System.Action E01; private abstract static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0621: 'I1.M01()': virtual or abstract members cannot be private // private abstract static void M01(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "M01").WithArguments("I1.M01()").WithLocation(4, 34), // (5,34): error CS0621: 'I1.P01': virtual or abstract members cannot be private // private abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_VirtualPrivate, "P01").WithArguments("I1.P01").WithLocation(5, 34), // (6,49): error CS0621: 'I1.E01': virtual or abstract members cannot be private // private abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_VirtualPrivate, "E01").WithArguments("I1.E01").WithLocation(6, 49), // (7,40): error CS0558: User-defined operator 'I1.operator +(I1)' must be declared static and public // private abstract static I1 operator+ (I1 x); Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 40) ); } [Fact] public void PropertyModifiers_01() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } private static void ValidatePropertyModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); { var m01 = i1.GetMember<PropertySymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<PropertySymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<PropertySymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<PropertySymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<PropertySymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<PropertySymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<PropertySymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<PropertySymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<PropertySymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<PropertySymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } { var m01 = i1.GetMember<PropertySymbol>("M01").GetMethod; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<PropertySymbol>("M02").GetMethod; Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<PropertySymbol>("M03").GetMethod; Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<PropertySymbol>("M04").GetMethod; Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<PropertySymbol>("M05").GetMethod; Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<PropertySymbol>("M06").GetMethod; Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<PropertySymbol>("M07").GetMethod; Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<PropertySymbol>("M08").GetMethod; Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<PropertySymbol>("M09").GetMethod; Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<PropertySymbol>("M10").GetMethod; Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } } [Fact] public void PropertyModifiers_02() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_03() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_04() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_05() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static bool M04 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_06() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static bool M04 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void EventModifiers_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event D M01 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 29), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static event D M03 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static event D M07 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static event D M10 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } private static void ValidateEventModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); { var m01 = i1.GetMember<EventSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<EventSymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<EventSymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<EventSymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<EventSymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<EventSymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<EventSymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<EventSymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<EventSymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<EventSymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } foreach (var addAccessor in new[] { true, false }) { var m01 = getAccessor(i1.GetMember<EventSymbol>("M01"), addAccessor); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = getAccessor(i1.GetMember<EventSymbol>("M02"), addAccessor); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = getAccessor(i1.GetMember<EventSymbol>("M03"), addAccessor); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = getAccessor(i1.GetMember<EventSymbol>("M04"), addAccessor); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = getAccessor(i1.GetMember<EventSymbol>("M05"), addAccessor); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = getAccessor(i1.GetMember<EventSymbol>("M06"), addAccessor); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = getAccessor(i1.GetMember<EventSymbol>("M07"), addAccessor); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = getAccessor(i1.GetMember<EventSymbol>("M08"), addAccessor); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = getAccessor(i1.GetMember<EventSymbol>("M09"), addAccessor); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = getAccessor(i1.GetMember<EventSymbol>("M10"), addAccessor); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } static MethodSymbol getAccessor(EventSymbol e, bool addAccessor) { return addAccessor ? e.AddMethod : e.RemoveMethod; } } [Fact] public void EventModifiers_02() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 29), // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static event D M03 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_03() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_04() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_05() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static event D M01 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 29), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (7,28): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static event D M02 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static event D M03 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (13,29): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static event D M04 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static event D M07 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (28,37): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static event D M09 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static event D M10 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_06() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 29), // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (7,28): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static event D M03 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (13,29): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (28,37): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void OperatorModifiers_01() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "9.0", "preview").WithLocation(10, 30), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "9.0", "preview").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "9.0", "preview").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "9.0", "preview").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "9.0", "preview").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } private static void ValidateOperatorModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("op_UnaryPlus"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<MethodSymbol>("op_UnaryNegation"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<MethodSymbol>("op_Increment"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<MethodSymbol>("op_Decrement"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<MethodSymbol>("op_LogicalNot"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<MethodSymbol>("op_OnesComplement"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<MethodSymbol>("op_Addition"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<MethodSymbol>("op_Subtraction"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<MethodSymbol>("op_Multiply"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<MethodSymbol>("op_Division"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } [Fact] public void OperatorModifiers_02() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(4, 32), // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "9.0", "preview").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "9.0", "preview").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "9.0", "preview").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "9.0", "preview").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "9.0", "preview").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_03() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_04() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_05() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-").WithArguments("default interface implementation", "8.0").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "7.3", "preview").WithLocation(10, 30), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "--").WithArguments("default interface implementation", "8.0").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "7.3", "preview").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "7.3", "preview").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "7.3", "preview").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "*").WithArguments("default interface implementation", "8.0").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "7.3", "preview").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_06() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(4, 32), // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-").WithArguments("default interface implementation", "8.0").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "7.3", "preview").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "--").WithArguments("default interface implementation", "8.0").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "7.3", "preview").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "7.3", "preview").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "7.3", "preview").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "*").WithArguments("default interface implementation", "8.0").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "7.3", "preview").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_07() { var source1 = @" public interface I1 { abstract static bool operator== (I1 x, I1 y); abstract static bool operator!= (I1 x, I1 y) {return false;} } public interface I2 { sealed static bool operator== (I2 x, I2 y); sealed static bool operator!= (I2 x, I2 y) {return false;} } public interface I3 { abstract sealed static bool operator== (I3 x, I3 y); abstract sealed static bool operator!= (I3 x, I3 y) {return false;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool operator== (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "7.3", "preview").WithLocation(4, 34), // (6,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "7.3", "preview").WithLocation(6, 34), // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (18,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "7.3", "preview").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "7.3", "preview").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator== (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(4, 34), // (6,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(6, 34), // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (18,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); void validate() { foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I1").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I2").GetMembers()) { Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I3").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } } } [Fact] public void OperatorModifiers_08() { var source1 = @" public interface I1 { abstract static implicit operator int(I1 x); abstract static explicit operator I1(bool x) {return null;} } public interface I2 { sealed static implicit operator int(I2 x); sealed static explicit operator I2(bool x) {return null;} } public interface I3 { abstract sealed static implicit operator int(I3 x); abstract sealed static explicit operator I3(bool x) {return null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "7.3", "preview").WithLocation(4, 39), // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I1").WithArguments("abstract", "7.3", "preview").WithLocation(6, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "7.3", "preview").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I3").WithArguments("abstract", "7.3", "preview").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(4, 39), // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I1").WithArguments("abstract", "9.0", "preview").WithLocation(6, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I3").WithArguments("abstract", "9.0", "preview").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); void validate() { foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I1").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I2").GetMembers()) { Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I3").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } } } [Fact] public void FieldModifiers_01() { var source1 = @" public interface I1 { abstract static int F1; sealed static int F2; abstract int F3; sealed int F4; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,25): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // abstract static int F1; Diagnostic(ErrorCode.ERR_AbstractField, "F1").WithLocation(4, 25), // (5,23): error CS0106: The modifier 'sealed' is not valid for this item // sealed static int F2; Diagnostic(ErrorCode.ERR_BadMemberFlag, "F2").WithArguments("sealed").WithLocation(5, 23), // (6,18): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // abstract int F3; Diagnostic(ErrorCode.ERR_AbstractField, "F3").WithLocation(6, 18), // (6,18): error CS0525: Interfaces cannot contain instance fields // abstract int F3; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F3").WithLocation(6, 18), // (7,16): error CS0106: The modifier 'sealed' is not valid for this item // sealed int F4; Diagnostic(ErrorCode.ERR_BadMemberFlag, "F4").WithArguments("sealed").WithLocation(7, 16), // (7,16): error CS0525: Interfaces cannot contain instance fields // sealed int F4; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F4").WithLocation(7, 16) ); } [Fact] public void ExternAbstractStatic_01() { var source1 = @" interface I1 { extern abstract static void M01(); extern abstract static bool P01 { get; } extern abstract static event System.Action E01; extern abstract static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0180: 'I1.M01()' cannot be both extern and abstract // extern abstract static void M01(); Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M01").WithArguments("I1.M01()").WithLocation(4, 33), // (5,33): error CS0180: 'I1.P01' cannot be both extern and abstract // extern abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P01").WithArguments("I1.P01").WithLocation(5, 33), // (6,48): error CS0180: 'I1.E01' cannot be both extern and abstract // extern abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "E01").WithArguments("I1.E01").WithLocation(6, 48), // (7,39): error CS0180: 'I1.operator +(I1)' cannot be both extern and abstract // extern abstract static I1 operator+ (I1 x); Diagnostic(ErrorCode.ERR_AbstractAndExtern, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 39) ); } [Fact] public void ExternAbstractStatic_02() { var source1 = @" interface I1 { extern abstract static void M01() {} extern abstract static bool P01 { get => false; } extern abstract static event System.Action E01 { add {} remove {} } extern abstract static I1 operator+ (I1 x) => null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0180: 'I1.M01()' cannot be both extern and abstract // extern abstract static void M01() {} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M01").WithArguments("I1.M01()").WithLocation(4, 33), // (5,33): error CS0180: 'I1.P01' cannot be both extern and abstract // extern abstract static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P01").WithArguments("I1.P01").WithLocation(5, 33), // (6,48): error CS0180: 'I1.E01' cannot be both extern and abstract // extern abstract static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "E01").WithArguments("I1.E01").WithLocation(6, 48), // (6,52): error CS8712: 'I1.E01': abstract event cannot use event accessor syntax // extern abstract static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.E01").WithLocation(6, 52), // (7,39): error CS0180: 'I1.operator +(I1)' cannot be both extern and abstract // extern abstract static I1 operator+ (I1 x) => null; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 39) ); } [Fact] public void ExternSealedStatic_01() { var source1 = @" #pragma warning disable CS0626 // Method, operator, or accessor is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. interface I1 { extern sealed static void M01(); extern sealed static bool P01 { get; } extern sealed static event System.Action E01; extern sealed static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void AbstractStaticInClass_01() { var source1 = @" abstract class C1 { public abstract static void M01(); public abstract static bool P01 { get; } public abstract static event System.Action E01; public abstract static C1 operator+ (C1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static void M01(); Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M01").WithArguments("abstract").WithLocation(4, 33), // (5,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P01").WithArguments("abstract").WithLocation(5, 33), // (6,48): error CS0112: A static member cannot be marked as 'abstract' // public abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "E01").WithArguments("abstract").WithLocation(6, 48), // (7,39): error CS0106: The modifier 'abstract' is not valid for this item // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("abstract").WithLocation(7, 39), // (7,39): error CS0501: 'C1.operator +(C1)' must declare a body because it is not marked abstract, extern, or partial // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("C1.operator +(C1)").WithLocation(7, 39) ); } [Fact] public void SealedStaticInClass_01() { var source1 = @" class C1 { sealed static void M01() {} sealed static bool P01 { get => false; } sealed static event System.Action E01 { add {} remove {} } public sealed static C1 operator+ (C1 x) => null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0238: 'C1.M01()' cannot be sealed because it is not an override // sealed static void M01() {} Diagnostic(ErrorCode.ERR_SealedNonOverride, "M01").WithArguments("C1.M01()").WithLocation(4, 24), // (5,24): error CS0238: 'C1.P01' cannot be sealed because it is not an override // sealed static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_SealedNonOverride, "P01").WithArguments("C1.P01").WithLocation(5, 24), // (6,39): error CS0238: 'C1.E01' cannot be sealed because it is not an override // sealed static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_SealedNonOverride, "E01").WithArguments("C1.E01").WithLocation(6, 39), // (7,37): error CS0106: The modifier 'sealed' is not valid for this item // public sealed static C1 operator+ (C1 x) => null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("sealed").WithLocation(7, 37) ); } [Fact] public void AbstractStaticInStruct_01() { var source1 = @" struct C1 { public abstract static void M01(); public abstract static bool P01 { get; } public abstract static event System.Action E01; public abstract static C1 operator+ (C1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static void M01(); Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M01").WithArguments("abstract").WithLocation(4, 33), // (5,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P01").WithArguments("abstract").WithLocation(5, 33), // (6,48): error CS0112: A static member cannot be marked as 'abstract' // public abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "E01").WithArguments("abstract").WithLocation(6, 48), // (7,39): error CS0106: The modifier 'abstract' is not valid for this item // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("abstract").WithLocation(7, 39), // (7,39): error CS0501: 'C1.operator +(C1)' must declare a body because it is not marked abstract, extern, or partial // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("C1.operator +(C1)").WithLocation(7, 39) ); } [Fact] public void SealedStaticInStruct_01() { var source1 = @" struct C1 { sealed static void M01() {} sealed static bool P01 { get => false; } sealed static event System.Action E01 { add {} remove {} } public sealed static C1 operator+ (C1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0238: 'C1.M01()' cannot be sealed because it is not an override // sealed static void M01() {} Diagnostic(ErrorCode.ERR_SealedNonOverride, "M01").WithArguments("C1.M01()").WithLocation(4, 24), // (5,24): error CS0238: 'C1.P01' cannot be sealed because it is not an override // sealed static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_SealedNonOverride, "P01").WithArguments("C1.P01").WithLocation(5, 24), // (6,39): error CS0238: 'C1.E01' cannot be sealed because it is not an override // sealed static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_SealedNonOverride, "E01").WithArguments("C1.E01").WithLocation(6, 39), // (7,37): error CS0106: The modifier 'sealed' is not valid for this item // public sealed static C1 operator+ (C1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("sealed").WithLocation(7, 37) ); } [Fact] public void DefineAbstractStaticMethod_01() { var source1 = @" interface I1 { abstract static void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); } } [Fact] public void DefineAbstractStaticMethod_02() { var source1 = @" interface I1 { abstract static void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 26) ); } [Theory] [InlineData("I1", "+", "(I1 x)")] [InlineData("I1", "-", "(I1 x)")] [InlineData("I1", "!", "(I1 x)")] [InlineData("I1", "~", "(I1 x)")] [InlineData("I1", "++", "(I1 x)")] [InlineData("I1", "--", "(I1 x)")] [InlineData("I1", "+", "(I1 x, I1 y)")] [InlineData("I1", "-", "(I1 x, I1 y)")] [InlineData("I1", "*", "(I1 x, I1 y)")] [InlineData("I1", "/", "(I1 x, I1 y)")] [InlineData("I1", "%", "(I1 x, I1 y)")] [InlineData("I1", "&", "(I1 x, I1 y)")] [InlineData("I1", "|", "(I1 x, I1 y)")] [InlineData("I1", "^", "(I1 x, I1 y)")] [InlineData("I1", "<<", "(I1 x, int y)")] [InlineData("I1", ">>", "(I1 x, int y)")] public void DefineAbstractStaticOperator_01(string type, string op, string paramList) { var source1 = @" interface I1 { abstract static " + type + " operator " + op + " " + paramList + @"; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); } } [Fact] public void DefineAbstractStaticOperator_02() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); abstract static I1 operator > (I1 x, I1 y); abstract static I1 operator < (I1 x, I1 y); abstract static I1 operator >= (I1 x, I1 y); abstract static I1 operator <= (I1 x, I1 y); abstract static I1 operator == (I1 x, I1 y); abstract static I1 operator != (I1 x, I1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(8, count); } } [Theory] [InlineData("I1", "+", "(I1 x)")] [InlineData("I1", "-", "(I1 x)")] [InlineData("I1", "!", "(I1 x)")] [InlineData("I1", "~", "(I1 x)")] [InlineData("I1", "++", "(I1 x)")] [InlineData("I1", "--", "(I1 x)")] [InlineData("I1", "+", "(I1 x, I1 y)")] [InlineData("I1", "-", "(I1 x, I1 y)")] [InlineData("I1", "*", "(I1 x, I1 y)")] [InlineData("I1", "/", "(I1 x, I1 y)")] [InlineData("I1", "%", "(I1 x, I1 y)")] [InlineData("I1", "&", "(I1 x, I1 y)")] [InlineData("I1", "|", "(I1 x, I1 y)")] [InlineData("I1", "^", "(I1 x, I1 y)")] [InlineData("I1", "<<", "(I1 x, int y)")] [InlineData("I1", ">>", "(I1 x, int y)")] public void DefineAbstractStaticOperator_03(string type, string op, string paramList) { var source1 = @" interface I1 { abstract static " + type + " operator " + op + " " + paramList + @"; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator + (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 31 + type.Length) ); } [Fact] public void DefineAbstractStaticOperator_04() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); abstract static I1 operator > (I1 x, I1 y); abstract static I1 operator < (I1 x, I1 y); abstract static I1 operator >= (I1 x, I1 y); abstract static I1 operator <= (I1 x, I1 y); abstract static I1 operator == (I1 x, I1 y); abstract static I1 operator != (I1 x, I1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(4, 35), // (5,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(5, 35), // (6,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator > (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, ">").WithLocation(6, 33), // (7,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator < (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "<").WithLocation(7, 33), // (8,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator >= (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, ">=").WithLocation(8, 33), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator <= (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "<=").WithLocation(9, 33), // (10,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator == (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "==").WithLocation(10, 33), // (11,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator != (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "!=").WithLocation(11, 33) ); } [Fact] public void DefineAbstractStaticConversion_01() { var source1 = @" interface I1<T> where T : I1<T> { abstract static implicit operator int(T x); abstract static explicit operator T(int x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticConversion_03() { var source1 = @" interface I1<T> where T : I1<T> { abstract static implicit operator int(T x); abstract static explicit operator T(int x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 39), // (5,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator T(int x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T").WithLocation(5, 39) ); } [Fact] public void DefineAbstractStaticProperty_01() { var source1 = @" interface I1 { abstract static int P01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var p01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); Assert.True(p01.IsAbstract); Assert.False(p01.IsVirtual); Assert.False(p01.IsSealed); Assert.True(p01.IsStatic); Assert.False(p01.IsOverride); int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticProperty_02() { var source1 = @" interface I1 { abstract static int P01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(4, 31), // (4,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(4, 36) ); } [Fact] public void DefineAbstractStaticEvent_01() { var source1 = @" interface I1 { abstract static event System.Action E01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var e01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); Assert.True(e01.IsAbstract); Assert.False(e01.IsVirtual); Assert.False(e01.IsSealed); Assert.True(e01.IsStatic); Assert.False(e01.IsOverride); int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticEvent_02() { var source1 = @" interface I1 { abstract static event System.Action E01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "E01").WithLocation(4, 41) ); } [Fact] public void ConstraintChecks_01() { var source1 = @" public interface I1 { abstract static void M01(); } public interface I2 : I1 { } public interface I3 : I2 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var source2 = @" class C1<T1> where T1 : I1 { void Test(C1<I2> x) { } } class C2 { void M<T2>() where T2 : I1 {} void Test(C2 x) { x.M<I2>(); } } class C3<T3> where T3 : I2 { void Test(C3<I2> x, C3<I3> y) { } } class C4 { void M<T4>() where T4 : I2 {} void Test(C4 x) { x.M<I2>(); x.M<I3>(); } } class C5<T5> where T5 : I3 { void Test(C5<I3> y) { } } class C6 { void M<T6>() where T6 : I3 {} void Test(C6 x) { x.M<I3>(); } } class C7<T7> where T7 : I1 { void Test(C7<I1> y) { } } class C8 { void M<T8>() where T8 : I1 {} void Test(C8 x) { x.M<I1>(); } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); var expected = new[] { // (4,22): error CS8920: The interface 'I2' cannot be used as type parameter 'T1' in the generic type or method 'C1<T1>'. The constraint interface 'I1' or its base interface has static abstract members. // void Test(C1<I2> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "x").WithArguments("C1<T1>", "I1", "T1", "I2").WithLocation(4, 22), // (15,11): error CS8920: The interface 'I2' cannot be used as type parameter 'T2' in the generic type or method 'C2.M<T2>()'. The constraint interface 'I1' or its base interface has static abstract members. // x.M<I2>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I2>").WithArguments("C2.M<T2>()", "I1", "T2", "I2").WithLocation(15, 11), // (21,22): error CS8920: The interface 'I2' cannot be used as type parameter 'T3' in the generic type or method 'C3<T3>'. The constraint interface 'I2' or its base interface has static abstract members. // void Test(C3<I2> x, C3<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "x").WithArguments("C3<T3>", "I2", "T3", "I2").WithLocation(21, 22), // (21,32): error CS8920: The interface 'I3' cannot be used as type parameter 'T3' in the generic type or method 'C3<T3>'. The constraint interface 'I2' or its base interface has static abstract members. // void Test(C3<I2> x, C3<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C3<T3>", "I2", "T3", "I3").WithLocation(21, 32), // (32,11): error CS8920: The interface 'I2' cannot be used as type parameter 'T4' in the generic type or method 'C4.M<T4>()'. The constraint interface 'I2' or its base interface has static abstract members. // x.M<I2>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I2>").WithArguments("C4.M<T4>()", "I2", "T4", "I2").WithLocation(32, 11), // (33,11): error CS8920: The interface 'I3' cannot be used as type parameter 'T4' in the generic type or method 'C4.M<T4>()'. The constraint interface 'I2' or its base interface has static abstract members. // x.M<I3>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I3>").WithArguments("C4.M<T4>()", "I2", "T4", "I3").WithLocation(33, 11), // (39,22): error CS8920: The interface 'I3' cannot be used as type parameter 'T5' in the generic type or method 'C5<T5>'. The constraint interface 'I3' or its base interface has static abstract members. // void Test(C5<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C5<T5>", "I3", "T5", "I3").WithLocation(39, 22), // (50,11): error CS8920: The interface 'I3' cannot be used as type parameter 'T6' in the generic type or method 'C6.M<T6>()'. The constraint interface 'I3' or its base interface has static abstract members. // x.M<I3>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I3>").WithArguments("C6.M<T6>()", "I3", "T6", "I3").WithLocation(50, 11), // (56,22): error CS8920: The interface 'I1' cannot be used as type parameter 'T7' in the generic type or method 'C7<T7>'. The constraint interface 'I1' or its base interface has static abstract members. // void Test(C7<I1> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C7<T7>", "I1", "T7", "I1").WithLocation(56, 22), // (67,11): error CS8920: The interface 'I1' cannot be used as type parameter 'T8' in the generic type or method 'C8.M<T8>()'. The constraint interface 'I1' or its base interface has static abstract members. // x.M<I1>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I1>").WithArguments("C8.M<T8>()", "I1", "T8", "I1").WithLocation(67, 11) }; compilation2.VerifyDiagnostics(expected); compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.EmitToImageReference() }); compilation2.VerifyDiagnostics(expected); } [Fact] public void ConstraintChecks_02() { var source1 = @" public interface I1 { abstract static void M01(); } public class C : I1 { public static void M01() {} } public struct S : I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var source2 = @" class C1<T1> where T1 : I1 { void Test(C1<C> x, C1<S> y, C1<T1> z) { } } class C2 { public void M<T2>(C2 x) where T2 : I1 { x.M<T2>(x); } void Test(C2 x) { x.M<C>(x); x.M<S>(x); } } class C3<T3> where T3 : I1 { void Test(C1<T3> z) { } } class C4 { void M<T4>(C2 x) where T4 : I1 { x.M<T4>(x); } } class C5<T5> { internal virtual void M<U5>() where U5 : T5 { } } class C6 : C5<I1> { internal override void M<U6>() { base.M<U6>(); } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyEmitDiagnostics(); compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.EmitToImageReference() }); compilation2.VerifyEmitDiagnostics(); } [Fact] public void VarianceSafety_01() { var source1 = @" interface I2<out T1, in T2> { abstract static T1 P1 { get; } abstract static T2 P2 { get; } abstract static T1 P3 { set; } abstract static T2 P4 { set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (5,21): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.P2'. 'T2' is contravariant. // abstract static T2 P2 { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I2<T1, T2>.P2", "T2", "contravariant", "covariantly").WithLocation(5, 21), // (6,21): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.P3'. 'T1' is covariant. // abstract static T1 P3 { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I2<T1, T2>.P3", "T1", "covariant", "contravariantly").WithLocation(6, 21) ); } [Fact] public void VarianceSafety_02() { var source1 = @" interface I2<out T1, in T2> { abstract static T1 M1(); abstract static T2 M2(); abstract static void M3(T1 x); abstract static void M4(T2 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (5,21): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.M2()'. 'T2' is contravariant. // abstract static T2 M2(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I2<T1, T2>.M2()", "T2", "contravariant", "covariantly").WithLocation(5, 21), // (6,29): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.M3(T1)'. 'T1' is covariant. // abstract static void M3(T1 x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I2<T1, T2>.M3(T1)", "T1", "covariant", "contravariantly").WithLocation(6, 29) ); } [Fact] public void VarianceSafety_03() { var source1 = @" interface I2<out T1, in T2> { abstract static event System.Action<System.Func<T1>> E1; abstract static event System.Action<System.Func<T2>> E2; abstract static event System.Action<System.Action<T1>> E3; abstract static event System.Action<System.Action<T2>> E4; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (5,58): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.E2'. 'T2' is contravariant. // abstract static event System.Action<System.Func<T2>> E2; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "E2").WithArguments("I2<T1, T2>.E2", "T2", "contravariant", "covariantly").WithLocation(5, 58), // (6,60): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.E3'. 'T1' is covariant. // abstract static event System.Action<System.Action<T1>> E3; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "E3").WithArguments("I2<T1, T2>.E3", "T1", "covariant", "contravariantly").WithLocation(6, 60) ); } [Fact] public void VarianceSafety_04() { var source1 = @" interface I2<out T2> { abstract static int operator +(I2<T2> x); } interface I3<out T3> { abstract static int operator +(I3<T3> x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,36): error CS1961: Invalid variance: The type parameter 'T2' must be contravariantly valid on 'I2<T2>.operator +(I2<T2>)'. 'T2' is covariant. // abstract static int operator +(I2<T2> x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "I2<T2>").WithArguments("I2<T2>.operator +(I2<T2>)", "T2", "covariant", "contravariantly").WithLocation(4, 36), // (9,36): error CS1961: Invalid variance: The type parameter 'T3' must be contravariantly valid on 'I3<T3>.operator +(I3<T3>)'. 'T3' is covariant. // abstract static int operator +(I3<T3> x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "I3<T3>").WithArguments("I3<T3>.operator +(I3<T3>)", "T3", "covariant", "contravariantly").WithLocation(9, 36) ); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("!")] [InlineData("~")] [InlineData("true")] [InlineData("false")] public void OperatorSignature_01(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x); } interface I13 { static abstract bool operator " + op + @"(I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,26): error CS0562: The parameter of a unary operator must be the containing type // static bool operator +(T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0562: The parameter of a unary operator must be the containing type // static bool operator +(T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T5 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T71 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T8 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T10 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator false(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11)").WithLocation(47, 18), // (51,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator false(int x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [InlineData("++")] [InlineData("--")] public void OperatorSignature_02(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static T1 operator " + op + @"(T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static T2? operator " + op + @"(T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract T3 operator " + op + @"(T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract T4? operator " + op + @"(T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract T5 operator " + op + @"(T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract T71 operator " + op + @"(T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract T8 operator " + op + @"(T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract T10 operator " + op + @"(T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract int operator " + op + @"(int x); } interface I13 { static abstract I13 operator " + op + @"(I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0559: The parameter type for ++ or -- operator must be the containing type // static T1 operator ++(T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecSignature, op).WithLocation(4, 24), // (9,25): error CS0559: The parameter type for ++ or -- operator must be the containing type // static T2? operator ++(T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecSignature, op).WithLocation(9, 25), // (26,37): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T5 operator ++(T5 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(26, 37), // (32,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T71 operator ++(T71 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(32, 34), // (37,33): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T8 operator ++(T8 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(37, 33), // (44,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T10 operator ++(T10 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(44, 34), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator --(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11)").WithLocation(47, 18), // (51,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract int operator ++(int x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(51, 34) ); } [Theory] [InlineData("++")] [InlineData("--")] public void OperatorSignature_03(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static T1 operator " + op + @"(I1<T1> x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static T2? operator " + op + @"(I2<T2> x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract T3 operator " + op + @"(I3<T3> x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract T4? operator " + op + @"(I4<T4> x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract T5 operator " + op + @"(I6 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract T71 operator " + op + @"(I7<T71, T72> x); } interface I8<T8> where T8 : I9<T8> { static abstract T8 operator " + op + @"(I8<T8> x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract T10 operator " + op + @"(I10<T10> x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract int operator " + op + @"(I12 x); } interface I13<T13> where T13 : struct, I13<T13> { static abstract T13? operator " + op + @"(T13 x); } interface I14<T14> where T14 : struct, I14<T14> { static abstract T14 operator " + op + @"(T14? x); } interface I15<T151, T152> where T151 : I15<T151, T152> where T152 : I15<T151, T152> { static abstract T151 operator " + op + @"(T152 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // static T1 operator ++(I1<T1> x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecRetType, op).WithLocation(4, 24), // (9,25): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // static T2? operator ++(I2<T2> x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecRetType, op).WithLocation(9, 25), // (19,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T4? operator ++(I4<T4> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(19, 34), // (26,37): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T5 operator ++(I6 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(26, 37), // (32,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T71 operator ++(I7<T71, T72> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(32, 34), // (37,33): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T8 operator ++(I8<T8> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(37, 33), // (44,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T10 operator ++(I10<T10> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(44, 34), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator ++(I10<T11>)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(I10<T11>)").WithLocation(47, 18), // (51,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract int operator ++(I12 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(51, 34), // (56,35): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T13? operator ++(T13 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(56, 35), // (61,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T14 operator ++(T14? x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(61, 34), // (66,35): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T151 operator ++(T152 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(66, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x, bool y) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x, bool y) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x, bool y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x, bool y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x, bool y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x, bool y); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x, bool y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x, bool y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x, bool y); } interface I13 { static abstract bool operator " + op + @"(I13 x, bool y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators)).Verify( // (4,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(T1 x, bool y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(T2? x, bool y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T5 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T71 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T8 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T10 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator /(T11, bool)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11, bool)").WithLocation(47, 18), // (51,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(int x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_05([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(bool y, T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(bool y, T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(bool y, T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(bool y, T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(bool y, T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(bool y, T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(bool y, T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(bool y, T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(bool y, int x); } interface I13 { static abstract bool operator " + op + @"(bool y, I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators)).Verify( // (4,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(bool y, T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(bool y, T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T5 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T71 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T8 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T10 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator <=(bool, T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(bool, T11)").WithLocation(47, 18), // (51,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, int x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [InlineData("<<")] [InlineData(">>")] public void OperatorSignature_06(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x, int y) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x, int y) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x, int y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x, int y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x, int y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x, int y); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x, int y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x, int y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x, int y); } interface I13 { static abstract bool operator " + op + @"(I13 x, int y); } interface I14 { static abstract bool operator " + op + @"(I14 x, bool y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,26): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // static bool operator <<(T1 x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // static bool operator <<(T2? x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T5 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T71 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T8 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T10 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator >>(T11, int)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11, int)").WithLocation(47, 18), // (51,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(int x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(51, 35), // (61,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(I14 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(61, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_07([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { abstract static " + op + @" operator T1(T1 y); } interface I2<T2> where T2 : I2<T2> { abstract static " + op + @" operator dynamic(T2 y); } interface I3<T3> where T3 : I3<T3> { static abstract " + op + @" operator T3(bool y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract " + op + @" operator T4?(bool y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract " + op + @" operator T5 (bool y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract " + op + @" operator T71 (bool y); } interface I8<T8> where T8 : I9<T8> { static abstract " + op + @" operator T8(bool y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract " + op + @" operator T10(bool y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract " + op + @" operator int(bool y); } interface I13 { static abstract " + op + @" operator I13(bool y); } interface I14<T14> where T14 : I14<T14> { abstract static " + op + @" operator object(T14 y); } class C15 {} class C16 : C15 {} interface I17<T17> where T17 : C15, I17<T17> { abstract static " + op + @" operator C16(T17 y); } interface I18<T18> where T18 : C16, I18<T18> { abstract static " + op + @" operator C15(T18 y); } interface I19<T19_1, T19_2> where T19_1 : I19<T19_1, T19_2>, T19_2 { abstract static " + op + @" operator T19_1(T19_2 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0555: User-defined operator cannot convert a type to itself // abstract static explicit operator T1(T1 y); Diagnostic(ErrorCode.ERR_IdentityConversion, "T1").WithLocation(4, 39), // (9,39): error CS1964: 'I2<T2>.explicit operator dynamic(T2)': user-defined conversions to or from the dynamic type are not allowed // abstract static explicit operator dynamic(T2 y); Diagnostic(ErrorCode.ERR_BadDynamicConversion, "dynamic").WithArguments("I2<T2>." + op + " operator dynamic(T2)").WithLocation(9, 39), // (26,43): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T5 (bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T5").WithLocation(26, 43), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T71 (bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T71").WithLocation(32, 39), // (37,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T8(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T8").WithLocation(37, 39), // (44,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T10(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T10").WithLocation(44, 39), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.explicit operator T11(bool)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>." + op + " operator T11(bool)").WithLocation(47, 18), // (51,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator int(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "int").WithLocation(51, 39), // (56,39): error CS0552: 'I13.explicit operator I13(bool)': user-defined conversions to or from an interface are not allowed // static abstract explicit operator I13(bool y); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I13").WithArguments("I13." + op + " operator I13(bool)").WithLocation(56, 39) ); } [Theory] [CombinatorialData] public void OperatorSignature_08([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { abstract static " + op + @" operator T1(T1 y); } interface I2<T2> where T2 : I2<T2> { abstract static " + op + @" operator T2(dynamic y); } interface I3<T3> where T3 : I3<T3> { static abstract " + op + @" operator bool(T3 y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract " + op + @" operator bool(T4? y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract " + op + @" operator bool(T5 y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract " + op + @" operator bool(T71 y); } interface I8<T8> where T8 : I9<T8> { static abstract " + op + @" operator bool(T8 y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract " + op + @" operator bool(T10 y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract " + op + @" operator bool(int y); } interface I13 { static abstract " + op + @" operator bool(I13 y); } interface I14<T14> where T14 : I14<T14> { abstract static " + op + @" operator T14(object y); } class C15 {} class C16 : C15 {} interface I17<T17> where T17 : C15, I17<T17> { abstract static " + op + @" operator T17(C16 y); } interface I18<T18> where T18 : C16, I18<T18> { abstract static " + op + @" operator T18(C15 y); } interface I19<T19_1, T19_2> where T19_1 : I19<T19_1, T19_2>, T19_2 { abstract static " + op + @" operator T19_2(T19_1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0555: User-defined operator cannot convert a type to itself // abstract static explicit operator T1(T1 y); Diagnostic(ErrorCode.ERR_IdentityConversion, "T1").WithLocation(4, 39), // (9,39): error CS1964: 'I2<T2>.explicit operator T2(dynamic)': user-defined conversions to or from the dynamic type are not allowed // abstract static explicit operator T2(dynamic y); Diagnostic(ErrorCode.ERR_BadDynamicConversion, "T2").WithArguments("I2<T2>." + op + " operator T2(dynamic)").WithLocation(9, 39), // (26,43): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T5 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(26, 43), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T71 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(32, 39), // (37,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T8 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(37, 39), // (44,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T10 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(44, 39), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.explicit operator bool(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>." + op + " operator bool(T11)").WithLocation(47, 18), // (51,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(int y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(51, 39), // (56,39): error CS0552: 'I13.explicit operator bool(I13)': user-defined conversions to or from an interface are not allowed // static abstract explicit operator bool(I13 y); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "bool").WithArguments("I13." + op + " operator bool(I13)").WithLocation(56, 39) ); } [Fact] public void ConsumeAbstractStaticMethod_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { M01(); M04(); } void M03() { this.M01(); this.M04(); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { I1.M01(); x.M01(); I1.M04(); x.M04(); } static void MT2<T>() where T : I1 { T.M03(); T.M04(); T.M00(); T.M05(); _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.M01()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // M01(); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "M01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // this.M01(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // this.M04(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.M01(); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.M01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // x.M01(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // x.M04(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M03(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M04(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M00(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.M05()' is inaccessible due to its protection level // T.M05(); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 11), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.M01()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01()").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticMethod_02() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = nameof(M01); _ = nameof(M04); } void M03() { _ = nameof(this.M01); _ = nameof(this.M04); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = nameof(I1.M01); _ = nameof(x.M01); _ = nameof(I1.M04); _ = nameof(x.M04); } static void MT2<T>() where T : I1 { _ = nameof(T.M03); _ = nameof(T.M04); _ = nameof(T.M00); _ = nameof(T.M05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = nameof(T.M05); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticMethod_03() { var source1 = @" public interface I1 { abstract static void M01(); abstract static void M04(int x); } class Test { static void M02<T, U>() where T : U where U : I1 { T.M01(); } static string M03<T, U>() where T : U where U : I1 { return nameof(T.M01); } static async void M05<T, U>() where T : U where U : I1 { T.M04(await System.Threading.Tasks.Task.FromResult(1)); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 14 (0xe) .maxstack 0 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""void I1.M01()"" IL_000c: nop IL_000d: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""M01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 12 (0xc) .maxstack 0 IL_0000: constrained. ""T"" IL_0006: call ""void I1.M01()"" IL_000b: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""M01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("T.M01()", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IInvocationOperation (virtual void I1.M01()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'T.M01()') Instance Receiver: null Arguments(0) "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("void I1.M01()", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("M01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticMethod_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.M01(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.M01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_05() { var source1 = @" public interface I1 { abstract static I1 Select(System.Func<int, int> p); } class Test { static void M02<T>() where T : I1 { _ = from t in T select t + 1; _ = from t in I1 select t + 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); // https://github.com/dotnet/roslyn/issues/53796: Confirm whether we want to enable the 'from t in T' scenario. compilation1.VerifyDiagnostics( // (11,23): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = from t in T select t + 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(11, 23), // (12,26): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = from t in I1 select t + 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "select t + 1").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.M01(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.M01(); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.M01(); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_01(string prefixOp, string postfixOp) { var source1 = @" interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); abstract static I1<T> operator" + prefixOp + postfixOp + @" (I1<T> x); static void M02(I1<T> x) { _ = " + prefixOp + "x" + postfixOp + @"; } void M03(I1<T> y) { _ = " + prefixOp + "y" + postfixOp + @"; } } class Test<T> where T : I1<T> { static void MT1(I1<T> a) { _ = " + prefixOp + "a" + postfixOp + @"; } static void MT2() { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (" + prefixOp + "b" + postfixOp + @").ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "x" + postfixOp).WithLocation(8, 13), // (13,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "y" + postfixOp).WithLocation(13, 13), // (21,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "a" + postfixOp).WithLocation(21, 13), (prefixOp + postfixOp).Length == 1 ? // (26,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (-b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, prefixOp + "b" + postfixOp).WithLocation(26, 78) : // (26,78): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b--).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, prefixOp + "b" + postfixOp).WithLocation(26, 78) ); } [Theory] [InlineData("+", "", "op_UnaryPlus", "Plus")] [InlineData("-", "", "op_UnaryNegation", "Minus")] [InlineData("!", "", "op_LogicalNot", "Not")] [InlineData("~", "", "op_OnesComplement", "BitwiseNegation")] [InlineData("++", "", "op_Increment", "Increment")] [InlineData("--", "", "op_Decrement", "Decrement")] [InlineData("", "++", "op_Increment", "Increment")] [InlineData("", "--", "op_Decrement", "Decrement")] public void ConsumeAbstractUnaryOperator_03(string prefixOp, string postfixOp, string metadataName, string opKind) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } class Test { static T M02<T, U>(T x) where T : U where U : I1<T> { return " + prefixOp + "x" + postfixOp + @"; } static T? M03<T, U>(T? y) where T : struct, U where U : I1<T> { return " + prefixOp + "y" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 21 (0x15) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: dup IL_000e: starg.s V_0 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: dup IL_002f: starg.s V_0 IL_0031: stloc.2 IL_0032: br.s IL_0034 IL_0034: ldloc.2 IL_0035: ret } "); break; case ("", "++"): case ("", "--"): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 21 (0x15) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: dup IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T)"" IL_000e: starg.s V_0 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: dup IL_0003: stloc.0 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: brtrue.s IL_0018 IL_000d: ldloca.s V_1 IL_000f: initobj ""T?"" IL_0015: ldloc.1 IL_0016: br.s IL_002f IL_0018: ldloca.s V_0 IL_001a: call ""readonly T T?.GetValueOrDefault()"" IL_001f: constrained. ""T"" IL_0025: call ""T I1<T>." + metadataName + @"(T)"" IL_002a: newobj ""T?..ctor(T)"" IL_002f: starg.s V_0 IL_0031: stloc.2 IL_0032: br.s IL_0034 IL_0034: ldloc.2 IL_0035: ret } "); break; default: verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); break; } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(T)"" IL_000c: dup IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0016 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: br.s IL_002d IL_0016: ldloca.s V_0 IL_0018: call ""readonly T T?.GetValueOrDefault()"" IL_001d: constrained. ""T"" IL_0023: call ""T I1<T>." + metadataName + @"(T)"" IL_0028: newobj ""T?..ctor(T)"" IL_002d: dup IL_002e: starg.s V_0 IL_0030: ret } "); break; case ("", "++"): case ("", "--"): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: dup IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: starg.s V_0 IL_0030: ret } "); break; default: verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(T)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""T I1<T>." + metadataName + @"(T)"" IL_0027: newobj ""T?..ctor(T)"" IL_002c: ret } "); break; } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = postfixOp != "" ? (ExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().First() : tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().First(); Assert.Equal(prefixOp + "x" + postfixOp, node.ToString()); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): case ("", "++"): case ("", "--"): VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IIncrementOrDecrementOperation (" + (prefixOp != "" ? "Prefix" : "Postfix") + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x)) (OperationKind." + opKind + @", Type: T) (Syntax: '" + prefixOp + "x" + postfixOp + @"') Target: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); break; default: VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IUnaryOperation (UnaryOperatorKind." + opKind + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x)) (OperationKind.Unary, Type: T) (Syntax: '" + prefixOp + "x" + postfixOp + @"') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); break; } } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_04(string prefixOp, string postfixOp) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1<T> { _ = " + prefixOp + "x" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = -x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, prefixOp + "x" + postfixOp).WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator- (T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, prefixOp + postfixOp).WithLocation(12, 31) ); } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_06(string prefixOp, string postfixOp) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1<T> { _ = " + prefixOp + "x" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = -x; Diagnostic(ErrorCode.ERR_FeatureInPreview, prefixOp + "x" + postfixOp).WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,31): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator- (T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, prefixOp + postfixOp).WithArguments("abstract", "9.0", "preview").WithLocation(12, 31) ); } [Fact] public void ConsumeAbstractTrueOperator_01() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); static void M02(I1 x) { _ = x ? true : false; } void M03(I1 y) { _ = y ? true : false; } } class Test { static void MT1(I1 a) { _ = a ? true : false; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b ? true : false).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x").WithLocation(9, 13), // (14,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y").WithLocation(14, 13), // (22,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a").WithLocation(22, 13), // (27,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b ? true : false).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b").WithLocation(27, 78) ); } [Fact] public void ConsumeAbstractTrueOperator_03() { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator true (T x); abstract static bool operator false (T x); } class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>.op_True(T)"" IL_000d: brtrue.s IL_0011 IL_000f: br.s IL_0011 IL_0011: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""bool I1<T>.op_True(T)"" IL_000c: pop IL_000d: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalExpressionSyntax>().First(); Assert.Equal("x ? true : false", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IConditionalOperation (OperationKind.Conditional, Type: System.Boolean) (Syntax: 'x ? true : false') Condition: IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean I1<T>.op_True(T x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') WhenTrue: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') WhenFalse: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') "); } [Fact] public void ConsumeAbstractTrueOperator_04() { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1 { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(12, 35), // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(13, 35) ); } [Fact] public void ConsumeAbstractTrueOperator_06() { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1 { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(12, 35), // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); static void M02((int, C<I1>) x) { _ = x " + op + @" x; } void M03((int, C<I1>) y) { _ = y " + op + @" y; } } class Test { static void MT1((int, C<I1>) a) { _ = a " + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b " + op + @" b).ToString()); } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x == x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " x").WithLocation(9, 13), // (14,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y == y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " y").WithLocation(14, 13), // (22,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a == a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " a").WithLocation(22, 13), // (27,98): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(27, 98) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator true (T x); abstract static bool operator false (T x); } class Test { static void M02<T, U>((int, C<T>) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 55 (0x37) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0034 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_False(T)"" IL_002f: ldc.i4.0 IL_0030: ceq IL_0032: br.s IL_0035 IL_0034: ldc.i4.0 IL_0035: pop IL_0036: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_True(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.1 IL_0032: pop IL_0033: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0033 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_False(T)"" IL_002e: ldc.i4.0 IL_002f: ceq IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: pop IL_0035: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_True(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.1 IL_0031: pop IL_0032: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1 { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (21,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(21, 35), // (22,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(22, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1 { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (21,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(21, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" partial interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); static void M02(I1 x) { _ = x " + op + @" 1; } void M03(I1 y) { _ = y " + op + @" 2; } } class Test { static void MT1(I1 a) { _ = a " + op + @" 3; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + @" 4).ToString()); } } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator" + matchingOp + @" (I1 x, int y); } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x - 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " 1").WithLocation(8, 13), // (13,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y - 2; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " 2").WithLocation(13, 13), // (21,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a - 3; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " 3").WithLocation(21, 13), // (26,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b - 4).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b " + op + " 4").WithLocation(26, 78) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_01(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" static void M02(I1 x) { _ = x " + op + op + @" x; } void M03(I1 y) { _ = y " + op + op + @" y; } } class Test { static void MT1(I1 a) { _ = a " + op + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + op + @" b).ToString()); } static void MT3(I1 b, dynamic c) { _ = b " + op + op + @" c; } "; if (!success) { source1 += @" static void MT4<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T, dynamic>>)((T d, dynamic e) => (d " + op + op + @" e).ToString()); } "; } source1 += @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); if (success) { Assert.False(binaryIsAbstract); Assert.False(op == "&" ? falseIsAbstract : trueIsAbstract); var binaryMetadataName = op == "&" ? "op_BitwiseAnd" : "op_BitwiseOr"; var unaryMetadataName = op == "&" ? "op_False" : "op_True"; var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.MT1(I1)", @" { // Code size 22 (0x16) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0009: brtrue.s IL_0015 IL_000b: ldloc.0 IL_000c: ldarg.0 IL_000d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0012: pop IL_0013: br.s IL_0015 IL_0015: ret } "); if (op == "&") { verifier.VerifyIL("Test.MT3(I1, dynamic)", @" { // Code size 97 (0x61) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""bool I1.op_False(I1)"" IL_0007: brtrue.s IL_0060 IL_0009: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_000e: brfalse.s IL_0012 IL_0010: br.s IL_0047 IL_0012: ldc.i4.8 IL_0013: ldc.i4.2 IL_0014: ldtoken ""Test"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.2 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.1 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: dup IL_002f: ldc.i4.1 IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0037: stelem.ref IL_0038: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0042: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_004c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Target"" IL_0051: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0056: ldarg.0 IL_0057: ldarg.1 IL_0058: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, I1, dynamic)"" IL_005d: pop IL_005e: br.s IL_0060 IL_0060: ret } "); } else { verifier.VerifyIL("Test.MT3(I1, dynamic)", @" { // Code size 98 (0x62) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""bool I1.op_True(I1)"" IL_0007: brtrue.s IL_0061 IL_0009: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_000e: brfalse.s IL_0012 IL_0010: br.s IL_0048 IL_0012: ldc.i4.8 IL_0013: ldc.i4.s 36 IL_0015: ldtoken ""Test"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: ldc.i4.2 IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0025: dup IL_0026: ldc.i4.0 IL_0027: ldc.i4.1 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: dup IL_0030: ldc.i4.1 IL_0031: ldc.i4.0 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003e: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0043: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_004d: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Target"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0057: ldarg.0 IL_0058: ldarg.1 IL_0059: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, I1, dynamic)"" IL_005e: pop IL_005f: br.s IL_0061 IL_0061: ret } "); } } else { var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); builder.AddRange( // (10,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x && x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + op + " x").WithLocation(10, 13), // (15,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y && y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + op + " y").WithLocation(15, 13), // (23,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a && a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + op + " a").WithLocation(23, 13), // (28,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b && b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b " + op + op + " b").WithLocation(28, 78) ); if (op == "&" ? falseIsAbstract : trueIsAbstract) { builder.Add( // (33,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = b || c; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "b " + op + op + " c").WithLocation(33, 13) ); } builder.Add( // (38,98): error CS7083: Expression must be implicitly convertible to Boolean or its type 'T' must define operator 'true'. // _ = (System.Linq.Expressions.Expression<System.Action<T, dynamic>>)((T d, dynamic e) => (d || e).ToString()); Diagnostic(ErrorCode.ERR_InvalidDynamicCondition, "d").WithArguments("T", op == "&" ? "false" : "true").WithLocation(38, 98) ); compilation1.VerifyDiagnostics(builder.ToArrayAndFree()); } } [Theory] [CombinatorialData] public void ConsumeAbstractCompoundBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>")] string op) { var source1 = @" interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); static void M02(I1 x) { x " + op + @"= 1; } void M03(I1 y) { y " + op + @"= 2; } } interface I2<T> where T : I2<T> { abstract static T operator" + op + @" (T x, int y); } class Test { static void MT1(I1 a) { a " + op + @"= 3; } static void MT2<T>() where T : I2<T> { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + @"= 4).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x /= 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + "= 1").WithLocation(8, 9), // (13,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // y /= 2; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + "= 2").WithLocation(13, 9), // (26,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // a /= 3; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + "= 3").WithLocation(26, 9), // (31,78): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b /= 4).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "b " + op + "= 4").WithLocation(31, 78) ); } private static string BinaryOperatorKind(string op) { switch (op) { case "+": return "Add"; case "-": return "Subtract"; case "*": return "Multiply"; case "/": return "Divide"; case "%": return "Remainder"; case "<<": return "LeftShift"; case ">>": return "RightShift"; case "&": return "And"; case "|": return "Or"; case "^": return "ExclusiveOr"; case "<": return "LessThan"; case "<=": return "LessThanOrEqual"; case "==": return "Equals"; case "!=": return "NotEquals"; case ">=": return "GreaterThanOrEqual"; case ">": return "GreaterThan"; } throw TestExceptionUtilities.UnexpectedValue(op); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); abstract static bool operator == (I1<T> x, I1<T> y); abstract static bool operator != (I1<T> x, I1<T> y); static void M02((int, I1<T>) x) { _ = x " + op + @" x; } void M03((int, I1<T>) y) { _ = y " + op + @" y; } } class Test { static void MT1<T>((int, I1<T>) a) where T : I1<T> { _ = a " + op + @" a; } static void MT2<T>() where T : I1<T> { _ = (System.Linq.Expressions.Expression<System.Action<(int, T)>>)(((int, T) b) => (b " + op + @" b).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x == x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " x").WithLocation(12, 13), // (17,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y == y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " y").WithLocation(17, 13), // (25,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a == a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " a").WithLocation(25, 13), // (30,92): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, T)>>)(((int, T) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(30, 92) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_03([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>")] string op) { string metadataName = BinaryOperatorName(op); bool isShiftOperator = op is "<<" or ">>"; var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static T0 operator" + op + @" (T0 x, int a); } partial class Test { static void M03<T, U>(T x) where T : U where U : I1<T> { _ = x " + op + @" 1; } static void M05<T, U>(T? y) where T : struct, U where U : I1<T> { _ = y " + op + @" 1; } } "; if (!isShiftOperator) { source1 += @" public partial interface I1<T0> { abstract static T0 operator" + op + @" (int a, T0 x); abstract static T0 operator" + op + @" (I1<T0> x, T0 a); abstract static T0 operator" + op + @" (T0 x, I1<T0> a); } partial class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = 1 " + op + @" x; } static void M04<T, U>(T? y) where T : struct, U where U : I1<T> { _ = 1 " + op + @" y; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { _ = x " + op + @" y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { _ = x " + op + @" y; } } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldarg.0 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(int, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_000e IL_000c: br.s IL_0022 IL_000e: ldc.i4.1 IL_000f: ldloca.s V_0 IL_0011: call ""readonly T T?.GetValueOrDefault()"" IL_0016: constrained. ""T"" IL_001c: call ""T I1<T>." + metadataName + @"(int, T)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: pop IL_000f: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_000e IL_000c: br.s IL_0022 IL_000e: ldloca.s V_0 IL_0010: call ""readonly T T?.GetValueOrDefault()"" IL_0015: ldc.i4.1 IL_0016: constrained. ""T"" IL_001c: call ""T I1<T>." + metadataName + @"(T, int)"" IL_0021: pop IL_0022: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 32 (0x20) .maxstack 2 .locals init (T? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brfalse.s IL_001f IL_000b: ldc.i4.1 IL_000c: ldloca.s V_0 IL_000e: call ""readonly T T?.GetValueOrDefault()"" IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + metadataName + @"(int, T)"" IL_001e: pop IL_001f: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: pop IL_000e: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 32 (0x20) .maxstack 2 .locals init (T? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brfalse.s IL_001f IL_000b: ldloca.s V_0 IL_000d: call ""readonly T T?.GetValueOrDefault()"" IL_0012: ldc.i4.1 IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + metadataName + @"(T, int)"" IL_001e: pop IL_001f: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " 1").Single(); Assert.Equal("x " + op + " 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.Binary, Type: T) (Syntax: 'x " + op + @" 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractComparisonBinaryOperator_03([CombinatorialValues("<", ">", "<=", ">=", "==", "!=")] string op) { string metadataName = BinaryOperatorName(op); var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static bool operator" + op + @" (T0 x, int a); abstract static bool operator" + op + @" (int a, T0 x); abstract static bool operator" + op + @" (I1<T0> x, T0 a); abstract static bool operator" + op + @" (T0 x, I1<T0> a); } partial class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = 1 " + op + @" x; } static void M03<T, U>(T x) where T : U where U : I1<T> { _ = x " + op + @" 1; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { _ = x " + op + @" y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { _ = x " + op + @" y; } } "; string matchingOp = MatchingBinaryOperator(op); source1 += @" public partial interface I1<T0> { abstract static bool operator" + matchingOp + @" (T0 x, int a); abstract static bool operator" + matchingOp + @" (int a, T0 x); abstract static bool operator" + matchingOp + @" (I1<T0> x, T0 a); abstract static bool operator" + matchingOp + @" (T0 x, I1<T0> a); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldarg.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(int, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(T, int)"" IL_000e: pop IL_000f: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(int, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(T, int)"" IL_000d: pop IL_000e: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " 1").Single(); Assert.Equal("x " + op + " 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @") (OperatorMethod: System.Boolean I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x " + op + @" 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractLiftedComparisonBinaryOperator_03([CombinatorialValues("<", ">", "<=", ">=", "==", "!=")] string op) { string metadataName = BinaryOperatorName(op); var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static bool operator" + op + @" (T0 x, T0 a); } partial class Test { static void M04<T, U>(T? x, T? y) where T : struct, U where U : I1<T> { _ = x " + op + @" y; } } "; string matchingOp = MatchingBinaryOperator(op); source1 += @" public partial interface I1<T0> { abstract static bool operator" + matchingOp + @" (T0 x, T0 a); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op is "==" or "!=") { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 61 (0x3d) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool T?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: beq.s IL_0017 IL_0015: br.s IL_003c IL_0017: ldloca.s V_0 IL_0019: call ""readonly bool T?.HasValue.get"" IL_001e: brtrue.s IL_0022 IL_0020: br.s IL_003c IL_0022: ldloca.s V_0 IL_0024: call ""readonly T T?.GetValueOrDefault()"" IL_0029: ldloca.s V_1 IL_002b: call ""readonly T T?.GetValueOrDefault()"" IL_0030: constrained. ""T"" IL_0036: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_003b: pop IL_003c: ret } "); } else { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool T?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: and IL_0014: brtrue.s IL_0018 IL_0016: br.s IL_0032 IL_0018: ldloca.s V_0 IL_001a: call ""readonly T T?.GetValueOrDefault()"" IL_001f: ldloca.s V_1 IL_0021: call ""readonly T T?.GetValueOrDefault()"" IL_0026: constrained. ""T"" IL_002c: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_0031: pop IL_0032: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op is "==" or "!=") { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 56 (0x38) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: bne.un.s IL_0037 IL_0014: ldloca.s V_0 IL_0016: call ""readonly bool T?.HasValue.get"" IL_001b: brfalse.s IL_0037 IL_001d: ldloca.s V_0 IL_001f: call ""readonly T T?.GetValueOrDefault()"" IL_0024: ldloca.s V_1 IL_0026: call ""readonly T T?.GetValueOrDefault()"" IL_002b: constrained. ""T"" IL_0031: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_0036: pop IL_0037: ret } "); } else { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 48 (0x30) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: and IL_0013: brfalse.s IL_002f IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: ldloca.s V_1 IL_001e: call ""readonly T T?.GetValueOrDefault()"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_002e: pop IL_002f: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " y").Single(); Assert.Equal("x " + op + " y", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @", IsLifted) (OperatorMethod: System.Boolean I1<T>." + metadataName + @"(T x, T a)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x " + op + @" y') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T?) (Syntax: 'x') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T?) (Syntax: 'y') "); } [Theory] [InlineData("&", true, true)] [InlineData("|", true, true)] [InlineData("&", true, false)] [InlineData("|", true, false)] [InlineData("&", false, true)] [InlineData("|", false, true)] public void ConsumeAbstractLogicalBinaryOperator_03(string op, bool binaryIsAbstract, bool unaryIsAbstract) { var binaryMetadataName = op == "&" ? "op_BitwiseAnd" : "op_BitwiseOr"; var unaryMetadataName = op == "&" ? "op_False" : "op_True"; var opKind = op == "&" ? "ConditionalAnd" : "ConditionalOr"; if (binaryIsAbstract && unaryIsAbstract) { consumeAbstract(op); } else { consumeMixed(op, binaryIsAbstract, unaryIsAbstract); } void consumeAbstract(string op) { var source1 = @" public interface I1<T0> where T0 : I1<T0> { abstract static T0 operator" + op + @" (T0 a, T0 x); abstract static bool operator true (T0 x); abstract static bool operator false (T0 x); } public interface I2<T0> where T0 : struct, I2<T0> { abstract static T0 operator" + op + @" (T0 a, T0 x); abstract static bool operator true (T0? x); abstract static bool operator false (T0? x); } class Test { static void M03<T, U>(T x, T y) where T : U where U : I1<T> { _ = x " + op + op + @" y; } static void M04<T, U>(T? x, T? y) where T : struct, U where U : I2<T> { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 34 (0x22) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: constrained. ""T"" IL_000a: call ""bool I1<T>." + unaryMetadataName + @"(T)"" IL_000f: brtrue.s IL_0021 IL_0011: ldloc.0 IL_0012: ldarg.1 IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + binaryMetadataName + @"(T, T)"" IL_001e: pop IL_001f: br.s IL_0021 IL_0021: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 69 (0x45) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: constrained. ""T"" IL_000a: call ""bool I2<T>." + unaryMetadataName + @"(T?)"" IL_000f: brtrue.s IL_0044 IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldarg.1 IL_0014: stloc.2 IL_0015: ldloca.s V_1 IL_0017: call ""readonly bool T?.HasValue.get"" IL_001c: ldloca.s V_2 IL_001e: call ""readonly bool T?.HasValue.get"" IL_0023: and IL_0024: brtrue.s IL_0028 IL_0026: br.s IL_0042 IL_0028: ldloca.s V_1 IL_002a: call ""readonly T T?.GetValueOrDefault()"" IL_002f: ldloca.s V_2 IL_0031: call ""readonly T T?.GetValueOrDefault()"" IL_0036: constrained. ""T"" IL_003c: call ""T I2<T>." + binaryMetadataName + @"(T, T)"" IL_0041: pop IL_0042: br.s IL_0044 IL_0044: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + unaryMetadataName + @"(T)"" IL_000e: brtrue.s IL_001e IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: constrained. ""T"" IL_0018: call ""T I1<T>." + binaryMetadataName + @"(T, T)"" IL_001d: pop IL_001e: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 64 (0x40) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I2<T>." + unaryMetadataName + @"(T?)"" IL_000e: brtrue.s IL_003f IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: ldarg.1 IL_0013: stloc.2 IL_0014: ldloca.s V_1 IL_0016: call ""readonly bool T?.HasValue.get"" IL_001b: ldloca.s V_2 IL_001d: call ""readonly bool T?.HasValue.get"" IL_0022: and IL_0023: brfalse.s IL_003f IL_0025: ldloca.s V_1 IL_0027: call ""readonly T T?.GetValueOrDefault()"" IL_002c: ldloca.s V_2 IL_002e: call ""readonly T T?.GetValueOrDefault()"" IL_0033: constrained. ""T"" IL_0039: call ""T I2<T>." + binaryMetadataName + @"(T, T)"" IL_003e: pop IL_003f: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + op + " y").First(); Assert.Equal("x " + op + op + " y", node1.ToString()); VerifyOperationTreeForNode(compilation1, model, node1, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + opKind + @") (OperatorMethod: T I1<T>." + binaryMetadataName + @"(T a, T x)) (OperationKind.Binary, Type: T) (Syntax: 'x " + op + op + @" y') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T) (Syntax: 'y') "); } void consumeMixed(string op, bool binaryIsAbstract, bool unaryIsAbstract) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 a, I1 x)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (unaryIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (unaryIsAbstract ? ";" : " => throw null;") + @" " + (unaryIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (unaryIsAbstract ? ";" : " => throw null;") + @" } class Test { static void M03<T, U>(T x, T y) where T : U where U : I1 { _ = x " + op + op + @" y; } static void M04<T, U>(T? x, T? y) where T : struct, U where U : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch (binaryIsAbstract, unaryIsAbstract) { case (true, false): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000e: brtrue.s IL_0025 IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: box ""T"" IL_0017: constrained. ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T?"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000e: brtrue.s IL_0025 IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: box ""T?"" IL_0017: constrained. ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); break; case (false, true): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: constrained. ""T"" IL_000f: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldarg.1 IL_0018: box ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T?"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: constrained. ""T"" IL_000f: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldarg.1 IL_0018: box ""T?"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); break; default: Assert.True(false); break; } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch (binaryIsAbstract, unaryIsAbstract) { case (true, false): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000d: brtrue.s IL_0022 IL_000f: ldloc.0 IL_0010: ldarg.1 IL_0011: box ""T"" IL_0016: constrained. ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T?"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000d: brtrue.s IL_0022 IL_000f: ldloc.0 IL_0010: ldarg.1 IL_0011: box ""T?"" IL_0016: constrained. ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); break; case (false, true): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: constrained. ""T"" IL_000e: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0013: brtrue.s IL_0022 IL_0015: ldloc.0 IL_0016: ldarg.1 IL_0017: box ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T?"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: constrained. ""T"" IL_000e: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0013: brtrue.s IL_0022 IL_0015: ldloc.0 IL_0016: ldarg.1 IL_0017: box ""T?"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); break; default: Assert.True(false); break; } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + op + " y").First(); Assert.Equal("x " + op + op + " y", node1.ToString()); VerifyOperationTreeForNode(compilation1, model, node1, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + opKind + @") (OperatorMethod: I1 I1." + binaryMetadataName + @"(I1 a, I1 x)) (OperationKind.Binary, Type: I1) (Syntax: 'x " + op + op + @" y') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: I1, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: I1, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T) (Syntax: 'y') "); } } [Theory] [InlineData("+", "op_Addition", "Add")] [InlineData("-", "op_Subtraction", "Subtract")] [InlineData("*", "op_Multiply", "Multiply")] [InlineData("/", "op_Division", "Divide")] [InlineData("%", "op_Modulus", "Remainder")] [InlineData("&", "op_BitwiseAnd", "And")] [InlineData("|", "op_BitwiseOr", "Or")] [InlineData("^", "op_ExclusiveOr", "ExclusiveOr")] [InlineData("<<", "op_LeftShift", "LeftShift")] [InlineData(">>", "op_RightShift", "RightShift")] public void ConsumeAbstractCompoundBinaryOperator_03(string op, string metadataName, string operatorKind) { bool isShiftOperator = op.Length == 2; var source1 = @" public interface I1<T0> where T0 : I1<T0> { "; if (!isShiftOperator) { source1 += @" abstract static int operator" + op + @" (int a, T0 x); abstract static I1<T0> operator" + op + @" (I1<T0> x, T0 a); abstract static T0 operator" + op + @" (T0 x, I1<T0> a); "; } source1 += @" abstract static T0 operator" + op + @" (T0 x, int a); } class Test { "; if (!isShiftOperator) { source1 += @" static void M02<T, U>(int a, T x) where T : U where U : I1<T> { a " + op + @"= x; } static void M04<T, U>(int? a, T? y) where T : struct, U where U : I1<T> { a " + op + @"= y; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { x " + op + @"= y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { x " + op + @"= y; } "; } source1 += @" static void M03<T, U>(T x) where T : U where U : I1<T> { x " + op + @"= 1; } static void M05<T, U>(T? y) where T : struct, U where U : I1<T> { y " + op + @"= 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(int, T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""int I1<T>." + metadataName + @"(int, T)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?, T?)", @" { // Code size 66 (0x42) .maxstack 2 .locals init (int? V_0, T? V_1, int? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool int?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: and IL_0014: brtrue.s IL_0021 IL_0016: ldloca.s V_2 IL_0018: initobj ""int?"" IL_001e: ldloc.2 IL_001f: br.s IL_003f IL_0021: ldloca.s V_0 IL_0023: call ""readonly int int?.GetValueOrDefault()"" IL_0028: ldloca.s V_1 IL_002a: call ""readonly T T?.GetValueOrDefault()"" IL_002f: constrained. ""T"" IL_0035: call ""int I1<T>." + metadataName + @"(int, T)"" IL_003a: newobj ""int?..ctor(int)"" IL_003f: starg.s V_0 IL_0041: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""I1<T> I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: starg.s V_0 IL_0010: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 50 (0x32) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002f IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: ldc.i4.1 IL_001f: constrained. ""T"" IL_0025: call ""T I1<T>." + metadataName + @"(T, int)"" IL_002a: newobj ""T?..ctor(T)"" IL_002f: starg.s V_0 IL_0031: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(int, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(int, T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?, T?)", @" { // Code size 65 (0x41) .maxstack 2 .locals init (int? V_0, T? V_1, int? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool int?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: and IL_0013: brtrue.s IL_0020 IL_0015: ldloca.s V_2 IL_0017: initobj ""int?"" IL_001d: ldloc.2 IL_001e: br.s IL_003e IL_0020: ldloca.s V_0 IL_0022: call ""readonly int int?.GetValueOrDefault()"" IL_0027: ldloca.s V_1 IL_0029: call ""readonly T T?.GetValueOrDefault()"" IL_002e: constrained. ""T"" IL_0034: call ""int I1<T>." + metadataName + @"(int, T)"" IL_0039: newobj ""int?..ctor(int)"" IL_003e: starg.s V_0 IL_0040: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""I1<T> I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: starg.s V_0 IL_000f: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0016 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: br.s IL_002e IL_0016: ldloca.s V_0 IL_0018: call ""readonly T T?.GetValueOrDefault()"" IL_001d: ldc.i4.1 IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T, int)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: starg.s V_0 IL_0030: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(n => n.ToString() == "x " + op + "= 1").Single(); Assert.Equal("x " + op + "= 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" ICompoundAssignmentOperation (BinaryOperatorKind." + operatorKind + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.CompoundAssignment, Type: T) (Syntax: 'x " + op + @"= 1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } class Test { static void M02<T, U>((int, T) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0011: bne.un.s IL_002c IL_0013: ldloc.0 IL_0014: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001f: constrained. ""T"" IL_0025: call ""bool I1<T>.op_Equality(T, T)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.0 IL_002d: pop IL_002e: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0011: bne.un.s IL_002c IL_0013: ldloc.0 IL_0014: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001f: constrained. ""T"" IL_0025: call ""bool I1<T>.op_Inequality(T, T)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.1 IL_002d: pop IL_002e: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0010: bne.un.s IL_002b IL_0012: ldloc.0 IL_0013: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001e: constrained. ""T"" IL_0024: call ""bool I1<T>.op_Equality(T, T)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0010: bne.un.s IL_002b IL_0012: ldloc.0 IL_0013: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001e: constrained. ""T"" IL_0024: call ""bool I1<T>.op_Inequality(T, T)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.1 IL_002c: pop IL_002d: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, T)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, T)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1 { _ = x " + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x - y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " y").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator- (I1 x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 32) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_04(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" } "; var source2 = @" class Test { static void M02<T>(T x, T y) where T : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); if (success) { compilation2.VerifyDiagnostics(); } else { compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x && y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + op + " y").WithLocation(6, 13) ); } var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); if (binaryIsAbstract) { builder.Add( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator& (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 32) ); } if (trueIsAbstract) { builder.Add( // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(13, 35) ); } if (falseIsAbstract) { builder.Add( // (14,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(14, 35) ); } compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation).Verify(builder.ToArrayAndFree()); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("*")] [InlineData("/")] [InlineData("%")] [InlineData("&")] [InlineData("|")] [InlineData("^")] [InlineData("<<")] [InlineData(">>")] public void ConsumeAbstractCompoundBinaryOperator_04(string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + op + @" (T x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1<T> { x " + op + @"= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // x *= y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + "= y").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator* (T x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 31) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } "; var source2 = @" class Test { static void M02<T>((int, T) x) where T : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator == (T x, T y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "==").WithLocation(12, 35), // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator != (T x, T y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "!=").WithLocation(13, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_06([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1 { _ = x " + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x - y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " y").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator- (I1 x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 32) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_06(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" } "; var source2 = @" class Test { static void M02<T>(T x, T y) where T : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); if (success) { compilation2.VerifyDiagnostics(); } else { compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x && y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + op + " y").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); } var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); if (binaryIsAbstract) { builder.Add( // (12,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator& (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 32) ); } if (trueIsAbstract) { builder.Add( // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } if (falseIsAbstract) { builder.Add( // (14,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(14, 35) ); } compilation3.VerifyDiagnostics(builder.ToArrayAndFree()); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("*")] [InlineData("/")] [InlineData("%")] [InlineData("&")] [InlineData("|")] [InlineData("^")] [InlineData("<<")] [InlineData(">>")] public void ConsumeAbstractCompoundBinaryOperator_06(string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + op + @" (T x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1<T> { x " + op + @"= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x <<= y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + "= y").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,31): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator<< (T x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 31) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } "; var source2 = @" class Test { static void M02<T>((int, T) x) where T : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator == (T x, T y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(12, 35), // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator != (T x, T y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { _ = P01; _ = P04; } void M03() { _ = this.P01; _ = this.P04; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { _ = I1.P01; _ = x.P01; _ = I1.P04; _ = x.P04; } static void MT2<T>() where T : I1 { _ = T.P03; _ = T.P04; _ = T.P00; _ = T.P05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01.ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = P01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 13), // (14,13): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = this.P01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 13), // (15,13): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = this.P04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 13), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = I1.P01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 13), // (28,13): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = x.P01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 13), // (30,13): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = x.P04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 13), // (35,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 13), // (36,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 13), // (37,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 13), // (38,15): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = T.P05; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 15), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01.ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticPropertySet_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { P01 = 1; P04 = 1; } void M03() { this.P01 = 1; this.P04 = 1; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { I1.P01 = 1; x.P01 = 1; I1.P04 = 1; x.P04 = 1; } static void MT2<T>() where T : I1 { T.P03 = 1; T.P04 = 1; T.P00 = 1; T.P05 = 1; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 = 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 = 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 = 1; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 = 1").WithLocation(40, 71), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { P01 += 1; P04 += 1; } void M03() { this.P01 += 1; this.P04 += 1; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { I1.P01 += 1; x.P01 += 1; I1.P04 += 1; x.P04 += 1; } static void MT2<T>() where T : I1 { T.P03 += 1; T.P04 += 1; T.P00 += 1; T.P05 += 1; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 += 1; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 += 1").WithLocation(40, 71), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticProperty_02() { var source1 = @" interface I1 { abstract static int P01 { get; set; } static void M02() { _ = nameof(P01); _ = nameof(P04); } void M03() { _ = nameof(this.P01); _ = nameof(this.P04); } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { _ = nameof(I1.P01); _ = nameof(x.P01); _ = nameof(I1.P04); _ = nameof(x.P04); } static void MT2<T>() where T : I1 { _ = nameof(T.P03); _ = nameof(T.P04); _ = nameof(T.P00); _ = nameof(T.P05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (14,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 20), // (15,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 20), // (28,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 20), // (30,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 20), // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = nameof(T.P05); Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""int I1.P01.get"" IL_000c: pop IL_000d: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: constrained. ""T"" IL_0006: call ""int I1.P01.get"" IL_000b: pop IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Right; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertySet_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 15 (0xf) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""void I1.P01.set"" IL_000d: nop IL_000e: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: constrained. ""T"" IL_0007: call ""void I1.P01.set"" IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertyCompound_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { T.P01 += 1; } static string M03<T, U>() where T : U where U : I1 { return nameof(T.P01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""int I1.P01.get"" IL_000c: ldc.i4.1 IL_000d: add IL_000e: constrained. ""T"" IL_0014: call ""void I1.P01.set"" IL_0019: nop IL_001a: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""P01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: constrained. ""T"" IL_0006: call ""int I1.P01.get"" IL_000b: ldc.i4.1 IL_000c: add IL_000d: constrained. ""T"" IL_0013: call ""void I1.P01.set"" IL_0018: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""P01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertyGet_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = T.P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertySet_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 = 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9), // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = T.P01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = T.P01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 13), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticPropertySet_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 = 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 = 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticEventAdd_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used interface I1 { abstract static event System.Action P01; static void M02() { P01 += null; P04 += null; } void M03() { this.P01 += null; this.P04 += null; } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { I1.P01 += null; x.P01 += null; I1.P04 += null; x.P04 += null; } static void MT2<T>() where T : I1 { T.P03 += null; T.P04 += null; T.P00 += null; T.P05 += null; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += null); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01 += null").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (14,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // this.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "this.P01 += null").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01 += null").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (28,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x.P01 += null").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += null); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 += null").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticEventRemove_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used interface I1 { abstract static event System.Action P01; static void M02() { P01 -= null; P04 -= null; } void M03() { this.P01 -= null; this.P04 -= null; } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { I1.P01 -= null; x.P01 -= null; I1.P04 -= null; x.P04 -= null; } static void MT2<T>() where T : I1 { T.P03 -= null; T.P04 -= null; T.P00 -= null; T.P05 -= null; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 -= null); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01 -= null").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (14,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // this.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "this.P01 -= null").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01 -= null").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (28,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x.P01 -= null").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 -= null); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 -= null").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticEvent_02() { var source1 = @" interface I1 { abstract static event System.Action P01; static void M02() { _ = nameof(P01); _ = nameof(P04); } void M03() { _ = nameof(this.P01); _ = nameof(this.P04); } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { _ = nameof(I1.P01); _ = nameof(x.P01); _ = nameof(I1.P04); _ = nameof(x.P04); } static void MT2<T>() where T : I1 { _ = nameof(T.P03); _ = nameof(T.P04); _ = nameof(T.P00); _ = nameof(T.P05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (14,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 20), // (15,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 20), // (28,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 20), // (30,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 20), // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = nameof(T.P05); Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticEvent_03() { var source1 = @" public interface I1 { abstract static event System.Action E01; } class Test { static void M02<T, U>() where T : U where U : I1 { T.E01 += null; T.E01 -= null; } static string M03<T, U>() where T : U where U : I1 { return nameof(T.E01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 28 (0x1c) .maxstack 1 IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: call ""void I1.E01.add"" IL_000d: nop IL_000e: ldnull IL_000f: constrained. ""T"" IL_0015: call ""void I1.E01.remove"" IL_001a: nop IL_001b: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""E01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 25 (0x19) .maxstack 1 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: call ""void I1.E01.add"" IL_000c: ldnull IL_000d: constrained. ""T"" IL_0013: call ""void I1.E01.remove"" IL_0018: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""E01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.E01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IEventReferenceOperation: event System.Action I1.E01 (Static) (OperationKind.EventReference, Type: System.Action) (Syntax: 'T.E01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "E01").Single().ToTestDisplayString()); Assert.Equal("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "E01").Single().ToTestDisplayString()); Assert.Contains("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("event System.Action I1.E01", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "E01").Single().ToTestDisplayString()); Assert.Equal("event System.Action I1.E01", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "E01").Single().ToTestDisplayString()); Assert.Contains("event System.Action I1.E01", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("event System.Action I1.E01", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("E01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticEventAdd_04() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01 += null").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "P01").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventRemove_04() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 -= null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 -= null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01 -= null").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "P01").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventAdd_06() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventRemove_06() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 -= null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 -= null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 -= null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticIndexedProperty_03() { var ilSource = @" .class interface public auto ansi abstract I1 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) // Methods .method public hidebysig specialname newslot abstract virtual static int32 get_Item ( int32 x ) cil managed { } // end of method I1::get_Item .method public hidebysig specialname newslot abstract virtual static void set_Item ( int32 x, int32 'value' ) cil managed { } // end of method I1::set_Item // Properties .property int32 Item( int32 x ) { .get int32 I1::get_Item(int32) .set void I1::set_Item(int32, int32) } } // end of class I1 "; var source1 = @" class Test { static void M02<T>() where T : I1 { T.Item[0] += 1; } static string M03<T>() where T : I1 { return nameof(T.Item); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.Item[0] += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(6, 9), // (11,23): error CS0119: 'T' is a type parameter, which is not valid in the given context // return nameof(T.Item); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(11, 23) ); var source2 = @" class Test { static void M02<T>() where T : I1 { T[0] += 1; } static void M03<T>() where T : I1 { T.set_Item(0, T.get_Item(0) + 1); } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (6,9): error CS0119: 'T' is a type, which is not valid in the given context // T[0] += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type").WithLocation(6, 9), // (11,11): error CS0571: 'I1.this[int].set': cannot explicitly call operator or accessor // T.set_Item(0, T.get_Item(0) + 1); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Item").WithArguments("I1.this[int].set").WithLocation(11, 11), // (11,25): error CS0571: 'I1.this[int].get': cannot explicitly call operator or accessor // T.set_Item(0, T.get_Item(0) + 1); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Item").WithArguments("I1.this[int].get").WithLocation(11, 25) ); } [Fact] public void ConsumeAbstractStaticIndexedProperty_04() { var ilSource = @" .class interface public auto ansi abstract I1 { // Methods .method public hidebysig specialname newslot abstract virtual static int32 get_Item ( int32 x ) cil managed { } // end of method I1::get_Item .method public hidebysig specialname newslot abstract virtual static void set_Item ( int32 x, int32 'value' ) cil managed { } // end of method I1::set_Item // Properties .property int32 Item( int32 x ) { .get int32 I1::get_Item(int32) .set void I1::set_Item(int32, int32) } } // end of class I1 "; var source1 = @" class Test { static void M02<T>() where T : I1 { T.Item[0] += 1; } static string M03<T>() where T : I1 { return nameof(T.Item); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,11): error CS1545: Property, indexer, or event 'I1.Item[int]' is not supported by the language; try directly calling accessor methods 'I1.get_Item(int)' or 'I1.set_Item(int, int)' // T.Item[0] += 1; Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Item").WithArguments("I1.Item[int]", "I1.get_Item(int)", "I1.set_Item(int, int)").WithLocation(6, 11), // (11,25): error CS1545: Property, indexer, or event 'I1.Item[int]' is not supported by the language; try directly calling accessor methods 'I1.get_Item(int)' or 'I1.set_Item(int, int)' // return nameof(T.Item); Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Item").WithArguments("I1.Item[int]", "I1.get_Item(int)", "I1.set_Item(int, int)").WithLocation(11, 25) ); var source2 = @" class Test { static void M02<T>() where T : I1 { T.set_Item(0, T.get_Item(0) + 1); } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation2, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T>()", @" { // Code size 29 (0x1d) .maxstack 3 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: ldc.i4.0 IL_0003: constrained. ""T"" IL_0009: call ""int I1.get_Item(int)"" IL_000e: ldc.i4.1 IL_000f: add IL_0010: constrained. ""T"" IL_0016: call ""void I1.set_Item(int, int)"" IL_001b: nop IL_001c: ret } "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = (System.Action)M01; _ = (System.Action)M04; } void M03() { _ = (System.Action)this.M01; _ = (System.Action)this.M04; } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = (System.Action)I1.M01; _ = (System.Action)x.M01; _ = (System.Action)I1.M04; _ = (System.Action)x.M04; } static void MT2<T>() where T : I1 { _ = (System.Action)T.M03; _ = (System.Action)T.M04; _ = (System.Action)T.M00; _ = (System.Action)T.M05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.Action)T.M01).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (System.Action)M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(System.Action)M01").WithLocation(8, 13), // (14,28): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)this.M01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 28), // (15,28): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)this.M04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 28), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (System.Action)I1.M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(System.Action)I1.M01").WithLocation(27, 13), // (28,28): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)x.M01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 28), // (30,28): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)x.M04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 28), // (35,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 28), // (36,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 28), // (37,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 28), // (38,30): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = (System.Action)T.M05; Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 30), // (40,87): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.Action)T.M01).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01").WithLocation(40, 87) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_03() { var source1 = @" public interface I1 { abstract static void M01(); } class Test { static System.Action M02<T, U>() where T : U where U : I1 { return T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 24 (0x18) .maxstack 2 .locals init (System.Action V_0) IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: ldftn ""void I1.M01()"" IL_000e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0012: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = (System.Action)T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "(System.Action)T.M01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = (System.Action)T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,28): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 28) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,28): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 28), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = new System.Action(M01); _ = new System.Action(M04); } void M03() { _ = new System.Action(this.M01); _ = new System.Action(this.M04); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = new System.Action(I1.M01); _ = new System.Action(x.M01); _ = new System.Action(I1.M04); _ = new System.Action(x.M04); } static void MT2<T>() where T : I1 { _ = new System.Action(T.M03); _ = new System.Action(T.M04); _ = new System.Action(T.M00); _ = new System.Action(T.M05); _ = (System.Linq.Expressions.Expression<System.Action>)(() => new System.Action(T.M01).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,31): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = new System.Action(M01); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "M01").WithLocation(8, 31), // (14,31): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(this.M01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 31), // (15,31): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(this.M04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 31), // (27,31): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = new System.Action(I1.M01); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.M01").WithLocation(27, 31), // (28,31): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(x.M01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 31), // (30,31): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(x.M04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 31), // (35,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 31), // (36,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 31), // (37,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 31), // (38,33): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = new System.Action(T.M05); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 33), // (40,89): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => new System.Action(T.M01).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01").WithLocation(40, 89) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_03() { var source1 = @" public interface I1 { abstract static void M01(); } class Test { static System.Action M02<T, U>() where T : U where U : I1 { return new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 24 (0x18) .maxstack 2 .locals init (System.Action V_0) IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: ldftn ""void I1.M01()"" IL_000e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0012: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.M01").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_01() { var source1 = @" unsafe interface I1 { abstract static void M01(); static void M02() { _ = (delegate*<void>)&M01; _ = (delegate*<void>)&M04; } void M03() { _ = (delegate*<void>)&this.M01; _ = (delegate*<void>)&this.M04; } static void M04() {} protected abstract static void M05(); } unsafe class Test { static void MT1(I1 x) { _ = (delegate*<void>)&I1.M01; _ = (delegate*<void>)&x.M01; _ = (delegate*<void>)&I1.M04; _ = (delegate*<void>)&x.M04; } static void MT2<T>() where T : I1 { _ = (delegate*<void>)&T.M03; _ = (delegate*<void>)&T.M04; _ = (delegate*<void>)&T.M00; _ = (delegate*<void>)&T.M05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (delegate*<void>)&M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(delegate*<void>)&M01").WithLocation(8, 13), // (14,13): error CS8757: No overload for 'M01' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&this.M01; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&this.M01").WithArguments("M01", "delegate*<void>").WithLocation(14, 13), // (15,13): error CS8757: No overload for 'M04' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&this.M04; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&this.M04").WithArguments("M04", "delegate*<void>").WithLocation(15, 13), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (delegate*<void>)&I1.M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(delegate*<void>)&I1.M01").WithLocation(27, 13), // (28,13): error CS8757: No overload for 'M01' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&x.M01; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&x.M01").WithArguments("M01", "delegate*<void>").WithLocation(28, 13), // (30,13): error CS8757: No overload for 'M04' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&x.M04; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&x.M04").WithArguments("M04", "delegate*<void>").WithLocation(30, 13), // (35,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 31), // (36,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 31), // (37,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 31), // (38,33): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = (delegate*<void>)&T.M05; Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 33), // (40,88): error CS1944: An expression tree may not contain an unsafe pointer operation // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "(delegate*<void>)&T.M01").WithLocation(40, 88), // (40,106): error CS8810: '&' on method groups cannot be used in expression trees // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); Diagnostic(ErrorCode.ERR_AddressOfMethodGroupInExpressionTree, "T.M01").WithLocation(40, 106) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_03() { var source1 = @" public interface I1 { abstract static void M01(); } unsafe class Test { static delegate*<void> M02<T, U>() where T : U where U : I1 { return &T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 18 (0x12) .maxstack 1 .locals init (delegate*<void> V_0) IL_0000: nop IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: constrained. ""T"" IL_0006: ldftn ""void I1.M01()"" IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionFunctionPointer_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" unsafe class Test { static void M02<T>() where T : I1 { _ = (delegate*<void>)&T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "(delegate*<void>)&T.M01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" unsafe class Test { static void M02<T>() where T : I1 { _ = (delegate*<void>)&T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public void M01() {} } " + typeKeyword + @" C3 : I1 { static void M01() {} } " + typeKeyword + @" C4 : I1 { void I1.M01() {} } " + typeKeyword + @" C5 : I1 { public static int M01() => throw null; } " + typeKeyword + @" C6 : I1 { static int I1.M01() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01()' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01()").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01()'. 'C2.M01()' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01()", "C2.M01()").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01()'. 'C3.M01()' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01()", "C3.M01()").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01()' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01()").WithLocation(24, 10), // (26,13): error CS0539: 'C4.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01()").WithLocation(26, 13), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01()'. 'C5.M01()' cannot implement 'I1.M01()' because it does not have the matching return type of 'void'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01()", "C5.M01()", "void").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01()' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01()").WithLocation(36, 10), // (38,19): error CS0539: 'C6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01() => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01()").WithLocation(38, 19) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract void M01(); } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static void M01() {} } " + typeKeyword + @" C3 : I1 { void M01() {} } " + typeKeyword + @" C4 : I1 { static void I1.M01() {} } " + typeKeyword + @" C5 : I1 { public int M01() => throw null; } " + typeKeyword + @" C6 : I1 { int I1.M01() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01()' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01()").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01()'. 'C2.M01()' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01()", "C2.M01()").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01()'. 'C3.M01()' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01()", "C3.M01()").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01()' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01()").WithLocation(24, 10), // (26,20): error CS0539: 'C4.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01()").WithLocation(26, 20), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01()'. 'C5.M01()' cannot implement 'I1.M01()' because it does not have the matching return type of 'void'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01()", "C5.M01()", "void").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01()' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01()").WithLocation(36, 10), // (38,12): error CS0539: 'C6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01() => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01()").WithLocation(38, 12) ); } [Fact] public void ImplementAbstractStaticMethod_03() { var source1 = @" public interface I1 { abstract static void M01(); } interface I2 : I1 {} interface I3 : I1 { public virtual void M01() {} } interface I4 : I1 { static void M01() {} } interface I5 : I1 { void I1.M01() {} } interface I6 : I1 { static void I1.M01() {} } interface I7 : I1 { abstract static void M01(); } interface I8 : I1 { abstract static void I1.M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,25): warning CS0108: 'I3.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // public virtual void M01() {} Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01()", "I1.M01()").WithLocation(12, 25), // (17,17): warning CS0108: 'I4.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // static void M01() {} Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01()", "I1.M01()").WithLocation(17, 17), // (22,13): error CS0539: 'I5.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01()").WithLocation(22, 13), // (27,20): error CS0106: The modifier 'static' is not valid for this item // static void I1.M01() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 20), // (27,20): error CS0539: 'I6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01()").WithLocation(27, 20), // (32,26): warning CS0108: 'I7.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // abstract static void M01(); Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01()", "I1.M01()").WithLocation(32, 26), // (37,29): error CS0106: The modifier 'static' is not valid for this item // abstract static void I1.M01(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 29), // (37,29): error CS0539: 'I8.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static void I1.M01(); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01()").WithLocation(37, 29) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); abstract static void M02(); } "; var source2 = typeKeyword + @" Test: I1 { static void I1.M01() {} public static void M02() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,20): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 20) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,20): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 20), // (10,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 26), // (11,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M02(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = typeKeyword + @" Test1: I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01()' cannot implement interface member 'I1.M01()' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01()", "I1.M01()", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01()' cannot implement interface member 'I1.M01()' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01()", "I1.M01()", "Test1").WithLocation(2, 12), // (9,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = typeKeyword + @" Test1: I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,20): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 20) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,20): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 20), // (9,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C : I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, cM01.MethodKind); Assert.Equal("void C.M01()", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C : I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.Equal("void C.I1.M01()", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticMethod_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static void M01(); } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C2.I1.M01()", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticMethod_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig static abstract virtual void M01 () cil managed { } // end of method I1::M01 } // end of class I1 .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static void I1.M01 () cil managed { .override method void I1::M01() .maxstack 8 IL_0000: ret } // end of method C1::I1.M01 .method public hidebysig static void M01 () cil managed { IL_0000: ret } // end of method C1::M01 .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } // end of method C1::.ctor } // end of class C1 .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static void M01 () cil managed { IL_0000: ret } // end of method C2::M01 .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1.I1.M01()", c1M01.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); Assert.Equal("void C2.M01()", c5.FindImplementationForInterfaceMember(m01).ToTestDisplayString()); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticMethod_11() { // Ignore invalid metadata (non-abstract static virtual method). var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig virtual static void M01 () cil managed { IL_0000: ret } // end of method I1::M01 } // end of class I1 "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static void I1.M01() {} } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,19): error CS0539: 'C1.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01()").WithLocation(4, 19) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Fact] public void ImplementAbstractStaticMethod_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void M01 () cil managed { } // end of method I1::M01 } // end of class I1 .class interface public auto ansi abstract I2 implements I1 { // Methods .method private hidebysig static void I1.M01 () cil managed { .override method void I1::M01() IL_0000: ret } // end of method I2::I1.M01 } // end of class I2 "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01()' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01()").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticMethod_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static void M01(); } class C1 { public static void M01() {} } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("void C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1.M01"); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Ordinary, c2M01.MethodKind); Assert.Equal("void C1.M01()", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C1.M01()"" IL_0005: ret } "); } [Fact] public void ImplementAbstractStaticMethod_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void modopt(I1) M01 () cil managed { } // end of method I1::M01 } // end of class I1 "; var source1 = @" class C1 : I1 { public static void M01() {} } class C2 : I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("void modopt(I1) C1.I1.M01()", c1M01.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1.M01"); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("void modopt(I1) C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C1.M01()"" IL_0005: ret } "); } [Fact] public void ImplementAbstractStaticMethod_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static void M01(); abstract static void M02(); } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static void I1.M02() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<MethodSymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>("M01"); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<MethodSymbol>().Single(); var c2M02 = c3.BaseType().GetMember<MethodSymbol>("I1.M02"); Assert.Equal("void C2.I1.M02()", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Fact] public void ImplementAbstractStaticMethod_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static void M01(); } public class C1 : I1 { public static void M01() {} } public class C2 : C1 { new public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C2.M01()"" IL_0005: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<MethodSymbol>("M01"); Assert.Equal("void C2.M01()", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C3.I1.M01()", c3M01.ToTestDisplayString()); Assert.Same(m01, c3M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_17(bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(System.Int32 x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(System.Int32 x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_18(bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(T x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(T x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_19(bool genericFirst) { // Same as ImplementAbstractStaticMethod_17 only implementation is explicit in source. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" static void I1.M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.I1.M01(System.Int32 x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_20(bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implementation is explicit in source. var generic = @" static void I1<T>.M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.I1<T>.M01(T x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_21(bool genericFirst) { // Same as ImplementAbstractStaticMethod_17 only implicit implementation is in an intermediate base. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T> : C1<T>, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C11<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "void C11<T>.I1.M01(System.Int32 x)" : "void C1<T>.M01(System.Int32 x)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_22(bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implicit implementation is in an intermediate base. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T> : C1<T>, I1<T> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C11<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "void C11<T>.I1<T>.M01(T x)" : "void C1<T>.M01(T x)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } private static string UnaryOperatorName(string op) => OperatorFacts.UnaryOperatorNameFromSyntaxKindIfAny(SyntaxFactory.ParseToken(op).Kind()); private static string BinaryOperatorName(string op) => op switch { ">>" => WellKnownMemberNames.RightShiftOperatorName, _ => OperatorFacts.BinaryOperatorNameFromSyntaxKindIfAny(SyntaxFactory.ParseToken(op).Kind()) }; [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = UnaryOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public C2 operator " + op + @"(C2 x) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static C3 operator " + op + @"(C3 x) => throw null; } " + typeKeyword + @" C4 : I1<C4> { C4 I1<C4>.operator " + op + @"(C4 x) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static int operator " + op + @" (C5 x) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static int I1<C6>.operator " + op + @" (C6 x) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static C7 " + opName + @"(C7 x) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static C8 I1<C8>." + opName + @"(C8 x) => throw null; } public interface I2<T> where T : I2<T> { abstract static T " + opName + @"(T x); } " + typeKeyword + @" C9 : I2<C9> { public static C9 operator " + op + @"(C9 x) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static C10 I2<C10>.operator " + op + @"(C10 x) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_BadIncDecRetType or (int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.operator +(C1)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>.operator " + op + "(C1)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.operator +(C2)'. 'C2.operator +(C2)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>.operator " + op + "(C2)", "C2.operator " + op + "(C2)").WithLocation(12, 10), // (14,24): error CS0558: User-defined operator 'C2.operator +(C2)' must be declared static and public // public C2 operator +(C2 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C2.operator " + op + "(C2)").WithLocation(14, 24), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.operator +(C3)'. 'C3.operator +(C3)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>.operator " + op + "(C3)", "C3.operator " + op + "(C3)").WithLocation(18, 10), // (20,24): error CS0558: User-defined operator 'C3.operator +(C3)' must be declared static and public // static C3 operator +(C3 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C3.operator " + op + "(C3)").WithLocation(20, 24), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.operator +(C4)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>.operator " + op + "(C4)").WithLocation(24, 10), // (26,24): error CS8930: Explicit implementation of a user-defined operator 'C4.operator +(C4)' must be declared static // C4 I1<C4>.operator +(C4 x) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("C4.operator " + op + "(C4)").WithLocation(26, 24), // (26,24): error CS0539: 'C4.operator +(C4)' in explicit interface declaration is not found among members of the interface that can be implemented // C4 I1<C4>.operator +(C4 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C4.operator " + op + "(C4)").WithLocation(26, 24), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.operator +(C5)'. 'C5.operator +(C5)' cannot implement 'I1<C5>.operator +(C5)' because it does not have the matching return type of 'C5'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>.operator " + op + "(C5)", "C5.operator " + op + "(C5)", "C5").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.operator +(C6)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>.operator " + op + "(C6)").WithLocation(36, 10), // (38,32): error CS0539: 'C6.operator +(C6)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C6>.operator + (C6 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C6.operator " + op + "(C6)").WithLocation(38, 32), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.operator +(C7)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>.operator " + op + "(C7)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.operator +(C8)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>.operator " + op + "(C8)").WithLocation(48, 10), // (50,22): error CS0539: 'C8.op_UnaryPlus(C8)' in explicit interface declaration is not found among members of the interface that can be implemented // static C8 I1<C8>.op_UnaryPlus(C8 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8)").WithLocation(50, 22), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_UnaryPlus(C9)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_UnaryPlus(C10)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10)").WithLocation(65, 11), // (67,33): error CS0539: 'C10.operator +(C10)' in explicit interface declaration is not found among members of the interface that can be implemented // static C10 I2<C10>.operator +(C10 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C10.operator " + op + "(C10)").WithLocation(67, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = BinaryOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public C2 operator " + op + @"(C2 x, int y) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static C3 operator " + op + @"(C3 x, int y) => throw null; } " + typeKeyword + @" C4 : I1<C4> { C4 I1<C4>.operator " + op + @"(C4 x, int y) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static int operator " + op + @" (C5 x, int y) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static int I1<C6>.operator " + op + @" (C6 x, int y) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static C7 " + opName + @"(C7 x, int y) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static C8 I1<C8>." + opName + @"(C8 x, int y) => throw null; } public interface I2<T> where T : I2<T> { abstract static T " + opName + @"(T x, int y); } " + typeKeyword + @" C9 : I2<C9> { public static C9 operator " + op + @"(C9 x, int y) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static C10 I2<C10>.operator " + op + @"(C10 x, int y) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.operator >>(C1, int)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>.operator " + op + "(C1, int)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.operator >>(C2, int)'. 'C2.operator >>(C2, int)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>.operator " + op + "(C2, int)", "C2.operator " + op + "(C2, int)").WithLocation(12, 10), // (14,24): error CS0558: User-defined operator 'C2.operator >>(C2, int)' must be declared static and public // public C2 operator >>(C2 x, int y) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C2.operator " + op + "(C2, int)").WithLocation(14, 24), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.operator >>(C3, int)'. 'C3.operator >>(C3, int)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>.operator " + op + "(C3, int)", "C3.operator " + op + "(C3, int)").WithLocation(18, 10), // (20,24): error CS0558: User-defined operator 'C3.operator >>(C3, int)' must be declared static and public // static C3 operator >>(C3 x, int y) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C3.operator " + op + "(C3, int)").WithLocation(20, 24), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.operator >>(C4, int)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>.operator " + op + "(C4, int)").WithLocation(24, 10), // (26,24): error CS8930: Explicit implementation of a user-defined operator 'C4.operator >>(C4, int)' must be declared static // C4 I1<C4>.operator >>(C4 x, int y) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("C4.operator " + op + "(C4, int)").WithLocation(26, 24), // (26,24): error CS0539: 'C4.operator >>(C4, int)' in explicit interface declaration is not found among members of the interface that can be implemented // C4 I1<C4>.operator >>(C4 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C4.operator " + op + "(C4, int)").WithLocation(26, 24), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.operator >>(C5, int)'. 'C5.operator >>(C5, int)' cannot implement 'I1<C5>.operator >>(C5, int)' because it does not have the matching return type of 'C5'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>.operator " + op + "(C5, int)", "C5.operator " + op + "(C5, int)", "C5").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.operator >>(C6, int)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>.operator " + op + "(C6, int)").WithLocation(36, 10), // (38,32): error CS0539: 'C6.operator >>(C6, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C6>.operator >> (C6 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C6.operator " + op + "(C6, int)").WithLocation(38, 32), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.operator >>(C7, int)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>.operator " + op + "(C7, int)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.operator >>(C8, int)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>.operator " + op + "(C8, int)").WithLocation(48, 10), // (50,22): error CS0539: 'C8.op_RightShift(C8, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static C8 I1<C8>.op_RightShift(C8 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8, int)").WithLocation(50, 22), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_RightShift(C9, int)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9, int)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_RightShift(C10, int)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10, int)").WithLocation(65, 11), // (67,33): error CS0539: 'C10.operator >>(C10, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static C10 I2<C10>.operator >>(C10 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C10.operator " + op + "(C10, int)").WithLocation(67, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_03([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } interface I2 : I1 {} interface I3 : I1 { I1 operator " + op + @"(I1 x) => default; } interface I4 : I1 { static I1 operator " + op + @"(I1 x) => default; } interface I5 : I1 { I1 I1.operator " + op + @"(I1 x) => default; } interface I6 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } interface I7 : I1 { abstract static I1 operator " + op + @"(I1 x); } public interface I11<T> where T : I11<T> { abstract static T operator " + op + @"(T x); } interface I8<T> : I11<T> where T : I8<T> { T operator " + op + @"(T x) => default; } interface I9<T> : I11<T> where T : I9<T> { static T operator " + op + @"(T x) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static T operator " + op + @"(T x); } interface I12<T> : I11<T> where T : I12<T> { static T I11<T>.operator " + op + @"(T x) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static T I11<T>.operator " + op + @"(T x); } interface I14 : I1 { abstract static I1 I1.operator " + op + @"(I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ErrorCode badSignatureError = op.Length != 2 ? ErrorCode.ERR_BadUnaryOperatorSignature : ErrorCode.ERR_BadIncDecSignature; ErrorCode badAbstractSignatureError = op.Length != 2 ? ErrorCode.ERR_BadAbstractUnaryOperatorSignature : ErrorCode.ERR_BadAbstractIncDecSignature; compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (12,17): error CS0558: User-defined operator 'I3.operator +(I1)' must be declared static and public // I1 operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I3.operator " + op + "(I1)").WithLocation(12, 17), // (12,17): error CS0562: The parameter of a unary operator must be the containing type // I1 operator +(I1 x) => default; Diagnostic(badSignatureError, op).WithLocation(12, 17), // (17,24): error CS0562: The parameter of a unary operator must be the containing type // static I1 operator +(I1 x) => default; Diagnostic(badSignatureError, op).WithLocation(17, 24), // (22,20): error CS8930: Explicit implementation of a user-defined operator 'I5.operator +(I1)' must be declared static // I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("I5.operator " + op + "(I1)").WithLocation(22, 20), // (22,20): error CS0539: 'I5.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I5.operator " + op + "(I1)").WithLocation(22, 20), // (27,27): error CS0539: 'I6.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I6.operator " + op + "(I1)").WithLocation(27, 27), // (32,33): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // abstract static I1 operator +(I1 x); Diagnostic(badAbstractSignatureError, op).WithLocation(32, 33), // (42,16): error CS0558: User-defined operator 'I8<T>.operator +(T)' must be declared static and public // T operator +(T x) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I8<T>.operator " + op + "(T)").WithLocation(42, 16), // (42,16): error CS0562: The parameter of a unary operator must be the containing type // T operator +(T x) => default; Diagnostic(badSignatureError, op).WithLocation(42, 16), // (47,23): error CS0562: The parameter of a unary operator must be the containing type // static T operator +(T x) => default; Diagnostic(badSignatureError, op).WithLocation(47, 23), // (57,30): error CS0539: 'I12<T>.operator +(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static T I11<T>.operator +(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I12<T>.operator " + op + "(T)").WithLocation(57, 30), // (62,39): error CS0106: The modifier 'abstract' is not valid for this item // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(62, 39), // (62,39): error CS0501: 'I13<T>.operator +(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I13<T>.operator " + op + "(T)").WithLocation(62, 39), // (62,39): error CS0539: 'I13<T>.operator +(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I13<T>.operator " + op + "(T)").WithLocation(62, 39), // (67,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(67, 36), // (67,36): error CS0501: 'I14.operator +(I1)' must declare a body because it is not marked abstract, extern, or partial // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I14.operator " + op + "(I1)").WithLocation(67, 36), // (67,36): error CS0539: 'I14.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I14.operator " + op + "(I1)").WithLocation(67, 36) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_03([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } interface I2 : I1 {} interface I3 : I1 { I1 operator " + op + @"(I1 x, int y) => default; } interface I4 : I1 { static I1 operator " + op + @"(I1 x, int y) => default; } interface I5 : I1 { I1 I1.operator " + op + @"(I1 x, int y) => default; } interface I6 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } interface I7 : I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public interface I11<T> where T : I11<T> { abstract static T operator " + op + @"(T x, int y); } interface I8<T> : I11<T> where T : I8<T> { T operator " + op + @"(T x, int y) => default; } interface I9<T> : I11<T> where T : I9<T> { static T operator " + op + @"(T x, int y) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static T operator " + op + @"(T x, int y); } interface I12<T> : I11<T> where T : I12<T> { static T I11<T>.operator " + op + @"(T x, int y) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static T I11<T>.operator " + op + @"(T x, int y); } interface I14 : I1 { abstract static I1 I1.operator " + op + @"(I1 x, int y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); bool isShift = op == "<<" || op == ">>"; ErrorCode badSignatureError = isShift ? ErrorCode.ERR_BadShiftOperatorSignature : ErrorCode.ERR_BadBinaryOperatorSignature; ErrorCode badAbstractSignatureError = isShift ? ErrorCode.ERR_BadAbstractShiftOperatorSignature : ErrorCode.ERR_BadAbstractBinaryOperatorSignature; var expected = new[] { // (12,17): error CS0563: One of the parameters of a binary operator must be the containing type // I1 operator |(I1 x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(12, 17), // (17,24): error CS0563: One of the parameters of a binary operator must be the containing type // static I1 operator |(I1 x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(17, 24), // (22,20): error CS8930: Explicit implementation of a user-defined operator 'I5.operator |(I1, int)' must be declared static // I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("I5.operator " + op + "(I1, int)").WithLocation(22, 20), // (22,20): error CS0539: 'I5.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I5.operator " + op + "(I1, int)").WithLocation(22, 20), // (27,27): error CS0539: 'I6.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I6.operator " + op + "(I1, int)").WithLocation(27, 27), // (32,33): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // abstract static I1 operator |(I1 x, int y); Diagnostic(badAbstractSignatureError, op).WithLocation(32, 33), // (42,16): error CS0563: One of the parameters of a binary operator must be the containing type // T operator |(T x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(42, 16), // (47,23): error CS0563: One of the parameters of a binary operator must be the containing type // static T operator |(T x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(47, 23), // (57,30): error CS0539: 'I12<T>.operator |(T, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static T I11<T>.operator |(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I12<T>.operator " + op + "(T, int)").WithLocation(57, 30), // (62,39): error CS0106: The modifier 'abstract' is not valid for this item // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(62, 39), // (62,39): error CS0501: 'I13<T>.operator |(T, int)' must declare a body because it is not marked abstract, extern, or partial // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I13<T>.operator " + op + "(T, int)").WithLocation(62, 39), // (62,39): error CS0539: 'I13<T>.operator |(T, int)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I13<T>.operator " + op + "(T, int)").WithLocation(62, 39), // (67,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(67, 36), // (67,36): error CS0501: 'I14.operator |(I1, int)' must declare a body because it is not marked abstract, extern, or partial // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I14.operator " + op + "(I1, int)").WithLocation(67, 36), // (67,36): error CS0539: 'I14.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I14.operator " + op + "(I1, int)").WithLocation(67, 36) }; if (op is "==" or "!=") { expected = expected.Concat( new[] { // (12,17): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // I1 operator ==(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(12, 17), // (17,24): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static I1 operator ==(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(17, 24), // (42,16): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // T operator ==(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(42, 16), // (47,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static T operator ==(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(47, 23), } ).ToArray(); } else { expected = expected.Concat( new[] { // (12,17): error CS0558: User-defined operator 'I3.operator |(I1, int)' must be declared static and public // I1 operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I3.operator " + op + "(I1, int)").WithLocation(12, 17), // (42,16): error CS0558: User-defined operator 'I8<T>.operator |(T, int)' must be declared static and public // T operator |(T x, int y) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I8<T>.operator " + op + "(T, int)").WithLocation(42, 16) } ).ToArray(); } compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify(expected); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_04([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public interface I2<T> where T : I2<T> { abstract static T operator " + op + @"(T x); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static Test2 operator " + op + @"(Test2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15), // (14,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator +(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(14, 33), // (19,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator +(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(19, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public interface I2<T> where T : I2<T> { abstract static T operator " + op + @"(T x, int y); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static Test2 operator " + op + @"(Test2 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15), // (14,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator +(I1 x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(14, 33), // (19,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator +(T x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(19, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_05([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static Test1 operator " + op + @"(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (2,12): error CS8929: 'Test1.operator +(Test1)' cannot implement interface member 'I1<Test1>.operator +(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1)", "I1<Test1>.operator " + op + "(Test1)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (2,12): error CS8929: 'Test1.operator +(Test1)' cannot implement interface member 'I1<Test1>.operator +(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1)", "I1<Test1>.operator " + op + "(Test1)", "Test1").WithLocation(2, 12), // (9,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator +(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_05([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static Test1 operator " + op + @"(Test1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (2,12): error CS8929: 'Test1.operator >>(Test1, int)' cannot implement interface member 'I1<Test1>.operator >>(Test1, int)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1, int)", "I1<Test1>.operator " + op + "(Test1, int)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (2,12): error CS8929: 'Test1.operator >>(Test1, int)' cannot implement interface member 'I1<Test1>.operator >>(Test1, int)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1, int)", "I1<Test1>.operator " + op + "(Test1, int)", "Test1").WithLocation(2, 12), // (9,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator >>(T x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_06([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator +(I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_06([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator +(I1 x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_07([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } " + typeKeyword + @" C : I1<C> { public static C operator " + op + @"(C x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("C C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_07([CombinatorialValues("true", "false")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static bool operator " + op + @"(T x); } partial " + typeKeyword + @" C : I1<C> { public static bool operator " + op + @"(C x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1<T> where T : I1<T> { abstract static bool operator " + matchingOp + @"(T x); } partial " + typeKeyword + @" C { public static bool operator " + matchingOp + @"(C x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("System.Boolean C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_07([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() partial " + typeKeyword + @" C : I1<C> { public static C operator " + op + @"(C x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + matchingOp + @"(T x, int y); } partial " + typeKeyword + @" C { public static C operator " + matchingOp + @"(C x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.Equal(matchingOp is null ? 1 : 2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("C C." + opName + "(C x, System.Int32 y)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_08([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } " + typeKeyword + @" C : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.Equal("default", node.ToString()); Assert.Equal("I1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("I1 C.I1." + opName + "(I1 x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("I1 C.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_08([CombinatorialValues("true", "false")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1 { abstract static bool operator " + op + @"(I1 x); } partial " + typeKeyword + @" C : I1 { static bool I1.operator " + op + @"(I1 x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1 { abstract static bool operator " + matchingOp + @"(I1 x); } partial " + typeKeyword + @" C { static bool I1.operator " + matchingOp + @"(I1 x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("default", node.ToString()); Assert.Equal("System.Boolean", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("System.Boolean C.I1." + opName + "(I1 x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers(opName).OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("System.Boolean C.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_08([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } partial " + typeKeyword + @" C : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator " + matchingOp + @"(I1 x, int y); } partial " + typeKeyword + @" C { static I1 I1.operator " + matchingOp + @"(I1 x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("default", node.ToString()); Assert.Equal("I1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("I1 C.I1." + opName + "(I1 x, System.Int32 y)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers(opName).OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(matchingOp is null ? 1 : 2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("I1 C.I1." + opName + "(I1 x, System.Int32 y)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_09([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public class C2 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_09([CombinatorialValues("true", "false")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public partial interface I1 { abstract static bool operator " + op + @"(I1 x); } public partial class C2 : I1 { static bool I1.operator " + op + @"(I1 x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1 { abstract static bool operator " + matchingOp + @"(I1 x); } public partial class C2 { static bool I1.operator " + matchingOp + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Boolean C2.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_09([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public partial interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public partial class C2 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator " + matchingOp + @"(I1 x, int y); } public partial class C2 { static I1 I1.operator " + matchingOp + @"(I1 x, int y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2.I1." + opName + "(I1 x, System.Int32 y)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_10([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x) cil managed { .override method class I1 I1::" + opName + @"(class I1) IL_0000: ldnull IL_0001: ret } .method public hidebysig static specialname class I1 " + opName + @" (class I1 x) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static specialname class I1 " + opName + @" (class I1 x) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Equal(MethodKind.UserDefinedOperator, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C1.I1." + opName + "(I1 x)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2." + opName + "(I1 x)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_10([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x, int32 y) cil managed { .override method class I1 I1::" + opName + @"(class I1, int32) IL_0000: ldnull IL_0001: ret } .method public hidebysig static specialname class I1 " + opName + @" (class I1 x, int32 y) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static specialname class I1 " + opName + @" (class I1 x, int32 y) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Equal(MethodKind.UserDefinedOperator, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C1.I1." + opName + "(I1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2." + opName + "(I1 x, System.Int32 y)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_11([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname virtual static class I1 " + opName + @" ( class I1 x ) cil managed { IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,27): error CS0539: 'C1.operator ~(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator ~(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C1.operator " + op + "(I1)").WithLocation(4, 27) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("I1 I1." + opName + "(I1 x)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_11([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,27): error CS0539: 'C1.operator <(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator <(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C1.operator " + op + "(I1, int)").WithLocation(4, 27) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("I1 I1." + opName + "(I1 x, System.Int32 y)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_12([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x ) cil managed { } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x) cil managed { .override method class I1 I1::" + opName + @"(class I1) IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.operator ~(I1)' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.operator " + op + "(I1)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_12([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x, int32 y) cil managed { .override method class I1 I1::" + opName + @"(class I1, int32) IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.operator /(I1, int)' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.operator " + op + "(I1, int)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_13([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public class C2 : C1, I1<C2> { } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); } public partial class C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var i1 = c2.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.False(c2M01.HasSpecialName); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.False(c1M01.HasRuntimeSpecialName); Assert.True(c1M01.HasSpecialName); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.True(c2M01.HasSpecialName); Assert.Equal("C2 C1." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1<C2>." + opName + "(C2, C1)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C2 C1." + opName + @"(C2, C1)"" IL_0007: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_14([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static !T modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static C1 operator " + op + @"(C1 x) => default; } class C2 : I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("C1 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("C1 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("C1 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("C2 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""C1 C1." + opName + @"(C1)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_14([CombinatorialValues("true", "false")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static bool modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static bool operator " + op + @"(C1 x) => default; public static bool operator " + (op == "true" ? "false" : "true") + @"(C1 x) => default; } class C2 : I1<C2> { static bool I1<C2>.operator " + op + @"(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("System.Boolean modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("System.Boolean C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("System.Boolean C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("System.Boolean modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""bool C1." + opName + @"(C1)"" IL_0006: ret } "); } private static string MatchingBinaryOperator(string op) { return op switch { "<" => ">", ">" => "<", "<=" => ">=", ">=" => "<=", "==" => "!=", "!=" => "==", _ => null }; } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_14([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static !T modopt(I1`1) " + opName + @" ( !T x, int32 y ) cil managed { } } "; string matchingOp = MatchingBinaryOperator(op); string additionalMethods = ""; if (matchingOp is object) { additionalMethods = @" public static C1 operator " + matchingOp + @"(C1 x, int y) => default; "; } var source1 = @" #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() class C1 : I1<C1> { public static C1 operator " + op + @"(C1 x, int y) => default; " + additionalMethods + @" } class C2 : I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x, int y) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("C1 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("C1 C1." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("C1 C1." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("C2 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x, System.Int32 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1, int)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C1 C1." + opName + @"(C1, int)"" IL_0007: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_15([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public partial class C2 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M02 = c3.BaseType().GetMembers("I1." + opName).OfType<MethodSymbol>().Single(); Assert.Equal("I1 C2.I1." + opName + "(I1 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Fact] public void ImplementAbstractStaticUnaryTrueFalseOperator_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static bool operator true(I1 x); abstract static bool operator false(I1 x); } public partial class C2 : I1 { static bool I1.operator true(I1 x) => default; static bool I1.operator false(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("op_True").OfType<MethodSymbol>().Single(); var m02 = c3.Interfaces().Single().GetMembers("op_False").OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMembers("I1.op_True").OfType<MethodSymbol>().Single(); Assert.Equal("System.Boolean C2.I1.op_True(I1 x)", c2M01.ToTestDisplayString()); Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); var c2M02 = c3.BaseType().GetMembers("I1.op_False").OfType<MethodSymbol>().Single(); Assert.Equal("System.Boolean C2.I1.op_False(I1 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_15([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); abstract static T operator " + op + @"(T x, C2 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public partial class C2 : C1, I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x, C2 y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); abstract static T operator " + matchingOp + @"(T x, C2 y); } public partial class C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } public partial class C2 { static C2 I1<C2>.operator " + matchingOp + @"(C2 x, C2 y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().First(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C2 C1." + opName + "(C2 x, C1 y)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().ElementAt(1); var c2M02 = c3.BaseType().GetMembers("I1<C2>." + opName).OfType<MethodSymbol>().First(); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C2 y)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_16([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A new implicit implementation is properly considered. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 : I1<C2> { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public partial class C2 : C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); } public partial class C1 : I1<C2> { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } public partial class C2 : C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1<C2>." + opName + "(C2, C1)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C2 C2." + opName + @"(C2, C1)"" IL_0007: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C2 C2." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C2 C3.I1<C2>." + opName + "(C2 x, C1 y)", c3M01.ToTestDisplayString()); Assert.Equal(m01, c3M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_18([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, U y) => default; "; var nonGeneric = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, int y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> { public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, U y) => default; public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>." + opName + "(C1<T, U> x, U y)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>." + opName + "(C1<T, U> x, U y)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_20([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // Same as ImplementAbstractStaticBinaryOperator_18 only implementation is explicit in source. var generic = @" static C1<T, U> I1<C1<T, U>, U>.operator " + op + @"(C1<T, U> x, U y) => default; "; var nonGeneric = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, int y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> : I1<C1<T, U>, U> { public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, int y) => default; static C1<T, U> I1<C1<T, U>, U>.operator " + matchingOp + @"(C1<T, U> x, U y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>.I1<C1<T, U>, U>." + opName + "(C1<T, U> x, U y)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_22([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implicit implementation is in an intermediate base. var generic = @" public static C11<T, U> operator " + op + @"(C11<T, U> x, C1<T, U> y) => default; "; var nonGeneric = @" public static C11<T, U> operator " + op + @"(C11<T, int> x, C1<T, U> y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T, U> : C1<T, U>, I1<C11<T, U>, C1<T, U>> { } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> { public static C11<T, U> operator " + matchingOp + @"(C11<T, U> x, C1<T, U> y) => default; public static C11<T, U> operator " + matchingOp + @"(C11<T, int> x, C1<T, U> y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C11<int, int>, I1<C11<int, int>, C1<int, int>> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "C11<T, U> C11<T, U>.I1<C11<T, U>, C1<T, U>>." + opName + "(C11<T, U> x, C1<T, U> y)" : "C11<T, U> C1<T, U>." + opName + "(C11<T, U> x, C1<T, U> y)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } class C1 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } class C2 : I1 { private static I1 I1.operator " + op + @"(I1 x) => default; } class C3 : I1 { protected static I1 I1.operator " + op + @"(I1 x) => default; } class C4 : I1 { internal static I1 I1.operator " + op + @"(I1 x) => default; } class C5 : I1 { protected internal static I1 I1.operator " + op + @"(I1 x) => default; } class C6 : I1 { private protected static I1 I1.operator " + op + @"(I1 x) => default; } class C7 : I1 { public static I1 I1.operator " + op + @"(I1 x) => default; } class C8 : I1 { static partial I1 I1.operator " + op + @"(I1 x) => default; } class C9 : I1 { async static I1 I1.operator " + op + @"(I1 x) => default; } class C10 : I1 { unsafe static I1 I1.operator " + op + @"(I1 x) => default; } class C11 : I1 { static readonly I1 I1.operator " + op + @"(I1 x) => default; } class C12 : I1 { extern static I1 I1.operator " + op + @"(I1 x); } class C13 : I1 { abstract static I1 I1.operator " + op + @"(I1 x) => default; } class C14 : I1 { virtual static I1 I1.operator " + op + @"(I1 x) => default; } class C15 : I1 { sealed static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.WRN_ExternMethodNoImplementation or (int)ErrorCode.ERR_OpTFRetType or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (16,35): error CS0106: The modifier 'private' is not valid for this item // private static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private").WithLocation(16, 35), // (22,37): error CS0106: The modifier 'protected' is not valid for this item // protected static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected").WithLocation(22, 37), // (28,36): error CS0106: The modifier 'internal' is not valid for this item // internal static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("internal").WithLocation(28, 36), // (34,46): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected internal").WithLocation(34, 46), // (40,45): error CS0106: The modifier 'private protected' is not valid for this item // private protected static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private protected").WithLocation(40, 45), // (46,34): error CS0106: The modifier 'public' is not valid for this item // public static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("public").WithLocation(46, 34), // (52,12): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // static partial I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(52, 12), // (58,33): error CS0106: The modifier 'async' is not valid for this item // async static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("async").WithLocation(58, 33), // (70,36): error CS0106: The modifier 'readonly' is not valid for this item // static readonly I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("readonly").WithLocation(70, 36), // (82,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(82, 36), // (88,35): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("virtual").WithLocation(88, 35), // (94,34): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("sealed").WithLocation(94, 34) ); } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } struct C1 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C2 : I1 { private static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C3 : I1 { protected static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C4 : I1 { internal static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C5 : I1 { protected internal static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C6 : I1 { private protected static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C7 : I1 { public static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C8 : I1 { static partial I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C9 : I1 { async static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C10 : I1 { unsafe static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C11 : I1 { static readonly I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C12 : I1 { extern static I1 I1.operator " + op + @"(I1 x, int y); } struct C13 : I1 { abstract static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C14 : I1 { virtual static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C15 : I1 { sealed static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.WRN_ExternMethodNoImplementation or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (16,35): error CS0106: The modifier 'private' is not valid for this item // private static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private").WithLocation(16, 35), // (22,37): error CS0106: The modifier 'protected' is not valid for this item // protected static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected").WithLocation(22, 37), // (28,36): error CS0106: The modifier 'internal' is not valid for this item // internal static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("internal").WithLocation(28, 36), // (34,46): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected internal").WithLocation(34, 46), // (40,45): error CS0106: The modifier 'private protected' is not valid for this item // private protected static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private protected").WithLocation(40, 45), // (46,34): error CS0106: The modifier 'public' is not valid for this item // public static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("public").WithLocation(46, 34), // (52,12): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // static partial I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(52, 12), // (58,33): error CS0106: The modifier 'async' is not valid for this item // async static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("async").WithLocation(58, 33), // (70,36): error CS0106: The modifier 'readonly' is not valid for this item // static readonly I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("readonly").WithLocation(70, 36), // (82,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(82, 36), // (88,35): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("virtual").WithLocation(88, 35), // (94,34): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("sealed").WithLocation(94, 34) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1<T> where T : struct { abstract static I1<T> operator " + op + @"(I1<T> x); } class C1 { static I1<int> I1<int>.operator " + op + @"(I1<int> x) => default; } class C2 : I1<C2> { static I1<C2> I1<C2>.operator " + op + @"(I1<C2> x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OpTFRetType or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (9,20): error CS0540: 'C1.I1<int>.operator -(I1<int>)': containing type does not implement interface 'I1<int>' // static I1<int> I1<int>.operator -(I1<int> x) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<int>").WithArguments("C1.I1<int>.operator " + op + "(I1<int>)", "I1<int>").WithLocation(9, 20), // (12,7): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // class C2 : I1<C2> Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 7), // (14,19): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 19), // (14,35): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, op).WithArguments("I1<T>", "T", "C2").WithLocation(14, 35), // (14,44): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("I1<T>", "T", "C2").WithLocation(14, 44 + op.Length - 1) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1<T> where T : class { abstract static I1<T> operator " + op + @"(I1<T> x, int y); } struct C1 { static I1<string> I1<string>.operator " + op + @"(I1<string> x, int y) => default; } struct C2 : I1<C2> { static I1<C2> I1<C2>.operator " + op + @"(I1<C2> x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (9,23): error CS0540: 'C1.I1<string>.operator %(I1<string>, int)': containing type does not implement interface 'I1<string>' // static I1<string> I1<string>.operator %(I1<string> x, int y) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<string>").WithArguments("C1.I1<string>.operator " + op + "(I1<string>, int)", "I1<string>").WithLocation(9, 23), // (12,8): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // struct C2 : I1<C2> Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 8), // (14,19): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 19), // (14,35): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, op).WithArguments("I1<T>", "T", "C2").WithLocation(14, 35), // (14,44): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "x").WithArguments("I1<T>", "T", "C2").WithLocation(14, 44 + op.Length - 1) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public int M01 { get; set; } } " + typeKeyword + @" C3 : I1 { static int M01 { get; set; } } " + typeKeyword + @" C4 : I1 { int I1.M01 { get; set; } } " + typeKeyword + @" C5 : I1 { public static long M01 { get; set; } } " + typeKeyword + @" C6 : I1 { static long I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,12): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 12), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'int'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,20): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static long I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 20) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract int M01 { get; set; } } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static int M01 { get; set; } } " + typeKeyword + @" C3 : I1 { int M01 { get; set; } } " + typeKeyword + @" C4 : I1 { static int I1.M01 { get; set; } } " + typeKeyword + @" C5 : I1 { public long M01 { get; set; } } " + typeKeyword + @" C6 : I1 { long I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,19): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 19), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'int'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,13): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // long I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 13) ); } [Fact] public void ImplementAbstractStaticProperty_03() { var source1 = @" public interface I1 { abstract static int M01 { get; set; } } interface I2 : I1 {} interface I3 : I1 { public virtual int M01 { get => 0; set{} } } interface I4 : I1 { static int M01 { get; set; } } interface I5 : I1 { int I1.M01 { get => 0; set{} } } interface I6 : I1 { static int I1.M01 { get => 0; set{} } } interface I7 : I1 { abstract static int M01 { get; set; } } interface I8 : I1 { abstract static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,24): warning CS0108: 'I3.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // public virtual int M01 { get => 0; set{} } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01", "I1.M01").WithLocation(12, 24), // (17,16): warning CS0108: 'I4.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // static int M01 { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01", "I1.M01").WithLocation(17, 16), // (22,12): error CS0539: 'I5.M01' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01").WithLocation(22, 12), // (27,19): error CS0106: The modifier 'static' is not valid for this item // static int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 19), // (27,19): error CS0539: 'I6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01").WithLocation(27, 19), // (32,25): warning CS0108: 'I7.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01", "I1.M01").WithLocation(32, 25), // (37,28): error CS0106: The modifier 'static' is not valid for this item // abstract static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 28), // (37,28): error CS0539: 'I8.M01' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01").WithLocation(37, 28) ); foreach (var m01 in compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers()) { Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } abstract static int M02 { get; set; } } "; var source2 = typeKeyword + @" Test: I1 { static int I1.M01 { get; set; } public static int M02 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,19): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 19) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,19): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 19), // (10,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 25), // (11,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int M02 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 25) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } "; var source2 = typeKeyword + @" Test1: I1 { public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.set' cannot implement interface member 'I1.M01.set' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.set", "I1.M01.set", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.get' cannot implement interface member 'I1.M01.get' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.get", "I1.M01.get", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.set' cannot implement interface member 'I1.M01.set' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.set", "I1.M01.set", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.get' cannot implement interface member 'I1.M01.get' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.get", "I1.M01.get", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12), // (9,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(9, 31), // (9,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(9, 36) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } "; var source2 = typeKeyword + @" Test1: I1 { static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,19): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 19) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,19): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 19), // (9,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(9, 31), // (9,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(9, 36) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C : I1 { public static int M01 { get => 0; set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.False(cM01Get.HasRuntimeSpecialName); Assert.True(cM01Get.HasSpecialName); Assert.Equal("System.Int32 C.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.False(cM01Set.HasRuntimeSpecialName); Assert.True(cM01Set.HasSpecialName); Assert.Equal("void C.M01.set", cM01Set.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticReadonlyProperty_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; } } " + typeKeyword + @" C : I1 { public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Null(m01.SetMethod); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C.M01.set", cM01Set.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C : I1 { static int I1.M01 { get => 0; set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.I1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.False(cM01Get.HasRuntimeSpecialName); Assert.True(cM01Get.HasSpecialName); Assert.Equal("System.Int32 C.I1.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.False(cM01Set.HasRuntimeSpecialName); Assert.True(cM01Set.HasSpecialName); Assert.Equal("void C.I1.M01.set", cM01Set.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<PropertySymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var cM01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.I1.M01 { get; set; }", cM01.ToTestDisplayString()); Assert.Same(cM01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(cM01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, cM01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, cM01.SetMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig specialname static int32 I1.get_M01 () cil managed { .override method int32 I1::get_M01() IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static void I1.set_M01 ( int32 'value' ) cil managed { .override method void I1::set_M01(int32) IL_0000: ret } .property instance int32 I1.M01() { .get int32 C1::I1.get_M01() .set void C1::I1.set_M01(int32) } .method public hidebysig specialname static int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname static void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 C1::get_M01() .set void C1::set_M01(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig specialname static int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname static void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 C2::get_M01() .set void C2::set_M01(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = (PropertySymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1.I1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.Same(c1M01.GetMethod, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c2.FindImplementationForInterfaceMember(m01.SetMethod)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c4.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c4.FindImplementationForInterfaceMember(m01.SetMethod)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (PropertySymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.Same(c2M01.GetMethod, c5.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c2M01.SetMethod, c5.FindImplementationForInterfaceMember(m01.SetMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticProperty_11() { // Ignore invalid metadata (non-abstract static virtual method). scenario1(); scenario2(); scenario3(); void scenario1() { var ilSource = @" .class interface public auto ansi abstract I1 { .method private hidebysig specialname static virtual int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static virtual void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,18): error CS0539: 'C1.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01").WithLocation(4, 18) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c.FindImplementationForInterfaceMember(m01)); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); } } void scenario2() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method private hidebysig specialname static virtual void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source2 = @" public class C1 : I1 { static int I1.M01 { get; } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, sourceSymbolValidator: validate2, symbolValidator: validate2, verify: Verification.Skipped).VerifyDiagnostics(); void validate2(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.I1.M01 { get; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.I1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(cM01.SetMethod); Assert.Null(c.FindImplementationForInterfaceMember(m01Set)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,29): error CS0550: 'C1.I1.M01.set' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("C1.I1.M01.set", "I1.M01").WithLocation(4, 29) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static int M01 { get; } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation5, sourceSymbolValidator: validate5, symbolValidator: validate5, verify: Verification.Skipped).VerifyDiagnostics(); void validate5(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } } var source6 = @" public class C1 : I1 { public static int M01 { set{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.get' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.get").WithLocation(2, 19) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); var source7 = @" public class C1 : I1 { static int I1.M01 { set{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.get' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.get").WithLocation(2, 19), // (4,18): error CS0551: Explicit interface implementation 'C1.I1.M01' is missing accessor 'I1.M01.get' // static int I1.M01 { set{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "M01").WithArguments("C1.I1.M01", "I1.M01.get").WithLocation(4, 18), // (4,24): error CS0550: 'C1.I1.M01.set' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { set{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("C1.I1.M01.set", "I1.M01").WithLocation(4, 24) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); } void scenario3() { var ilSource = @" .class interface public auto ansi abstract I1 { .method private hidebysig specialname static virtual int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source2 = @" public class C1 : I1 { static int I1.M01 { set{} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, sourceSymbolValidator: validate2, symbolValidator: validate2, verify: Verification.Skipped).VerifyDiagnostics(); void validate2(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.I1.M01 { set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.I1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(cM01.GetMethod); Assert.Null(c.FindImplementationForInterfaceMember(m01Get)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,24): error CS0550: 'C1.I1.M01.get' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C1.I1.M01.get", "I1.M01").WithLocation(4, 24) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.SetMethod, c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static int M01 { set{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation5, sourceSymbolValidator: validate5, symbolValidator: validate5, verify: Verification.Skipped).VerifyDiagnostics(); void validate5(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } var source6 = @" public class C1 : I1 { public static int M01 { get; } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.set' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.set").WithLocation(2, 19) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); var source7 = @" public class C1 : I1 { static int I1.M01 { get; } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.set' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.set").WithLocation(2, 19), // (4,18): error CS0551: Explicit interface implementation 'C1.I1.M01' is missing accessor 'I1.M01.set' // static int I1.M01 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "M01").WithArguments("C1.I1.M01", "I1.M01.set").WithLocation(4, 18), // (4,24): error CS0550: 'C1.I1.M01.get' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C1.I1.M01.get", "I1.M01").WithLocation(4, 24) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig specialname static int32 I1.get_M01 () cil managed { .override method int32 I1::get_M01() IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static void I1.set_M01 ( int32 'value' ) cil managed { .override method void I1::set_M01(int32) IL_0000: ret } .property instance int32 I1.M01() { .get int32 I2::I1.get_M01() .set void I2::I1.set_M01(int32) } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.SetMethod)); var i2M01 = i2.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, i2M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, i2M01.SetMethod.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticProperty_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static int M01 { get; set; } } class C1 { public static int M01 { get; set; } } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Get = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.GetMethod); var c2M01Set = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.SetMethod); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Get.MethodKind); Assert.False(c2M01Get.HasRuntimeSpecialName); Assert.False(c2M01Get.HasSpecialName); Assert.Equal("System.Int32 C2.I1.get_M01()", c2M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c2M01Get.ExplicitInterfaceImplementations.Single()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Set.MethodKind); Assert.False(c2M01Set.HasRuntimeSpecialName); Assert.False(c2M01Set.HasSpecialName); Assert.Equal("void C2.I1.set_M01(System.Int32 value)", c2M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c2M01Set.ExplicitInterfaceImplementations.Single()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c2M01); var c1M01 = module.GlobalNamespace.GetMember<PropertySymbol>("C1.M01"); var c1M01Get = c1M01.GetMethod; var c1M01Set = c1M01.SetMethod; Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c1M01Get.MethodKind); Assert.False(c1M01Get.HasRuntimeSpecialName); Assert.True(c1M01Get.HasSpecialName); Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c1M01Set.MethodKind); Assert.False(c1M01Set.HasRuntimeSpecialName); Assert.True(c1M01Set.HasSpecialName); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); } else { Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.PropertyGet, c2M01Get.MethodKind); Assert.False(c2M01Get.HasRuntimeSpecialName); Assert.True(c2M01Get.HasSpecialName); Assert.Same(c2M01.GetMethod, c2M01Get); Assert.Empty(c2M01Get.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.PropertySet, c2M01Set.MethodKind); Assert.False(c2M01Set.HasRuntimeSpecialName); Assert.True(c2M01Set.HasSpecialName); Assert.Same(c2M01.SetMethod, c2M01Set); Assert.Empty(c2M01Set.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.get_M01", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C1.M01.get"" IL_0005: ret } "); verifier.VerifyIL("C2.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.set"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticProperty_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void modopt(I1) set_M01 ( int32 modopt(I1) 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void modopt(I1) I1::set_M01(int32 modopt(I1)) } } .class interface public auto ansi abstract I2 { .method public hidebysig specialname abstract virtual static int32 modopt(I2) get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 modopt(I2) 'value' ) cil managed { } .property int32 modopt(I2) M01() { .get int32 modopt(I2) I2::get_M01() .set void I2::set_M01(int32 modopt(I2)) } } "; var source1 = @" class C1 : I1 { public static int M01 { get; set; } } class C2 : I1 { static int I1.M01 { get; set; } } class C3 : I2 { static int I2.M01 { get; set; } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = (PropertySymbol)c1.FindImplementationForInterfaceMember(m01); var c1M01Get = c1M01.GetMethod; var c1M01Set = c1M01.SetMethod; Assert.Equal("System.Int32 C1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Equal(MethodKind.PropertyGet, c1M01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", c1M01Get.ToTestDisplayString()); Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Same(c1M01Get, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Equal(MethodKind.PropertySet, c1M01Set.MethodKind); Assert.Equal("void C1.M01.set", c1M01Set.ToTestDisplayString()); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Same(m01.GetMethod, c1M01Get.ExplicitInterfaceImplementations.Single()); c1M01Set = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Set.MethodKind); Assert.Equal("void modopt(I1) C1.I1.set_M01(System.Int32 modopt(I1) value)", c1M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c1M01Set.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); } else { Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); Assert.Same(c1M01Set, c1.FindImplementationForInterfaceMember(m01.SetMethod)); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Get = c2M01.GetMethod; var c2M01Set = c2M01.SetMethod; Assert.Equal("System.Int32 C2.I1.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c2M01Get.MethodKind); Assert.Equal("System.Int32 C2.I1.M01.get", c2M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c2M01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Get, c2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c2M01Set.MethodKind); Assert.Equal("void modopt(I1) C2.I1.M01.set", c2M01Set.ToTestDisplayString()); Assert.Equal("System.Int32 modopt(I1) value", c2M01Set.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.SetMethod, c2M01Set.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Set, c2.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(c2M01, c2.GetMembers().OfType<PropertySymbol>().Single()); Assert.Equal(2, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var c3 = module.GlobalNamespace.GetTypeMember("C3"); m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c3M01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); var c3M01Get = c3M01.GetMethod; var c3M01Set = c3M01.SetMethod; Assert.Equal("System.Int32 modopt(I2) C3.I2.M01 { get; set; }", c3M01.ToTestDisplayString()); Assert.True(c3M01.IsStatic); Assert.False(c3M01.IsAbstract); Assert.False(c3M01.IsVirtual); Assert.Same(m01, c3M01.ExplicitInterfaceImplementations.Single()); Assert.True(c3M01Get.IsStatic); Assert.False(c3M01Get.IsAbstract); Assert.False(c3M01Get.IsVirtual); Assert.False(c3M01Get.IsMetadataVirtual()); Assert.False(c3M01Get.IsMetadataFinal); Assert.False(c3M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c3M01Get.MethodKind); Assert.Equal("System.Int32 modopt(I2) C3.I2.M01.get", c3M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c3M01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(c3M01Get, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.True(c3M01Set.IsStatic); Assert.False(c3M01Set.IsAbstract); Assert.False(c3M01Set.IsVirtual); Assert.False(c3M01Set.IsMetadataVirtual()); Assert.False(c3M01Set.IsMetadataFinal); Assert.False(c3M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c3M01Set.MethodKind); Assert.Equal("void C3.I2.M01.set", c3M01Set.ToTestDisplayString()); Assert.Equal("System.Int32 modopt(I2) value", c3M01Set.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.SetMethod, c3M01Set.ExplicitInterfaceImplementations.Single()); Assert.Same(c3M01Set, c3.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(c3M01, c3.GetMembers().OfType<PropertySymbol>().Single()); Assert.Equal(2, c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); } verifier.VerifyIL("C1.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.set"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStatiProperty_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static int M01 { get; set; } abstract static int M02 { get; set; } } public class C1 { public static int M01 { get; set; } } public class C2 : C1, I1 { static int I1.M02 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<PropertySymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<PropertySymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<PropertySymbol>("M01"); Assert.Equal("System.Int32 C1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); var c1M01Get = c1M01.GetMethod; Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); var c1M01Set = c1M01.SetMethod; Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01Get = c3.FindImplementationForInterfaceMember(m01.GetMethod); Assert.Equal("System.Int32 C2.I1.get_M01()", c2M01Get.ToTestDisplayString()); var c2M01Set = c3.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal("void C2.I1.set_M01(System.Int32 value)", c2M01Set.ToTestDisplayString()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c3.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<PropertySymbol>().Single(); var c2M02 = c3.BaseType().GetMember<PropertySymbol>("I1.M02"); Assert.Equal("System.Int32 C2.I1.M02 { get; set; }", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c2M02.GetMethod, c3.FindImplementationForInterfaceMember(m02.GetMethod)); Assert.Same(c2M02.SetMethod, c3.FindImplementationForInterfaceMember(m02.SetMethod)); } } [Fact] public void ImplementAbstractStaticProperty_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1 : I1 { public static int M01 { get; set; } } public class C2 : C1 { new public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.get_M01", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C2.M01.get"" IL_0005: ret } "); verifier.VerifyIL("C3.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.set"" IL_0006: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c2M01 = c3.BaseType().GetMember<PropertySymbol>("M01"); var c2M01Get = c2M01.GetMethod; var c2M01Set = c2M01.SetMethod; Assert.Equal("System.Int32 C2.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.Empty(c2M01Get.ExplicitInterfaceImplementations); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); Assert.Empty(c2M01Set.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); // Forwarding methods for accessors aren't tied to a property Assert.Null(c3M01); var c3M01Get = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.GetMethod); Assert.Equal("System.Int32 C3.I1.get_M01()", c3M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c3M01Get.ExplicitInterfaceImplementations.Single()); var c3M01Set = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal("void C3.I1.set_M01(System.Int32 value)", c3M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c3M01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c2M01Get, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c2M01Set, c3.FindImplementationForInterfaceMember(m01.SetMethod)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_19(bool genericFirst) { // An "ambiguity" in implicit/explicit implementation declared in generic base class. var generic = @" public static T M01 { get; set; } "; var nonGeneric = @" static int I1.M01 { get; set; } "; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<PropertySymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1<T>.I1.M01 { get; set; }", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_20(bool genericFirst) { // Same as ImplementAbstractStaticProperty_19 only interface is generic too. var generic = @" static T I1<T>.M01 { get; set; } "; var nonGeneric = @" public static int M01 { get; set; } "; var source1 = @" public interface I1<T> { abstract static T M01 { get; set; } } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<PropertySymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("T C1<T>.I1<T>.M01 { get; set; }", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public event System.Action M01; } " + typeKeyword + @" C3 : I1 { static event System.Action M01; } " + typeKeyword + @" C4 : I1 { event System.Action I1.M01 { add{} remove{}} } " + typeKeyword + @" C5 : I1 { public static event System.Action<int> M01; } " + typeKeyword + @" C6 : I1 { static event System.Action<int> I1.M01 { add{} remove{}} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,28): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.M01 { add{} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 28), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'Action'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "System.Action").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,40): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action<int> I1.M01 { add{} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 40) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract event System.Action M01; } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static event System.Action M01; } " + typeKeyword + @" C3 : I1 { event System.Action M01; } " + typeKeyword + @" C4 : I1 { static event System.Action I1.M01 { add{} remove{} } } " + typeKeyword + @" C5 : I1 { public event System.Action<int> M01; } " + typeKeyword + @" C6 : I1 { event System.Action<int> I1.M01 { add{} remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,35): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 35), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'Action'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "System.Action").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,33): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action<int> I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 33) ); } [Fact] public void ImplementAbstractStaticEvent_03() { var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract static event System.Action M01; } interface I2 : I1 {} interface I3 : I1 { public virtual event System.Action M01 { add{} remove{} } } interface I4 : I1 { static event System.Action M01; } interface I5 : I1 { event System.Action I1.M01 { add{} remove{} } } interface I6 : I1 { static event System.Action I1.M01 { add{} remove{} } } interface I7 : I1 { abstract static event System.Action M01; } interface I8 : I1 { abstract static event System.Action I1.M01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,40): warning CS0108: 'I3.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // public virtual event System.Action M01 { add{} remove{} } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01", "I1.M01").WithLocation(12, 40), // (17,32): warning CS0108: 'I4.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // static event System.Action M01; Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01", "I1.M01").WithLocation(17, 32), // (22,28): error CS0539: 'I5.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01").WithLocation(22, 28), // (27,35): error CS0106: The modifier 'static' is not valid for this item // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 35), // (27,35): error CS0539: 'I6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01").WithLocation(27, 35), // (32,41): warning CS0108: 'I7.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // abstract static event System.Action M01; Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01", "I1.M01").WithLocation(32, 41), // (37,44): error CS0106: The modifier 'static' is not valid for this item // abstract static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 44), // (37,44): error CS0539: 'I8.M01' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static event System.Action I1.M01; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01").WithLocation(37, 44) ); foreach (var m01 in compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers()) { Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; abstract static event System.Action M02; } "; var source2 = typeKeyword + @" Test: I1 { static event System.Action I1.M01 { add{} remove => throw null; } public static event System.Action M02; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,35): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static event System.Action I1.M01 { add{} remove => throw null; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 35), // (5,39): warning CS0067: The event 'Test.M02' is never used // public static event System.Action M02; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "M02").WithArguments("Test.M02").WithLocation(5, 39) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,35): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static event System.Action I1.M01 { add{} remove => throw null; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 35), // (5,39): warning CS0067: The event 'Test.M02' is never used // public static event System.Action M02; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "M02").WithArguments("Test.M02").WithLocation(5, 39), // (10,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 41), // (11,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action M02; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } "; var source2 = typeKeyword + @" Test1: I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.remove' cannot implement interface member 'I1.M01.remove' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.remove", "I1.M01.remove", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.add' cannot implement interface member 'I1.M01.add' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.add", "I1.M01.add", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.remove' cannot implement interface member 'I1.M01.remove' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.remove", "I1.M01.remove", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.add' cannot implement interface member 'I1.M01.add' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.add", "I1.M01.add", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12), // (9,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } "; var source2 = typeKeyword + @" Test1: I1 { static event System.Action I1.M01 { add => throw null; remove => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static event System.Action I1.M01 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 35) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static event System.Action I1.M01 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 35), // (9,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C : I1 { public static event System.Action M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; var m01Remove = m01.RemoveMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.False(cM01Add.HasRuntimeSpecialName); Assert.True(cM01Add.HasSpecialName); Assert.Equal("void C.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.False(cM01Remove.HasRuntimeSpecialName); Assert.True(cM01Remove.HasSpecialName); Assert.Equal("void C.M01.remove", cM01Remove.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Add.ExplicitInterfaceImplementations); Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C : I1 { static event System.Action I1.M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; var m01Remove = m01.RemoveMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C.I1.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.False(cM01Add.HasRuntimeSpecialName); Assert.True(cM01Add.HasSpecialName); Assert.Equal("void C.I1.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.False(cM01Remove.HasRuntimeSpecialName); Assert.True(cM01Remove.HasSpecialName); Assert.Equal("void C.I1.M01.remove", cM01Remove.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static event System.Action M01; } public class C1 { public static event System.Action M01 { add => throw null; remove {} } } public class C2 : C1, I1 { static event System.Action I1.M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<EventSymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var cM01 = (EventSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C2.I1.M01", cM01.ToTestDisplayString()); Assert.Same(cM01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(cM01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, cM01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, cM01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig specialname static void I1.add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::add_M01(class [mscorlib]System.Action) IL_0000: ret } .method private hidebysig specialname static void I1.remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::remove_M01(class [mscorlib]System.Action) IL_0000: ret } .event [mscorlib]System.Action I1.M01 { .addon void C1::I1.add_M01(class [mscorlib]System.Action) .removeon void C1::I1.remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void C1::add_M01(class [mscorlib]System.Action) .removeon void C1::remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig specialname static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void C2::add_M01(class [mscorlib]System.Action) .removeon void C2::remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c1M01 = (EventSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C1.I1.M01", c1M01.ToTestDisplayString()); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c2.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c4.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c4.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (EventSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C2.M01", c2M01.ToTestDisplayString()); Assert.Same(c2M01.AddMethod, c5.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c2M01.RemoveMethod, c5.FindImplementationForInterfaceMember(m01.RemoveMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticEvent_11() { // Ignore invalid metadata (non-abstract static virtual method). scenario1(); scenario2(); scenario3(); void scenario1() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname static virtual void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static virtual void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,34): error CS0539: 'C1.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c.FindImplementationForInterfaceMember(m01)); Assert.Null(c.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c.FindImplementationForInterfaceMember(m01.RemoveMethod)); } } void scenario2() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname static virtual void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { add {} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add {} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C1.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.Equal("void C1.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.Equal("void C1.M01.remove", cM01Remove.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.RemoveMethod)); if (module is PEModuleSymbol) { Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01Add.ExplicitInterfaceImplementations); } Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,46): error CS0550: 'C1.I1.M01.remove' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "remove").WithArguments("C1.I1.M01.remove", "I1.M01").WithLocation(4, 46) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static event System.Action M01 { add{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics( // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { add{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation5.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source6 = @" public class C1 : I1 { public static event System.Action M01 { remove{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.add' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.add").WithLocation(2, 19), // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source7 = @" public class C1 : I1 { static event System.Action I1.M01 { remove{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.add' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.add").WithLocation(2, 19), // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34), // (4,40): error CS0550: 'C1.I1.M01.remove' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "remove").WithArguments("C1.I1.M01.remove", "I1.M01").WithLocation(4, 40) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } void scenario3() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname static virtual void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { remove {} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add {} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var m01Remove = m01.RemoveMethod; Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C1.M01", cM01.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.Equal("void C1.M01.remove", cM01Remove.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.Equal("void C1.M01.add", cM01Add.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.AddMethod)); if (module is PEModuleSymbol) { Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Add.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,40): error CS0550: 'C1.I1.M01.add' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "add").WithArguments("C1.I1.M01.add", "I1.M01").WithLocation(4, 40) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static event System.Action M01 { remove{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics( // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation5.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); var source6 = @" public class C1 : I1 { public static event System.Action M01 { add{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.remove' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.remove").WithLocation(2, 19), // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source7 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.remove' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.remove").WithLocation(2, 19), // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34), // (4,40): error CS0550: 'C1.I1.M01.add' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "add").WithArguments("C1.I1.M01.add", "I1.M01").WithLocation(4, 40) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig specialname static void I1.add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::add_M01(class [mscorlib]System.Action) IL_0000: ret } .method private hidebysig specialname static void I1.remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::remove_M01(class [mscorlib]System.Action) IL_0000: ret } .event [mscorlib]System.Action I1.M01 { .addon void I2::I1.add_M01(class [mscorlib]System.Action) .removeon void I2::I1.remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.RemoveMethod)); var i2M01 = i2.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, i2M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, i2M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticEvent_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static event System.Action M01; } class C1 { public static event System.Action M01 { add => throw null; remove{} } } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Add = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.AddMethod); var c2M01Remove = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Add.MethodKind); Assert.False(c2M01Add.HasRuntimeSpecialName); Assert.False(c2M01Add.HasSpecialName); Assert.Equal("void C2.I1.add_M01(System.Action value)", c2M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c2M01Add.ExplicitInterfaceImplementations.Single()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Remove.MethodKind); Assert.False(c2M01Remove.HasRuntimeSpecialName); Assert.False(c2M01Remove.HasSpecialName); Assert.Equal("void C2.I1.remove_M01(System.Action value)", c2M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c2M01Remove.ExplicitInterfaceImplementations.Single()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c2M01); var c1M01 = module.GlobalNamespace.GetMember<EventSymbol>("C1.M01"); var c1M01Add = c1M01.AddMethod; var c1M01Remove = c1M01.RemoveMethod; Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c1M01Add.MethodKind); Assert.False(c1M01Add.HasRuntimeSpecialName); Assert.True(c1M01Add.HasSpecialName); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c1M01Remove.MethodKind); Assert.False(c1M01Remove.HasRuntimeSpecialName); Assert.True(c1M01Remove.HasSpecialName); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); } else { Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Equal("event System.Action C1.M01", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.EventAdd, c2M01Add.MethodKind); Assert.False(c2M01Add.HasRuntimeSpecialName); Assert.True(c2M01Add.HasSpecialName); Assert.Same(c2M01.AddMethod, c2M01Add); Assert.Empty(c2M01Add.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.EventRemove, c2M01Remove.MethodKind); Assert.False(c2M01Remove.HasRuntimeSpecialName); Assert.True(c2M01Remove.HasSpecialName); Assert.Same(c2M01.RemoveMethod, c2M01Remove); Assert.Empty(c2M01Remove.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C2.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.remove"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticEvent_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action`1<int32 modopt(I1)> 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action`1<int32 modopt(I1)> 'value' ) cil managed { } .event class [mscorlib]System.Action`1<int32 modopt(I1)> M01 { .addon void I1::add_M01(class [mscorlib]System.Action`1<int32 modopt(I1)>) .removeon void I1::remove_M01(class [mscorlib]System.Action`1<int32 modopt(I1)>) } } .class interface public auto ansi abstract I2 { .method public hidebysig specialname abstract virtual static void add_M02 ( class [mscorlib]System.Action modopt(I1) 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void modopt(I2) remove_M02 ( class [mscorlib]System.Action 'value' ) cil managed { } .event class [mscorlib]System.Action M02 { .addon void I2::add_M02(class [mscorlib]System.Action modopt(I1)) .removeon void modopt(I2) I2::remove_M02(class [mscorlib]System.Action) } } "; var source1 = @" class C1 : I1 { public static event System.Action<int> M01 { add => throw null; remove{} } } class C2 : I1 { static event System.Action<int> I1.M01 { add => throw null; remove{} } } #pragma warning disable CS0067 // The event 'C3.M02' is never used class C3 : I2 { public static event System.Action M02; } class C4 : I2 { static event System.Action I2.M02 { add => throw null; remove{} } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); var c1M01Add = c1M01.AddMethod; var c1M01Remove = c1M01.RemoveMethod; Assert.Equal("event System.Action<System.Int32> C1.M01", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Equal(MethodKind.EventAdd, c1M01Add.MethodKind); Assert.Equal("void C1.M01.add", c1M01Add.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32> value", c1M01Add.Parameters.Single().ToTestDisplayString()); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c1M01Remove.MethodKind); Assert.Equal("void C1.M01.remove", c1M01Remove.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32> value", c1M01Remove.Parameters.Single().ToTestDisplayString()); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { c1M01Add = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Add.MethodKind); Assert.Equal("void C1.I1.add_M01(System.Action<System.Int32 modopt(I1)> value)", c1M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c1M01Add.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); c1M01Remove = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Remove.MethodKind); Assert.Equal("void C1.I1.remove_M01(System.Action<System.Int32 modopt(I1)> value)", c1M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c1M01Remove.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); // Forwarding methods aren't tied to an event Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01Add, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01Remove, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Add = c2M01.AddMethod; var c2M01Remove = c2M01.RemoveMethod; Assert.Equal("event System.Action<System.Int32 modopt(I1)> C2.I1.M01", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c2M01Add.MethodKind); Assert.Equal("void C2.I1.M01.add", c2M01Add.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32 modopt(I1)> value", c2M01Add.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.AddMethod, c2M01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Add, c2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c2M01Remove.MethodKind); Assert.Equal("void C2.I1.M01.remove", c2M01Remove.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32 modopt(I1)> value", c2M01Remove.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c2M01Remove.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Remove, c2.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(c2M01, c2.GetMembers().OfType<EventSymbol>().Single()); Assert.Equal(2, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m02 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c3M02 = c3.GetMembers().OfType<EventSymbol>().Single(); var c3M02Add = c3M02.AddMethod; var c3M02Remove = c3M02.RemoveMethod; Assert.Equal("event System.Action C3.M02", c3M02.ToTestDisplayString()); Assert.Empty(c3M02.ExplicitInterfaceImplementations); Assert.True(c3M02.IsStatic); Assert.False(c3M02.IsAbstract); Assert.False(c3M02.IsVirtual); Assert.Equal(MethodKind.EventAdd, c3M02Add.MethodKind); Assert.Equal("void C3.M02.add", c3M02Add.ToTestDisplayString()); Assert.Equal("System.Action value", c3M02Add.Parameters.Single().ToTestDisplayString()); Assert.Empty(c3M02Add.ExplicitInterfaceImplementations); Assert.True(c3M02Add.IsStatic); Assert.False(c3M02Add.IsAbstract); Assert.False(c3M02Add.IsVirtual); Assert.False(c3M02Add.IsMetadataVirtual()); Assert.False(c3M02Add.IsMetadataFinal); Assert.False(c3M02Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c3M02Remove.MethodKind); Assert.Equal("void C3.M02.remove", c3M02Remove.ToTestDisplayString()); Assert.Equal("System.Void", c3M02Remove.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Empty(c3M02Remove.ExplicitInterfaceImplementations); Assert.True(c3M02Remove.IsStatic); Assert.False(c3M02Remove.IsAbstract); Assert.False(c3M02Remove.IsVirtual); Assert.False(c3M02Remove.IsMetadataVirtual()); Assert.False(c3M02Remove.IsMetadataFinal); Assert.False(c3M02Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { c3M02Add = (MethodSymbol)c3.FindImplementationForInterfaceMember(m02.AddMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c3M02Add.MethodKind); Assert.Equal("void C3.I2.add_M02(System.Action modopt(I1) value)", c3M02Add.ToTestDisplayString()); Assert.Same(m02.AddMethod, c3M02Add.ExplicitInterfaceImplementations.Single()); Assert.True(c3M02Add.IsStatic); Assert.False(c3M02Add.IsAbstract); Assert.False(c3M02Add.IsVirtual); Assert.False(c3M02Add.IsMetadataVirtual()); Assert.False(c3M02Add.IsMetadataFinal); Assert.False(c3M02Add.IsMetadataNewSlot()); c3M02Remove = (MethodSymbol)c3.FindImplementationForInterfaceMember(m02.RemoveMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c3M02Remove.MethodKind); Assert.Equal("void modopt(I2) C3.I2.remove_M02(System.Action value)", c3M02Remove.ToTestDisplayString()); Assert.Same(m02.RemoveMethod, c3M02Remove.ExplicitInterfaceImplementations.Single()); Assert.True(c3M02Remove.IsStatic); Assert.False(c3M02Remove.IsAbstract); Assert.False(c3M02Remove.IsVirtual); Assert.False(c3M02Remove.IsMetadataVirtual()); Assert.False(c3M02Remove.IsMetadataFinal); Assert.False(c3M02Remove.IsMetadataNewSlot()); // Forwarding methods aren't tied to an event Assert.Null(c3.FindImplementationForInterfaceMember(m02)); } else { Assert.Same(c3M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c3M02Add, c3.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.Same(c3M02Remove, c3.FindImplementationForInterfaceMember(m02.RemoveMethod)); } var c4 = module.GlobalNamespace.GetTypeMember("C4"); var c4M02 = (EventSymbol)c4.FindImplementationForInterfaceMember(m02); var c4M02Add = c4M02.AddMethod; var c4M02Remove = c4M02.RemoveMethod; Assert.Equal("event System.Action C4.I2.M02", c4M02.ToTestDisplayString()); // Signatures of accessors are lacking custom modifiers due to https://github.com/dotnet/roslyn/issues/53390. Assert.True(c4M02.IsStatic); Assert.False(c4M02.IsAbstract); Assert.False(c4M02.IsVirtual); Assert.Same(m02, c4M02.ExplicitInterfaceImplementations.Single()); Assert.True(c4M02Add.IsStatic); Assert.False(c4M02Add.IsAbstract); Assert.False(c4M02Add.IsVirtual); Assert.False(c4M02Add.IsMetadataVirtual()); Assert.False(c4M02Add.IsMetadataFinal); Assert.False(c4M02Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c4M02Add.MethodKind); Assert.Equal("void C4.I2.M02.add", c4M02Add.ToTestDisplayString()); Assert.Equal("System.Action value", c4M02Add.Parameters.Single().ToTestDisplayString()); Assert.Equal("System.Void", c4M02Add.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Same(m02.AddMethod, c4M02Add.ExplicitInterfaceImplementations.Single()); Assert.Same(c4M02Add, c4.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.True(c4M02Remove.IsStatic); Assert.False(c4M02Remove.IsAbstract); Assert.False(c4M02Remove.IsVirtual); Assert.False(c4M02Remove.IsMetadataVirtual()); Assert.False(c4M02Remove.IsMetadataFinal); Assert.False(c4M02Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c4M02Remove.MethodKind); Assert.Equal("void C4.I2.M02.remove", c4M02Remove.ToTestDisplayString()); Assert.Equal("System.Action value", c4M02Remove.Parameters.Single().ToTestDisplayString()); Assert.Equal("System.Void", c4M02Remove.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Same(m02.RemoveMethod, c4M02Remove.ExplicitInterfaceImplementations.Single()); Assert.Same(c4M02Remove, c4.FindImplementationForInterfaceMember(m02.RemoveMethod)); Assert.Same(c4M02, c4.GetMembers().OfType<EventSymbol>().Single()); Assert.Equal(2, c4.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); } verifier.VerifyIL("C1.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C1.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.remove"" IL_0006: ret } "); verifier.VerifyIL("C3.I2.add_M02", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C3.M02.add"" IL_0006: ret } "); verifier.VerifyIL("C3.I2.remove_M02", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C3.M02.remove"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticEvent_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static event System.Action M01; abstract static event System.Action M02; } public class C1 { public static event System.Action M01 { add => throw null; remove{} } } public class C2 : C1, I1 { static event System.Action I1.M02 { add => throw null; remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<EventSymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<EventSymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<EventSymbol>("M01"); Assert.Equal("event System.Action C1.M01", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); var c1M01Add = c1M01.AddMethod; Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); var c1M01Remove = c1M01.RemoveMethod; Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01Add = c3.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal("void C2.I1.add_M01(System.Action value)", c2M01Add.ToTestDisplayString()); var c2M01Remove = c3.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal("void C2.I1.remove_M01(System.Action value)", c2M01Remove.ToTestDisplayString()); // Forwarding methods for accessors aren't tied to an event Assert.Null(c3.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<EventSymbol>().Single(); var c2M02 = c3.BaseType().GetMember<EventSymbol>("I1.M02"); Assert.Equal("event System.Action C2.I1.M02", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c2M02.AddMethod, c3.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.Same(c2M02.RemoveMethod, c3.FindImplementationForInterfaceMember(m02.RemoveMethod)); } } [Fact] public void ImplementAbstractStaticEvent_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static event System.Action M01; } public class C1 : I1 { public static event System.Action M01 { add{} remove => throw null; } } public class C2 : C1 { new public static event System.Action M01 { add{} remove => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C3.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.remove"" IL_0006: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<EventSymbol>("M01"); var c2M01Add = c2M01.AddMethod; var c2M01Remove = c2M01.RemoveMethod; Assert.Equal("event System.Action C2.M01", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.Empty(c2M01Add.ExplicitInterfaceImplementations); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); Assert.Empty(c2M01Remove.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (EventSymbol)c3.FindImplementationForInterfaceMember(m01); // Forwarding methods for accessors aren't tied to an event Assert.Null(c3M01); var c3M01Add = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal("void C3.I1.add_M01(System.Action value)", c3M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c3M01Add.ExplicitInterfaceImplementations.Single()); var c3M01Remove = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal("void C3.I1.remove_M01(System.Action value)", c3M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c3M01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c2M01Add, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c2M01Remove, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_19(bool genericFirst) { // An "ambiguity" in implicit/explicit implementation declared in generic base class. var generic = @" public static event System.Action<T> M01 { add{} remove{} } "; var nonGeneric = @" static event System.Action<int> I1.M01 { add{} remove{} } "; var source1 = @" public interface I1 { abstract static event System.Action<int> M01; } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<EventSymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action<System.Int32> C1<T>.I1.M01", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_20(bool genericFirst) { // Same as ImplementAbstractStaticEvent_19 only interface is generic too. var generic = @" static event System.Action<T> I1<T>.M01 { add{} remove{} } "; var nonGeneric = @" public static event System.Action<int> M01 { add{} remove{} } "; var source1 = @" public interface I1<T> { abstract static event System.Action<T> M01; } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<EventSymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action<T> C1<T>.I1<T>.M01", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } private static string ConversionOperatorName(string op) => op switch { "implicit" => WellKnownMemberNames.ImplicitConversionName, "explicit" => WellKnownMemberNames.ExplicitConversionName, _ => throw TestExceptionUtilities.UnexpectedValue(op) }; [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = ConversionOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public " + op + @" operator int(C2 x) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static " + op + @" operator int(C3 x) => throw null; } " + typeKeyword + @" C4 : I1<C4> { " + op + @" I1<C4>.operator int(C4 x) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static " + op + @" operator long(C5 x) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static " + op + @" I1<C6>.operator long(C6 x) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static int " + opName + @"(C7 x) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static int I1<C8>." + opName + @"(C8 x) => throw null; } public interface I2<T> where T : I2<T> { abstract static int " + opName + @"(T x); } " + typeKeyword + @" C9 : I2<C9> { public static " + op + @" operator int(C9 x) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static " + op + @" I2<C10>.operator int(C10 x) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.explicit operator int(C1)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>." + op + " operator int(C1)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.explicit operator int(C2)'. 'C2.explicit operator int(C2)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>." + op + " operator int(C2)", "C2." + op + " operator int(C2)").WithLocation(12, 10), // (14,30): error CS0558: User-defined operator 'C2.explicit operator int(C2)' must be declared static and public // public explicit operator int(C2 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "int").WithArguments("C2." + op + " operator int(C2)").WithLocation(14, 30), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.explicit operator int(C3)'. 'C3.explicit operator int(C3)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>." + op + " operator int(C3)", "C3." + op + " operator int(C3)").WithLocation(18, 10), // (20,30): error CS0558: User-defined operator 'C3.explicit operator int(C3)' must be declared static and public // static explicit operator int(C3 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "int").WithArguments("C3." + op + " operator int(C3)").WithLocation(20, 30), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.explicit operator int(C4)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>." + op + " operator int(C4)").WithLocation(24, 10), // (26,30): error CS8930: Explicit implementation of a user-defined operator 'C4.explicit operator int(C4)' must be declared static // explicit I1<C4>.operator int(C4 x) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, "int").WithArguments("C4." + op + " operator int(C4)").WithLocation(26, 30), // (26,30): error CS0539: 'C4.explicit operator int(C4)' in explicit interface declaration is not found among members of the interface that can be implemented // explicit I1<C4>.operator int(C4 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C4." + op + " operator int(C4)").WithLocation(26, 30), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.explicit operator int(C5)'. 'C5.explicit operator long(C5)' cannot implement 'I1<C5>.explicit operator int(C5)' because it does not have the matching return type of 'int'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>." + op + " operator int(C5)", "C5." + op + " operator long(C5)", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.explicit operator int(C6)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>." + op + " operator int(C6)").WithLocation(36, 10), // (38,37): error CS0539: 'C6.explicit operator long(C6)' in explicit interface declaration is not found among members of the interface that can be implemented // static explicit I1<C6>.operator long(C6 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "long").WithArguments("C6." + op + " operator long(C6)").WithLocation(38, 37), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.explicit operator int(C7)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>." + op + " operator int(C7)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.explicit operator int(C8)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>." + op + " operator int(C8)").WithLocation(48, 10), // (50,23): error CS0539: 'C8.op_Explicit(C8)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C8>.op_Explicit(C8 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8)").WithLocation(50, 23), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_Explicit(C9)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_Explicit(C10)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10)").WithLocation(65, 11), // (67,38): error CS0539: 'C10.explicit operator int(C10)' in explicit interface declaration is not found among members of the interface that can be implemented // static explicit I2<C10>.operator int(C10 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C10." + op + " operator int(C10)").WithLocation(67, 38) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_03([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } interface I2<T> : I1<T> where T : I1<T> {} interface I3<T> : I1<T> where T : I1<T> { " + op + @" operator int(T x) => default; } interface I4<T> : I1<T> where T : I1<T> { static " + op + @" operator int(T x) => default; } interface I5<T> : I1<T> where T : I1<T> { " + op + @" I1<T>.operator int(T x) => default; } interface I6<T> : I1<T> where T : I1<T> { static " + op + @" I1<T>.operator int(T x) => default; } interface I7<T> : I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public interface I11<T> where T : I11<T> { abstract static " + op + @" operator int(T x); } interface I8<T> : I11<T> where T : I8<T> { " + op + @" operator int(T x) => default; } interface I9<T> : I11<T> where T : I9<T> { static " + op + @" operator int(T x) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static " + op + @" operator int(T x); } interface I12<T> : I11<T> where T : I12<T> { static " + op + @" I11<T>.operator int(T x) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static " + op + @" I11<T>.operator int(T x); } interface I14<T> : I1<T> where T : I1<T> { abstract static " + op + @" I1<T>.operator int(T x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,23): error CS0556: User-defined conversion must convert to or from the enclosing type // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(12, 23), // (12,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(12, 23), // (17,30): error CS0556: User-defined conversion must convert to or from the enclosing type // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(17, 30), // (17,30): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(17, 30), // (22,29): error CS8930: Explicit implementation of a user-defined operator 'I5<T>.implicit operator int(T)' must be declared static // implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, "int").WithArguments("I5<T>." + op + " operator int(T)").WithLocation(22, 29), // (22,29): error CS0539: 'I5<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I5<T>." + op + " operator int(T)").WithLocation(22, 29), // (27,36): error CS0539: 'I6<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I6<T>." + op + " operator int(T)").WithLocation(27, 36), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "int").WithLocation(32, 39), // (42,23): error CS0556: User-defined conversion must convert to or from the enclosing type // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(42, 23), // (42,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(42, 23), // (47,30): error CS0556: User-defined conversion must convert to or from the enclosing type // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(47, 30), // (47,30): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(47, 30), // (57,37): error CS0539: 'I12<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I11<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I12<T>." + op + " operator int(T)").WithLocation(57, 37), // (62,46): error CS0106: The modifier 'abstract' is not valid for this item // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(62, 46), // (62,46): error CS0501: 'I13<T>.implicit operator int(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "int").WithArguments("I13<T>." + op + " operator int(T)").WithLocation(62, 46), // (62,46): error CS0539: 'I13<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I13<T>." + op + " operator int(T)").WithLocation(62, 46), // (67,45): error CS0106: The modifier 'abstract' is not valid for this item // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(67, 45), // (67,45): error CS0501: 'I14<T>.implicit operator int(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "int").WithArguments("I14<T>." + op + " operator int(T)").WithLocation(67, 45), // (67,45): error CS0539: 'I14<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I14<T>." + op + " operator int(T)").WithLocation(67, 45) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_04([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I2<T> where T : I2<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1 : I2<Test1> { static " + op + @" I2<Test1>.operator int(Test1 x) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static " + op + @" operator int(Test2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,21): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static explicit I2<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I2<Test1>.").WithArguments("static abstract members in interfaces").WithLocation(4, 21) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,21): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static explicit I2<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I2<Test1>.").WithArguments("static abstract members in interfaces").WithLocation(4, 21), // (14,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(14, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_05([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static " + op + @" operator int(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.explicit operator int(Test1)' cannot implement interface member 'I1<Test1>.explicit operator int(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1." + op + " operator int(Test1)", "I1<Test1>." + op + " operator int(Test1)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.explicit operator int(Test1)' cannot implement interface member 'I1<Test1>.explicit operator int(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1." + op + " operator int(Test1)", "I1<Test1>." + op + " operator int(Test1)", "Test1").WithLocation(2, 12), // (9,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(9, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_06([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1 : I1<Test1> { static " + op + @" I1<Test1>.operator int(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,40): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static explicit I1<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 40) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,40): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static explicit I1<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 40), // (9,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(9, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_07([CombinatorialValues("implicit", "explicit")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); abstract static " + op + @" operator long(T x); } " + typeKeyword + @" C : I1<C> { public static " + op + @" operator long(C x) => default; public static " + op + @" operator int(C x) => default; } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = i1.GetMembers().OfType<MethodSymbol>().First(); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("System.Int32 C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } var m02 = i1.GetMembers().OfType<MethodSymbol>().ElementAt(1); var cM02 = (MethodSymbol)c.FindImplementationForInterfaceMember(m02); Assert.True(cM02.IsStatic); Assert.False(cM02.IsAbstract); Assert.False(cM02.IsVirtual); Assert.False(cM02.IsMetadataVirtual()); Assert.False(cM02.IsMetadataFinal); Assert.False(cM02.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, cM02.MethodKind); Assert.False(cM02.HasRuntimeSpecialName); Assert.True(cM02.HasSpecialName); Assert.Equal("System.Int64 C." + opName + "(C x)", cM02.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m02, cM02.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM02.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_08([CombinatorialValues("implicit", "explicit")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" interface I1<T> where T : I1<T> { abstract static " + op + @" operator C(T x); abstract static " + op + @" operator int(T x); } " + typeKeyword + @" C : I1<C> { static " + op + @" I1<C>.operator int(C x) => int.MaxValue; static " + op + @" I1<C>.operator C(C x) => default; } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.Equal("default", node.ToString()); Assert.Equal("C", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<ConversionOperatorDeclarationSyntax>()); Assert.Equal("C C.I1<C>." + opName + "(C x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<MethodSymbol>().First(); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("C C.I1<C>." + opName + "(C x)", cM01.ToTestDisplayString()); Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); var m02 = c.Interfaces().Single().GetMembers().OfType<MethodSymbol>().ElementAt(1); var cM02 = (MethodSymbol)c.FindImplementationForInterfaceMember(m02); Assert.True(cM02.IsStatic); Assert.False(cM02.IsAbstract); Assert.False(cM02.IsVirtual); Assert.False(cM02.IsMetadataVirtual()); Assert.False(cM02.IsMetadataFinal); Assert.False(cM02.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM02.MethodKind); Assert.False(cM02.HasRuntimeSpecialName); Assert.False(cM02.HasSpecialName); Assert.Equal("System.Int32 C.I1<C>." + opName + "(C x)", cM02.ToTestDisplayString()); Assert.Equal(m02, cM02.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_09([CombinatorialValues("implicit", "explicit")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = ConversionOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.I1<C2>." + opName + "(C2 x)", cM01.ToTestDisplayString()); Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_10([CombinatorialValues("implicit", "explicit")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 " + opName + @" ( !T x ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements class I1`1<class C1> { .method private hidebysig static int32 'I1<C1>." + opName + @"' ( class C1 x ) cil managed { .override method int32 class I1`1<class C1>::" + opName + @"(!0) IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig static specialname int32 " + opName + @" ( class C1 x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2053 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: nop IL_0007: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements class I1`1<class C1> { .method public hidebysig static specialname int32 " + opName + @" ( class C1 x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1<C1> { } public class C5 : C2, I1<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Equal(MethodKind.Conversion, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2." + opName + "(C1 x)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.Conversion, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_11([CombinatorialValues("implicit", "explicit")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname virtual static int32 " + opName + @" ( !T x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } } "; var source1 = @" public class C1 : I1<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1<C1> { static " + op + @" I1<C1>.operator int(C1 x) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,37): error CS0539: 'C1.implicit operator int(C1)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I1<C1>.operator int(C1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C1." + op + " operator int(C1)").WithLocation(4, 37) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("System.Int32 I1<C1>." + opName + "(C1 x)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_12([CombinatorialValues("implicit", "explicit")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 " + opName + @" ( !T x ) cil managed { } } .class interface public auto ansi abstract I2`1<(class I1`1<!T>) T> implements class I1`1<!T> { .method private hidebysig static int32 'I1<!T>." + opName + @"' ( !T x ) cil managed { .override method int32 class I1`1<!T>::" + opName + @"(!0) IL_0000: ldc.i4.0 IL_0001: ret } } "; var source1 = @" public class C1 : I2<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1<C1>.explicit operator int(C1)' // public class C1 : I2<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C1>").WithArguments("C1", "I1<C1>." + op + " operator int(C1)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_13([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static " + op + @" operator C1<T>(T x); } public partial class C1<T> { public static " + op + @" operator C1<T>(T x) => default; } public class C2 : C1<C2>, I1<C2> { } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var i1 = c2.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.False(c2M01.HasSpecialName); Assert.Equal("C1<C2> C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.False(c1M01.HasRuntimeSpecialName); Assert.True(c1M01.HasSpecialName); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Conversion, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.True(c2M01.HasSpecialName); Assert.Equal("C1<C2> C1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1<C2>." + opName + "(C2)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""C1<C2> C1<C2>." + opName + @"(C2)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_14([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static " + op + @" operator int(C1 x) => default; } class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("System.Int32 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("System.Int32 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.Equal("System.Int32 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("System.Int32 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int C1." + opName + @"(C1)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_15([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static " + op + @" operator C1<T>(T x); abstract static " + op + @" operator T(int x); } public partial class C1<T> { public static " + op + @" operator C1<T>(T x) => default; } public class C2 : C1<C2>, I1<C2> { static " + op + @" I1<C2>.operator C2(int x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = ConversionOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().First(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C1<C2> C1<C2>." + opName + "(C2 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<C2> C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Equal(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().ElementAt(1); var c2M02 = c3.BaseType().GetMembers("I1<C2>." + opName).OfType<MethodSymbol>().First(); Assert.Equal("C2 C2.I1<C2>." + opName + "(System.Int32 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_18([CombinatorialValues("implicit", "explicit")] string op, bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static " + op + @" operator U(C1<T, U> x) => default; "; var nonGeneric = @" public static " + op + @" operator int(C1<T, U> x) => default; "; var source1 = @" public interface I1<T, U> where T : I1<T, U> { abstract static " + op + @" operator U(T x); } public class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>." + opName + "(C1<T, U> x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>." + opName + "(C1<T, U> x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_20([CombinatorialValues("implicit", "explicit")] string op, bool genericFirst) { // Same as ImplementAbstractStaticConversionOperator_18 only implementation is explicit in source. var generic = @" static " + op + @" I1<C1<T, U>, U>.operator U(C1<T, U> x) => default; "; var nonGeneric = @" public static " + op + @" operator int(C1<T, U> x) => default; "; var source1 = @" public interface I1<T, U> where T : I1<T, U> { abstract static " + op + @" operator U(T x); } public class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>.I1<C1<T, U>, U>." + opName + "(C1<T, U> x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class C1 : I1<C1> { static " + op + @" I1<C1>.operator int(C1 x) => default; } class C2 : I1<C2> { private static " + op + @" I1<C2>.operator int(C2 x) => default; } class C3 : I1<C3> { protected static " + op + @" I1<C3>.operator int(C3 x) => default; } class C4 : I1<C4> { internal static " + op + @" I1<C4>.operator int(C4 x) => default; } class C5 : I1<C5> { protected internal static " + op + @" I1<C5>.operator int(C5 x) => default; } class C6 : I1<C6> { private protected static " + op + @" I1<C6>.operator int(C6 x) => default; } class C7 : I1<C7> { public static " + op + @" I1<C7>.operator int(C7 x) => default; } class C9 : I1<C9> { async static " + op + @" I1<C9>.operator int(C9 x) => default; } class C10 : I1<C10> { unsafe static " + op + @" I1<C10>.operator int(C10 x) => default; } class C11 : I1<C11> { static readonly " + op + @" I1<C11>.operator int(C11 x) => default; } class C12 : I1<C12> { extern static " + op + @" I1<C12>.operator int(C12 x); } class C13 : I1<C13> { abstract static " + op + @" I1<C13>.operator int(C13 x) => default; } class C14 : I1<C14> { virtual static " + op + @" I1<C14>.operator int(C14 x) => default; } class C15 : I1<C15> { sealed static " + op + @" I1<C15>.operator int(C15 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.WRN_ExternMethodNoImplementation).Verify( // (16,45): error CS0106: The modifier 'private' is not valid for this item // private static explicit I1<C2>.operator int(C2 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("private").WithLocation(16, 45), // (22,47): error CS0106: The modifier 'protected' is not valid for this item // protected static explicit I1<C3>.operator int(C3 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("protected").WithLocation(22, 47), // (28,46): error CS0106: The modifier 'internal' is not valid for this item // internal static explicit I1<C4>.operator int(C4 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("internal").WithLocation(28, 46), // (34,56): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static explicit I1<C5>.operator int(C5 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("protected internal").WithLocation(34, 56), // (40,55): error CS0106: The modifier 'private protected' is not valid for this item // private protected static explicit I1<C6>.operator int(C6 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("private protected").WithLocation(40, 55), // (46,44): error CS0106: The modifier 'public' is not valid for this item // public static explicit I1<C7>.operator int(C7 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("public").WithLocation(46, 44), // (52,43): error CS0106: The modifier 'async' is not valid for this item // async static explicit I1<C9>.operator int(C9 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("async").WithLocation(52, 43), // (64,47): error CS0106: The modifier 'readonly' is not valid for this item // static readonly explicit I1<C11>.operator int(C11 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("readonly").WithLocation(64, 47), // (76,47): error CS0106: The modifier 'abstract' is not valid for this item // abstract static explicit I1<C13>.operator int(C13 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(76, 47), // (82,46): error CS0106: The modifier 'virtual' is not valid for this item // virtual static explicit I1<C14>.operator int(C14 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("virtual").WithLocation(82, 46), // (88,45): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit I1<C15>.operator int(C15 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(88, 45) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : struct, I1<T> { abstract static " + op + @" operator int(T x); } class C1 { static " + op + @" I1<int>.operator int(int x) => default; } class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,21): error CS0540: 'C1.I1<int>.implicit operator int(int)': containing type does not implement interface 'I1<int>' // static implicit I1<int>.operator int(int x) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<int>").WithArguments("C1.I1<int>." + op + " operator int(int)", "I1<int>").WithLocation(9, 21), // (9,21): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion from 'int' to 'I1<int>'. // static implicit I1<int>.operator int(int x) => default; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "I1<int>").WithArguments("I1<T>", "I1<int>", "T", "int").WithLocation(9, 21), // (12,7): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // class C2 : I1<C2> Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 7), // (14,21): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static implicit I1<C2>.operator int(C2 x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 21) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { string cast = (op == "explicit" ? "(int)" : ""); var source1 = @" interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); static int M02(I1<T> x) { return " + cast + @"x; } int M03(I1<T> y) { return " + cast + @"y; } } class Test<T> where T : I1<T> { static int MT1(I1<T> a) { return " + cast + @"a; } static void MT2() { _ = (System.Linq.Expressions.Expression<System.Func<T, int>>)((T b) => " + cast + @"b); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (8,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)x; Diagnostic(error, cast + "x").WithArguments("I1<T>", "int").WithLocation(8, 16), // (13,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)y; Diagnostic(error, cast + "y").WithArguments("I1<T>", "int").WithLocation(13, 16), // (21,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)a; Diagnostic(error, cast + "a").WithArguments("I1<T>", "int").WithLocation(21, 16), // (26,80): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Func<T, int>>)((T b) => (int)b); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, cast + "b").WithLocation(26, 80) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1 { abstract static implicit operator bool(I1 x); static void M02((int, C<I1>) x) { _ = x " + op + @" x; } void M03((int, C<I1>) y) { _ = y " + op + @" y; } } class Test { static void MT1((int, C<I1>) a) { _ = a " + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b " + op + @" b).ToString()); } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0552: 'I1.implicit operator bool(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator bool(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "bool").WithArguments("I1.implicit operator bool(I1)").WithLocation(4, 39), // (9,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = x == x; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x " + op + " x").WithArguments("I1", "bool").WithLocation(9, 13), // (14,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = y == y; Diagnostic(ErrorCode.ERR_NoImplicitConv, "y " + op + " y").WithArguments("I1", "bool").WithLocation(14, 13), // (22,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = a == a; Diagnostic(ErrorCode.ERR_NoImplicitConv, "a " + op + " a").WithArguments("I1", "bool").WithLocation(22, 13), // (27,98): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(27, 98) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_03([CombinatorialValues("implicit", "explicit")] string op) { string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class Test { static int M02<T, U>(T x) where T : U where U : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int? M03<T, U>(T y) where T : U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"y; } static int? M04<T, U>(T? y) where T : struct, U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"y; } static int? M05<T, U>() where T : struct, U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"(T?)new T(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 23 (0x17) .maxstack 1 .locals init (int? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: newobj ""int?..ctor(int)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (T? V_0, int? V_1, int? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""int?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""int I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""int?..ctor(int)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 27 (0x1b) .maxstack 1 .locals init (int? V_0) IL_0000: nop IL_0001: call ""T System.Activator.CreateInstance<T>()"" IL_0006: constrained. ""T"" IL_000c: call ""int I1<T>." + metadataName + @"(T)"" IL_0011: newobj ""int?..ctor(int)"" IL_0016: stloc.0 IL_0017: br.s IL_0019 IL_0019: ldloc.0 IL_001a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""int I1<T>." + metadataName + @"(T)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""int I1<T>." + metadataName + @"(T)"" IL_000c: newobj ""int?..ctor(int)"" IL_0011: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (T? V_0, int? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""int?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""int I1<T>." + metadataName + @"(T)"" IL_0027: newobj ""int?..ctor(int)"" IL_002c: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 22 (0x16) .maxstack 1 IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: constrained. ""T"" IL_000b: call ""int I1<T>." + metadataName + @"(T)"" IL_0010: newobj ""int?..ctor(int)"" IL_0015: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().First(); Assert.Equal("return " + (needCast ? "(int)" : "") + @"x;", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return " + (needCast ? "(int)" : "") + @"x;') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 I1<T>." + metadataName + @"(T x)) (OperationKind.Conversion, Type: System.Int32" + (needCast ? "" : ", IsImplicit") + @") (Syntax: '" + (needCast ? "(int)" : "") + @"x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 I1<T>." + metadataName + @"(T x)) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool (T x); } class Test { static void M02<T, U>((int, C<T>) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_Implicit(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.0 IL_0032: pop IL_0033: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_Implicit(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.1 IL_0032: pop IL_0033: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_Implicit(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.0 IL_0031: pop IL_0032: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_Implicit(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.1 IL_0031: pop IL_0032: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_04([CombinatorialValues("implicit", "explicit")] string op) { bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = @" class Test { static int M02<T>(T x) where T : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,16): error CS8919: Target runtime doesn't support static abstract members in interfaces. // return (int)x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, (needCast ? "(int)" : "") + "x").WithLocation(6, 16) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(12, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool(T x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (21,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static implicit operator bool(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "bool").WithLocation(21, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_06([CombinatorialValues("implicit", "explicit")] string op) { bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = @" class Test { static int M02<T>(T x) where T : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,16): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // return x; Diagnostic(ErrorCode.ERR_FeatureInPreview, (needCast ? "(int)" : "") + "x").WithArguments("static abstract members in interfaces").WithLocation(6, 16) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(12, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool(T x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (21,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator bool(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "bool").WithArguments("abstract", "9.0", "preview").WithLocation(21, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_07([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_03 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } class Test { static T M02<T, U>(int x) where T : U where U : I1<T> { return " + (needCast ? "(T)" : "") + @"x; } static T? M03<T, U>(int y) where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"y; } static T? M04<T, U>(int? y) where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"y; } static T? M05<T, U>() where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"(T?)0; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(int)", @" { // Code size 23 (0x17) .maxstack 1 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: newobj ""T?..ctor(T)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (int? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool int?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly int int?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(int)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 23 (0x17) .maxstack 1 .locals init (T? V_0) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: newobj ""T?..ctor(T)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: newobj ""T?..ctor(T)"" IL_0011: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (int? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool int?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly int int?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""T I1<T>." + metadataName + @"(int)"" IL_0027: newobj ""T?..ctor(T)"" IL_002c: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: newobj ""T?..ctor(T)"" IL_0011: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().First(); Assert.Equal("return " + (needCast ? "(T)" : "") + @"x;", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return " + (needCast ? "(T)" : "") + @"x;') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: T I1<T>." + metadataName + @"(System.Int32 x)) (OperationKind.Conversion, Type: T" + (needCast ? "" : ", IsImplicit") + @") (Syntax: '" + (needCast ? "(T)" : "") + @"x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: T I1<T>." + metadataName + @"(System.Int32 x)) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_08([CombinatorialValues("implicit", "explicit")] string op) { // Don't look in interfaces of the effective base string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class C1<T> : I1<C1<T>> { static " + op + @" I1<C1<T>>.operator int(C1<T> x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int M03<T>(C1<T> y) where T : I1<C1<T>> { return " + (needCast ? "(int)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (16,16): error CS0030: Cannot convert type 'T' to 'int' // return (int)x; Diagnostic(error, (needCast ? "(int)" : "") + "x").WithArguments("T", "int").WithLocation(16, 16), // (21,16): error CS0030: Cannot convert type 'C1<T>' to 'int' // return (int)y; Diagnostic(error, (needCast ? "(int)" : "") + "y").WithArguments("C1<T>", "int").WithLocation(21, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_09([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_08 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } class C1<T> : I1<C1<T>> { static " + op + @" I1<C1<T>>.operator C1<T>(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1<T> { return " + (needCast ? "(T)" : "") + @"x; } static C1<T> M03<T>(int y) where T : I1<C1<T>> { return " + (needCast ? "(C1<T>)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (16,16): error CS0030: Cannot convert type 'int' to 'T' // return (T)x; Diagnostic(error, (needCast ? "(T)" : "") + "x").WithArguments("int", "T").WithLocation(16, 16), // (21,16): error CS0030: Cannot convert type 'int' to 'C1<T>' // return (C1<T>)y; Diagnostic(error, (needCast ? "(C1<T>)" : "") + "y").WithArguments("int", "C1<T>").WithLocation(21, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_10([CombinatorialValues("implicit", "explicit")] string op) { // Look in derived interfaces string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public interface I2<T> : I1<T> where T : I1<T> {} class Test { static int M02<T, U>(T x) where T : U where U : I2<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_11([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_10 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } public interface I2<T> : I1<T> where T : I1<T> {} class Test { static T M02<T, U>(int x) where T : U where U : I2<T> { return " + (needCast ? "(T)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_12([CombinatorialValues("implicit", "explicit")] string op) { // Ignore duplicate candidates string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T, U> where T : I1<T, U> where U : I1<T, U> { abstract static " + op + @" operator U(T x); } class Test { static U M02<T, U>(T x) where T : I1<T, U> where U : I1<T, U> { return " + (needCast ? "(U)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (U V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""U I1<T, U>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_13([CombinatorialValues("implicit", "explicit")] string op) { // Look in effective base string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public class C1<T> { public static " + op + @" operator int(C1<T> x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: call ""int C1<T>." + metadataName + @"(C1<T>)"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Fact] public void ConsumeAbstractConversionOperator_14() { // Same as ConsumeAbstractConversionOperator_13 only direction of conversion is flipped var source1 = @" public class C1<T> { public static explicit operator C1<T>(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1<T> { return (T)x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""C1<T> C1<T>.op_Explicit(int)"" IL_0007: unbox.any ""T"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_15([CombinatorialValues("implicit", "explicit")] string op) { // If there is a non-trivial class constraint, interfaces are not looked at. string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C1 : I1<C1> { public static " + op + @" operator int(C1 x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1, I1<C1> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: call ""int C1." + metadataName + @"(C1)"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Fact] public void ConsumeAbstractConversionOperator_16() { // Same as ConsumeAbstractConversionOperator_15 only direction of conversion is flipped var source1 = @" public interface I1<T> where T : I1<T> { abstract static explicit operator T(int x); } public class C1 : I1<C1> { public static explicit operator C1(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1, I1<C1> { return (T)x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""C1 C1.op_Explicit(int)"" IL_0007: unbox.any ""T"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_17([CombinatorialValues("implicit", "explicit")] string op) { // If there is a non-trivial class constraint, interfaces are not looked at. bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C1 { } class Test { static int M02<T, U>(T x) where T : U where U : C1, I1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int M03<T, U>(T y) where T : U where U : I1<T> { return " + (needCast ? "(int)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (15,16): error CS0030: Cannot convert type 'T' to 'int' // return (int)x; Diagnostic((op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv), (needCast ? "(int)" : "") + "x").WithArguments("T", "int").WithLocation(15, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_18([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_17 only direction of conversion is flipped bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } public class C1 { } class Test { static T M02<T, U>(int x) where T : U where U : C1, I1<T> { return " + (needCast ? "(T)" : "") + @"x; } static T M03<T, U>(int y) where T : U where U : I1<T> { return " + (needCast ? "(T)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (15,16): error CS0030: Cannot convert type 'int' to 'T' // return (T)x; Diagnostic((op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv), (needCast ? "(T)" : "") + "x").WithArguments("int", "T").WithLocation(15, 16) ); } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_01() { var source1 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } public class Derived : Base<int>, Interface<int, int> { } class YetAnother : Interface<int, int> { public static void Method(int i) { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var b = module.GlobalNamespace.GetTypeMember("Base"); var bI = b.Interfaces().Single(); var biMethods = bI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", biMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", biMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", biMethods[2].OriginalDefinition.ToTestDisplayString()); var bM1 = b.FindImplementationForInterfaceMember(biMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", bM1.ToTestDisplayString()); var bM2 = b.FindImplementationForInterfaceMember(biMethods[1]); Assert.Equal("void Base<T>.Method(T i)", bM2.ToTestDisplayString()); Assert.Same(bM2, b.FindImplementationForInterfaceMember(biMethods[2])); var bM1Impl = ((MethodSymbol)bM1).ExplicitInterfaceImplementations; var bM2Impl = ((MethodSymbol)bM2).ExplicitInterfaceImplementations; if (module is PEModuleSymbol) { Assert.Equal(biMethods[0], bM1Impl.Single()); Assert.Equal(2, bM2Impl.Length); Assert.Equal(biMethods[1], bM2Impl[0]); Assert.Equal(biMethods[2], bM2Impl[1]); } else { Assert.Empty(bM1Impl); Assert.Empty(bM2Impl); } var d = module.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Same(bM1, dM1.OriginalDefinition); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Same(bM2, dM2.OriginalDefinition); Assert.Same(bM2, d.FindImplementationForInterfaceMember(diMethods[2]).OriginalDefinition); } } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_02() { var source0 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); var source1 = @" public class Derived : Base<int>, Interface<int, int> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation0.EmitToImageReference() }); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var d = module.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", dM1.OriginalDefinition.ToTestDisplayString()); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Equal("void Base<T>.Method(T i)", dM2.OriginalDefinition.ToTestDisplayString()); Assert.Same(dM2, d.FindImplementationForInterfaceMember(diMethods[2])); var dM1Impl = ((MethodSymbol)dM1).ExplicitInterfaceImplementations; var dM2Impl = ((MethodSymbol)dM2).ExplicitInterfaceImplementations; Assert.Equal(diMethods[0], dM1Impl.Single()); Assert.Equal(2, dM2Impl.Length); Assert.Equal(diMethods[1], dM2Impl[0]); Assert.Equal(diMethods[2], dM2Impl[1]); } } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_03() { var source0 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateEmptyCompilation("").ToMetadataReference() }); compilation0.VerifyDiagnostics(); var source1 = @" public class Derived : Base<int>, Interface<int, int> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation0.ToMetadataReference() }); var d = compilation1.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.IsType<RetargetingNamedTypeSymbol>(dB.OriginalDefinition); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", dM1.OriginalDefinition.ToTestDisplayString()); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Equal("void Base<T>.Method(T i)", dM2.OriginalDefinition.ToTestDisplayString()); Assert.Equal(dM2, d.FindImplementationForInterfaceMember(diMethods[2])); var dM1Impl = ((MethodSymbol)dM1).ExplicitInterfaceImplementations; var dM2Impl = ((MethodSymbol)dM2).ExplicitInterfaceImplementations; Assert.Empty(dM1Impl); Assert.Empty(dM2Impl); } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_04() { var source2 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } class Other : Interface<int, int> { static void Interface<int, int>.Method(int i) { } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (9,15): error CS0535: 'Other' does not implement interface member 'Interface<int, int>.Method(int)' // class Other : Interface<int, int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<int, int>").WithArguments("Other", "Interface<int, int>.Method(int)").WithLocation(9, 15), // (9,15): error CS0535: 'Other' does not implement interface member 'Interface<int, int>.Method(int)' // class Other : Interface<int, int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<int, int>").WithArguments("Other", "Interface<int, int>.Method(int)").WithLocation(9, 15), // (11,37): warning CS0473: Explicit interface implementation 'Other.Interface<int, int>.Method(int)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // static void Interface<int, int>.Method(int i) { } Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Other.Interface<int, int>.Method(int)").WithLocation(11, 37) ); } [Fact] public void UnmanagedCallersOnly_01() { var source2 = @" using System.Runtime.InteropServices; public interface I1 { [UnmanagedCallersOnly] abstract static void M1(); [UnmanagedCallersOnly] abstract static int operator +(I1 x); [UnmanagedCallersOnly] abstract static int operator +(I1 x, I1 y); } public interface I2<T> where T : I2<T> { [UnmanagedCallersOnly] abstract static implicit operator int(T i); [UnmanagedCallersOnly] abstract static explicit operator T(int i); } "; var compilation2 = CreateCompilation(new[] { source2, UnmanagedCallersOnlyAttributeDefinition }, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (6,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static void M1(); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(6, 6), // (7,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static int operator +(I1 x); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 6), // (8,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static int operator +(I1 x, I1 y); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(8, 6), // (13,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static implicit operator int(T i); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(13, 6), // (14,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static explicit operator T(int i); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(14, 6) ); } [Fact] [WorkItem(54113, "https://github.com/dotnet/roslyn/issues/54113")] public void UnmanagedCallersOnly_02() { var ilSource = @" .class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72 69 74 65 64 00 ) .field public class [mscorlib]System.Type[] CallConvs .field public string EntryPoint .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void M1 () cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static int32 op_UnaryPlus ( class I1 x ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static int32 op_Addition ( class I1 x, class I1 y ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } } .class interface public auto ansi abstract I2`1<(class I2`1<!T>) T> { .method public hidebysig specialname abstract virtual static int32 op_Implicit ( !T i ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static !T op_Explicit ( int32 i ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } } "; var source1 = @" class Test { static void M02<T>(T x, T y) where T : I1 { T.M1(); _ = +x; _ = x + y; } static int M03<T>(T x) where T : I2<T> { _ = (T)x; return x; } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); // Conversions aren't flagged due to https://github.com/dotnet/roslyn/issues/54113. compilation1.VerifyDiagnostics( // (6,11): error CS0570: 'I1.M1()' is not supported by the language // T.M1(); Diagnostic(ErrorCode.ERR_BindToBogus, "M1").WithArguments("I1.M1()").WithLocation(6, 11), // (7,13): error CS0570: 'I1.operator +(I1)' is not supported by the language // _ = +x; Diagnostic(ErrorCode.ERR_BindToBogus, "+x").WithArguments("I1.operator +(I1)").WithLocation(7, 13), // (8,13): error CS0570: 'I1.operator +(I1, I1)' is not supported by the language // _ = x + y; Diagnostic(ErrorCode.ERR_BindToBogus, "x + y").WithArguments("I1.operator +(I1, I1)").WithLocation(8, 13) ); } [Fact] public void UnmanagedCallersOnly_03() { var source2 = @" using System.Runtime.InteropServices; public interface I1<T> where T : I1<T> { abstract static void M1(); abstract static int operator +(T x); abstract static int operator +(T x, T y); abstract static implicit operator int(T i); abstract static explicit operator T(int i); } class C : I1<C> { [UnmanagedCallersOnly] public static void M1() {} [UnmanagedCallersOnly] public static int operator +(C x) => 0; [UnmanagedCallersOnly] public static int operator +(C x, C y) => 0; [UnmanagedCallersOnly] public static implicit operator int(C i) => 0; [UnmanagedCallersOnly] public static explicit operator C(int i) => null; } "; var compilation2 = CreateCompilation(new[] { source2, UnmanagedCallersOnlyAttributeDefinition }, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (15,47): error CS8932: 'UnmanagedCallersOnly' method 'C.M1()' cannot implement interface member 'I1<C>.M1()' in type 'C' // [UnmanagedCallersOnly] public static void M1() {} Diagnostic(ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod, "M1").WithArguments("C.M1()", "I1<C>.M1()", "C").WithLocation(15, 47), // (16,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static int operator +(C x) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(16, 6), // (17,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static int operator +(C x, C y) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(17, 6), // (18,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static implicit operator int(C i) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(18, 6), // (19,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static explicit operator C(int i) => null; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(19, 6) ); } [Fact] public void UnmanagedCallersOnly_04() { var source2 = @" using System.Runtime.InteropServices; public interface I1<T> where T : I1<T> { abstract static void M1(); abstract static int operator +(T x); abstract static int operator +(T x, T y); abstract static implicit operator int(T i); abstract static explicit operator T(int i); } class C : I1<C> { [UnmanagedCallersOnly] static void I1<C>.M1() {} [UnmanagedCallersOnly] static int I1<C>.operator +(C x) => 0; [UnmanagedCallersOnly] static int I1<C>.operator +(C x, C y) => 0; [UnmanagedCallersOnly] static implicit I1<C>.operator int(C i) => 0; [UnmanagedCallersOnly] static explicit I1<C>.operator C(int i) => null; } "; var compilation2 = CreateCompilation(new[] { source2, UnmanagedCallersOnlyAttributeDefinition }, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (15,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static void I1<C>.M1() {} Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(15, 6), // (16,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static int I1<C>.operator +(C x) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(16, 6), // (17,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static int I1<C>.operator +(C x, C y) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(17, 6), // (18,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static implicit I1<C>.operator int(C i) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(18, 6), // (19,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static explicit I1<C>.operator C(int i) => null; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(19, 6) ); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Tools/BuildValidator/xlf/BuildValidatorResources.pl.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="pl" original="../BuildValidatorResources.resx"> <body> <trans-unit id="Assemblies_to_be_excluded_substring_match"> <source>Assemblies to be excluded (substring match)</source> <target state="new">Assemblies to be excluded (substring match)</target> <note /> </trans-unit> <trans-unit id="Do_not_output_log_information_to_console"> <source>Do not output log information to console</source> <target state="new">Do not output log information to console</target> <note /> </trans-unit> <trans-unit id="Output_debug_info_when_rebuild_is_not_equal_to_the_original"> <source>Output debug info when rebuild is not equal to the original</source> <target state="new">Output debug info when rebuild is not equal to the original</target> <note /> </trans-unit> <trans-unit id="Output_verbose_log_information"> <source>Output verbose log information</source> <target state="new">Output verbose log information</target> <note /> </trans-unit> <trans-unit id="Path_to_assemblies_to_rebuild_can_be_specified_one_or_more_times"> <source>Path to assemblies to rebuild (can be specified one or more times)</source> <target state="new">Path to assemblies to rebuild (can be specified one or more times)</target> <note /> </trans-unit> <trans-unit id="Path_to_output_debug_info"> <source>Path to output debug info. Defaults to the user temp directory. Note that a unique debug path should be specified for every instance of the tool running with `--debug` enabled.</source> <target state="new">Path to output debug info. Defaults to the user temp directory. Note that a unique debug path should be specified for every instance of the tool running with `--debug` enabled.</target> <note /> </trans-unit> <trans-unit id="Path_to_referenced_assemblies_can_be_specified_zero_or_more_times"> <source>Path to referenced assemblies (can be specified zero or more times)</source> <target state="new">Path to referenced assemblies (can be specified zero or more times)</target> <note /> </trans-unit> <trans-unit id="Path_to_sources_to_use_in_rebuild"> <source>Path to sources to use in rebuild</source> <target state="new">Path to sources to use in rebuild</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="pl" original="../BuildValidatorResources.resx"> <body> <trans-unit id="Assemblies_to_be_excluded_substring_match"> <source>Assemblies to be excluded (substring match)</source> <target state="new">Assemblies to be excluded (substring match)</target> <note /> </trans-unit> <trans-unit id="Do_not_output_log_information_to_console"> <source>Do not output log information to console</source> <target state="new">Do not output log information to console</target> <note /> </trans-unit> <trans-unit id="Output_debug_info_when_rebuild_is_not_equal_to_the_original"> <source>Output debug info when rebuild is not equal to the original</source> <target state="new">Output debug info when rebuild is not equal to the original</target> <note /> </trans-unit> <trans-unit id="Output_verbose_log_information"> <source>Output verbose log information</source> <target state="new">Output verbose log information</target> <note /> </trans-unit> <trans-unit id="Path_to_assemblies_to_rebuild_can_be_specified_one_or_more_times"> <source>Path to assemblies to rebuild (can be specified one or more times)</source> <target state="new">Path to assemblies to rebuild (can be specified one or more times)</target> <note /> </trans-unit> <trans-unit id="Path_to_output_debug_info"> <source>Path to output debug info. Defaults to the user temp directory. Note that a unique debug path should be specified for every instance of the tool running with `--debug` enabled.</source> <target state="new">Path to output debug info. Defaults to the user temp directory. Note that a unique debug path should be specified for every instance of the tool running with `--debug` enabled.</target> <note /> </trans-unit> <trans-unit id="Path_to_referenced_assemblies_can_be_specified_zero_or_more_times"> <source>Path to referenced assemblies (can be specified zero or more times)</source> <target state="new">Path to referenced assemblies (can be specified zero or more times)</target> <note /> </trans-unit> <trans-unit id="Path_to_sources_to_use_in_rebuild"> <source>Path to sources to use in rebuild</source> <target state="new">Path to sources to use in rebuild</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/PartialMethodCompletionProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { public class PartialMethodCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(PartialMethodCompletionProvider); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoPartialMethods1() { var text = @"class c { $$ }"; await VerifyNoItemsExistAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoPartialMethods2() { var text = @"class c { private void goo() { }; partial void $$ }"; await VerifyNoItemsExistAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoExtendedPartialMethods2() { var text = @"class c { public void goo() { }; public void $$ }"; await VerifyNoItemsExistAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialMethodInPartialClass() { var text = @"partial class c { partial void goo(); partial void $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtendedPartialMethodInPartialClass() { var text = @"partial class c { public partial void goo(); public partial void $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialMethodInPartialGenericClass() { var text = @"partial class c<T> { partial void goo(T bar); partial void $$ }"; await VerifyItemExistsAsync(text, "goo(T bar)"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtendedPartialMethodInPartialGenericClass() { var text = @"partial class c<T> { public partial void goo(T bar); public partial void $$ }"; await VerifyItemExistsAsync(text, "goo(T bar)"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialMethodInPartialStruct() { var text = @"partial struct c { partial void goo(); partial void $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtendedPartialMethodInPartialStruct() { var text = @"partial struct c { public partial void goo(); public partial void $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionOnPartial1() { var text = @"partial class c { partial void goo(); partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionOnExtendedPartial1() { var text = @"partial class c { public partial void goo(); partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionOnPartial2() { var text = @"partial class c { partial void goo(); void partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionOnExtendedPartial2() { var text = @"partial class c { public partial void goo(); void partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticUnsafePartial() { var text = @"partial class c { partial static unsafe void goo(); void static unsafe partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticUnsafeExtendedPartial() { var text = @"partial class c { public partial static unsafe void goo(); void static unsafe partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialCompletionWithPrivate() { var text = @"partial class c { partial static unsafe void goo(); private partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialCompletionWithPublic() { var text = @"partial class c { public partial static unsafe void goo(); public partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotCompletionDespiteValidModifier() { var text = @"partial class c { partial void goo(); void partial unsafe $$ }"; await VerifyNoItemsExistAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoExtendedCompletionDespiteValidModifier() { var text = @"partial class c { public partial void goo(); void partial unsafe $$ }"; await VerifyNoItemsExistAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YesIfPublic() { var text = @"partial class c { public partial void goo(); void partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YesIfInternal() { var text = @"partial class c { internal partial void goo(); void partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YesIfProtected() { var text = @"partial class c { protected partial void goo(); void partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YesIfProtectedInternal() { var text = @"partial class c { protected internal partial void goo(); void partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YesIfExtern() { var text = @"partial class c { partial void goo(); extern void partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YesIfVirtual() { var text = @"partial class c { virtual partial void goo(); void partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YesIfNonVoidReturnType() { var text = @"partial class c { partial int goo(); partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInsideInterface() { var text = @"partial interface i { partial void goo(); partial $$ }"; await VerifyNoItemsExistAsync(text); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInPartialClass() { var markupBeforeCommit = @"partial class c { partial void goo(); partial $$ }"; var expectedCodeAfterCommit = @"partial class c { partial void goo(); partial void goo() { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInExtendedPartialClass() { var markupBeforeCommit = @"partial class c { public partial void goo(); partial $$ }"; var expectedCodeAfterCommit = @"partial class c { public partial void goo(); public partial void goo() { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitGenericPartialMethod() { var markupBeforeCommit = @"partial class c<T> { partial void goo(T bar); partial $$ }"; var expectedCodeAfterCommit = @"partial class c<T> { partial void goo(T bar); partial void goo(T bar) { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(T bar)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitGenericExtendedPartialMethod() { var markupBeforeCommit = @"partial class c<T> { public partial void goo(T bar); partial $$ }"; var expectedCodeAfterCommit = @"partial class c<T> { public partial void goo(T bar); public partial void goo(T bar) { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(T bar)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitMethodErasesPrivate() { var markupBeforeCommit = @"partial class c { partial void goo(); private partial $$ }"; var expectedCodeAfterCommit = @"partial class c { partial void goo(); partial void goo() { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitMethodKeepsExtendedPrivate() { var markupBeforeCommit = @"partial class c { private partial void goo(); private partial $$ }"; var expectedCodeAfterCommit = @"partial class c { private partial void goo(); private partial void goo() { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInPartialClassPart() { var markupBeforeCommit = @"partial class c { partial void goo(); } partial class c { partial $$ }"; var expectedCodeAfterCommit = @"partial class c { partial void goo(); } partial class c { partial void goo() { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInExtendedPartialClassPart() { var markupBeforeCommit = @"partial class c { public partial void goo(); } partial class c { partial $$ }"; var expectedCodeAfterCommit = @"partial class c { public partial void goo(); } partial class c { public partial void goo() { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInPartialStruct() { var markupBeforeCommit = @"partial struct c { partial void goo(); partial $$ }"; var expectedCodeAfterCommit = @"partial struct c { partial void goo(); partial void goo() { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotIfNoPartialKeyword() { var text = @"partial class C { partial void Goo(); } partial class C { void $$ } "; await VerifyNoItemsExistAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotIfNoExtendedPartialKeyword() { var text = @"partial class C { public partial void Goo(); } partial class C { void $$ } "; await VerifyNoItemsExistAsync(text); } [WorkItem(578757, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578757")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotConsiderFollowingDeclarationPartial() { var text = @"class Program { partial $$ void Goo() { } } "; await VerifyNoItemsExistAsync(text); } [WorkItem(578757, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578757")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotConsiderFollowingDeclarationExtendedPartial() { var text = @"class Program { public partial $$ void Goo() { } } "; await VerifyNoItemsExistAsync(text); } [WorkItem(578078, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578078")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAsync() { var markupBeforeCommit = @"using System; partial class Bar { partial void Goo(); async partial $$ }"; var expectedCodeAfterCommit = @"using System; partial class Bar { partial void Goo(); async partial void Goo() { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo()", expectedCodeAfterCommit); } [WorkItem(578078, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578078")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAsyncExtended() { var markupBeforeCommit = @"using System; partial class Bar { public partial void Goo(); async partial $$ }"; var expectedCodeAfterCommit = @"using System; partial class Bar { public partial void Goo(); public async partial void Goo() { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo()", expectedCodeAfterCommit); } [WorkItem(578078, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578078")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AmbiguityCommittingWithParen() { var markupBeforeCommit = @"using System; partial class Bar { partial void Goo(); partial Goo$$ }"; var expectedCodeAfterCommit = @"using System; partial class Bar { partial void Goo(); partial void Goo() { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo()", expectedCodeAfterCommit, commitChar: '('); } [WorkItem(965677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/965677")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoDefaultParameterValues() { var text = @"namespace PartialClass { partial class PClass { partial void PMethod(int i = 0); partial $$ } } "; var expected = @"namespace PartialClass { partial class PClass { partial void PMethod(int i = 0); partial void PMethod(int i) { throw new System.NotImplementedException();$$ } } } "; await VerifyCustomCommitProviderAsync(text, "PMethod(int i)", expected); } [WorkItem(965677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/965677")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoDefaultParameterValuesExtended() { var text = @"namespace PartialClass { partial class PClass { public partial void PMethod(int i = 0); partial $$ } } "; var expected = @"namespace PartialClass { partial class PClass { public partial void PMethod(int i = 0); public partial void PMethod(int i) { throw new System.NotImplementedException();$$ } } } "; await VerifyCustomCommitProviderAsync(text, "PMethod(int i)", expected); } [WorkItem(26388, "https://github.com/dotnet/roslyn/issues/26388")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionBodyMethod() { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var workspace = workspaceFixture.Target.GetWorkspace(ExportProvider); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption( CSharpCodeStyleOptions.PreferExpressionBodiedMethods, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent)))); var text = @"using System; partial class Bar { partial void Foo(); partial $$ } " ; var expected = @"using System; partial class Bar { partial void Foo(); partial void Foo() => throw new NotImplementedException();$$ } " ; await VerifyCustomCommitProviderAsync(text, "Foo()", expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionBodyMethodExtended() { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var workspace = workspaceFixture.Target.GetWorkspace(ExportProvider); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption( CSharpCodeStyleOptions.PreferExpressionBodiedMethods, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent)))); var text = @"using System; partial class Bar { public partial void Foo(); partial $$ } " ; var expected = @"using System; partial class Bar { public partial void Foo(); public partial void Foo() => throw new NotImplementedException();$$ } " ; await VerifyCustomCommitProviderAsync(text, "Foo()", expected); } private Task VerifyItemExistsAsync(string markup, string expectedItem) { return VerifyItemExistsAsync(markup, expectedItem, isComplexTextEdit: 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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { public class PartialMethodCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(PartialMethodCompletionProvider); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoPartialMethods1() { var text = @"class c { $$ }"; await VerifyNoItemsExistAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoPartialMethods2() { var text = @"class c { private void goo() { }; partial void $$ }"; await VerifyNoItemsExistAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoExtendedPartialMethods2() { var text = @"class c { public void goo() { }; public void $$ }"; await VerifyNoItemsExistAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialMethodInPartialClass() { var text = @"partial class c { partial void goo(); partial void $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtendedPartialMethodInPartialClass() { var text = @"partial class c { public partial void goo(); public partial void $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialMethodInPartialGenericClass() { var text = @"partial class c<T> { partial void goo(T bar); partial void $$ }"; await VerifyItemExistsAsync(text, "goo(T bar)"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtendedPartialMethodInPartialGenericClass() { var text = @"partial class c<T> { public partial void goo(T bar); public partial void $$ }"; await VerifyItemExistsAsync(text, "goo(T bar)"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialMethodInPartialStruct() { var text = @"partial struct c { partial void goo(); partial void $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtendedPartialMethodInPartialStruct() { var text = @"partial struct c { public partial void goo(); public partial void $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionOnPartial1() { var text = @"partial class c { partial void goo(); partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionOnExtendedPartial1() { var text = @"partial class c { public partial void goo(); partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionOnPartial2() { var text = @"partial class c { partial void goo(); void partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionOnExtendedPartial2() { var text = @"partial class c { public partial void goo(); void partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticUnsafePartial() { var text = @"partial class c { partial static unsafe void goo(); void static unsafe partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticUnsafeExtendedPartial() { var text = @"partial class c { public partial static unsafe void goo(); void static unsafe partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialCompletionWithPrivate() { var text = @"partial class c { partial static unsafe void goo(); private partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialCompletionWithPublic() { var text = @"partial class c { public partial static unsafe void goo(); public partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotCompletionDespiteValidModifier() { var text = @"partial class c { partial void goo(); void partial unsafe $$ }"; await VerifyNoItemsExistAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoExtendedCompletionDespiteValidModifier() { var text = @"partial class c { public partial void goo(); void partial unsafe $$ }"; await VerifyNoItemsExistAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YesIfPublic() { var text = @"partial class c { public partial void goo(); void partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YesIfInternal() { var text = @"partial class c { internal partial void goo(); void partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YesIfProtected() { var text = @"partial class c { protected partial void goo(); void partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YesIfProtectedInternal() { var text = @"partial class c { protected internal partial void goo(); void partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YesIfExtern() { var text = @"partial class c { partial void goo(); extern void partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YesIfVirtual() { var text = @"partial class c { virtual partial void goo(); void partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YesIfNonVoidReturnType() { var text = @"partial class c { partial int goo(); partial $$ }"; await VerifyItemExistsAsync(text, "goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInsideInterface() { var text = @"partial interface i { partial void goo(); partial $$ }"; await VerifyNoItemsExistAsync(text); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInPartialClass() { var markupBeforeCommit = @"partial class c { partial void goo(); partial $$ }"; var expectedCodeAfterCommit = @"partial class c { partial void goo(); partial void goo() { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInExtendedPartialClass() { var markupBeforeCommit = @"partial class c { public partial void goo(); partial $$ }"; var expectedCodeAfterCommit = @"partial class c { public partial void goo(); public partial void goo() { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitGenericPartialMethod() { var markupBeforeCommit = @"partial class c<T> { partial void goo(T bar); partial $$ }"; var expectedCodeAfterCommit = @"partial class c<T> { partial void goo(T bar); partial void goo(T bar) { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(T bar)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitGenericExtendedPartialMethod() { var markupBeforeCommit = @"partial class c<T> { public partial void goo(T bar); partial $$ }"; var expectedCodeAfterCommit = @"partial class c<T> { public partial void goo(T bar); public partial void goo(T bar) { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(T bar)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitMethodErasesPrivate() { var markupBeforeCommit = @"partial class c { partial void goo(); private partial $$ }"; var expectedCodeAfterCommit = @"partial class c { partial void goo(); partial void goo() { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitMethodKeepsExtendedPrivate() { var markupBeforeCommit = @"partial class c { private partial void goo(); private partial $$ }"; var expectedCodeAfterCommit = @"partial class c { private partial void goo(); private partial void goo() { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInPartialClassPart() { var markupBeforeCommit = @"partial class c { partial void goo(); } partial class c { partial $$ }"; var expectedCodeAfterCommit = @"partial class c { partial void goo(); } partial class c { partial void goo() { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInExtendedPartialClassPart() { var markupBeforeCommit = @"partial class c { public partial void goo(); } partial class c { partial $$ }"; var expectedCodeAfterCommit = @"partial class c { public partial void goo(); } partial class c { public partial void goo() { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInPartialStruct() { var markupBeforeCommit = @"partial struct c { partial void goo(); partial $$ }"; var expectedCodeAfterCommit = @"partial struct c { partial void goo(); partial void goo() { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotIfNoPartialKeyword() { var text = @"partial class C { partial void Goo(); } partial class C { void $$ } "; await VerifyNoItemsExistAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotIfNoExtendedPartialKeyword() { var text = @"partial class C { public partial void Goo(); } partial class C { void $$ } "; await VerifyNoItemsExistAsync(text); } [WorkItem(578757, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578757")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotConsiderFollowingDeclarationPartial() { var text = @"class Program { partial $$ void Goo() { } } "; await VerifyNoItemsExistAsync(text); } [WorkItem(578757, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578757")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotConsiderFollowingDeclarationExtendedPartial() { var text = @"class Program { public partial $$ void Goo() { } } "; await VerifyNoItemsExistAsync(text); } [WorkItem(578078, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578078")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAsync() { var markupBeforeCommit = @"using System; partial class Bar { partial void Goo(); async partial $$ }"; var expectedCodeAfterCommit = @"using System; partial class Bar { partial void Goo(); async partial void Goo() { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo()", expectedCodeAfterCommit); } [WorkItem(578078, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578078")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAsyncExtended() { var markupBeforeCommit = @"using System; partial class Bar { public partial void Goo(); async partial $$ }"; var expectedCodeAfterCommit = @"using System; partial class Bar { public partial void Goo(); public async partial void Goo() { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo()", expectedCodeAfterCommit); } [WorkItem(578078, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578078")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AmbiguityCommittingWithParen() { var markupBeforeCommit = @"using System; partial class Bar { partial void Goo(); partial Goo$$ }"; var expectedCodeAfterCommit = @"using System; partial class Bar { partial void Goo(); partial void Goo() { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo()", expectedCodeAfterCommit, commitChar: '('); } [WorkItem(965677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/965677")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoDefaultParameterValues() { var text = @"namespace PartialClass { partial class PClass { partial void PMethod(int i = 0); partial $$ } } "; var expected = @"namespace PartialClass { partial class PClass { partial void PMethod(int i = 0); partial void PMethod(int i) { throw new System.NotImplementedException();$$ } } } "; await VerifyCustomCommitProviderAsync(text, "PMethod(int i)", expected); } [WorkItem(965677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/965677")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoDefaultParameterValuesExtended() { var text = @"namespace PartialClass { partial class PClass { public partial void PMethod(int i = 0); partial $$ } } "; var expected = @"namespace PartialClass { partial class PClass { public partial void PMethod(int i = 0); public partial void PMethod(int i) { throw new System.NotImplementedException();$$ } } } "; await VerifyCustomCommitProviderAsync(text, "PMethod(int i)", expected); } [WorkItem(26388, "https://github.com/dotnet/roslyn/issues/26388")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionBodyMethod() { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var workspace = workspaceFixture.Target.GetWorkspace(ExportProvider); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption( CSharpCodeStyleOptions.PreferExpressionBodiedMethods, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent)))); var text = @"using System; partial class Bar { partial void Foo(); partial $$ } " ; var expected = @"using System; partial class Bar { partial void Foo(); partial void Foo() => throw new NotImplementedException();$$ } " ; await VerifyCustomCommitProviderAsync(text, "Foo()", expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionBodyMethodExtended() { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var workspace = workspaceFixture.Target.GetWorkspace(ExportProvider); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption( CSharpCodeStyleOptions.PreferExpressionBodiedMethods, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent)))); var text = @"using System; partial class Bar { public partial void Foo(); partial $$ } " ; var expected = @"using System; partial class Bar { public partial void Foo(); public partial void Foo() => throw new NotImplementedException();$$ } " ; await VerifyCustomCommitProviderAsync(text, "Foo()", expected); } private Task VerifyItemExistsAsync(string markup, string expectedItem) { return VerifyItemExistsAsync(markup, expectedItem, isComplexTextEdit: true); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Tools/ExternalAccess/FSharp/FindUsages/FSharpSourceReferenceItem.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.ExternalAccess.FSharp.FindUsages { internal class FSharpSourceReferenceItem { private readonly Microsoft.CodeAnalysis.FindUsages.SourceReferenceItem _roslynSourceReferenceItem; private FSharpSourceReferenceItem(Microsoft.CodeAnalysis.FindUsages.SourceReferenceItem roslynDefinitionItem) { _roslynSourceReferenceItem = roslynDefinitionItem; } public FSharpSourceReferenceItem(FSharpDefinitionItem definition, FSharpDocumentSpan sourceSpan) { _roslynSourceReferenceItem = new Microsoft.CodeAnalysis.FindUsages.SourceReferenceItem(definition.RoslynDefinitionItem, sourceSpan.ToRoslynDocumentSpan()); } internal Microsoft.CodeAnalysis.FindUsages.SourceReferenceItem RoslynSourceReferenceItem { get { return _roslynSourceReferenceItem; } } } }
// Licensed to the .NET Foundation under one or more 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.ExternalAccess.FSharp.FindUsages { internal class FSharpSourceReferenceItem { private readonly Microsoft.CodeAnalysis.FindUsages.SourceReferenceItem _roslynSourceReferenceItem; private FSharpSourceReferenceItem(Microsoft.CodeAnalysis.FindUsages.SourceReferenceItem roslynDefinitionItem) { _roslynSourceReferenceItem = roslynDefinitionItem; } public FSharpSourceReferenceItem(FSharpDefinitionItem definition, FSharpDocumentSpan sourceSpan) { _roslynSourceReferenceItem = new Microsoft.CodeAnalysis.FindUsages.SourceReferenceItem(definition.RoslynDefinitionItem, sourceSpan.ToRoslynDocumentSpan()); } internal Microsoft.CodeAnalysis.FindUsages.SourceReferenceItem RoslynSourceReferenceItem { get { return _roslynSourceReferenceItem; } } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/EditorFeatures/CSharpTest/Diagnostics/PreferFrameworkType/PreferFrameworkTypeTests.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.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Diagnostics.Analyzers; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.PreferFrameworkType; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.PreferFrameworkType { public partial class PreferFrameworkTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public PreferFrameworkTypeTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpPreferFrameworkTypeDiagnosticAnalyzer(), new PreferFrameworkTypeCodeFixProvider()); private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion); private readonly CodeStyleOption2<bool> offWithInfo = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion); private OptionsCollection NoFrameworkType => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo }, }; private OptionsCollection FrameworkTypeEverywhere => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo }, }; private OptionsCollection FrameworkTypeInDeclaration => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo }, }; private OptionsCollection FrameworkTypeInMemberAccess => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo }, }; [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotWhenOptionsAreNotSet() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|int|] x = 1; } }", new TestParameters(options: NoFrameworkType)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnDynamic() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|dynamic|] x = 1; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnSystemVoid() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { [|void|] Method() { } }", new TestParameters(options: FrameworkTypeEverywhere)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnUserdefinedType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|Program|] p; } }", new TestParameters(options: FrameworkTypeEverywhere)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnFrameworkType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|Int32|] p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnQualifiedTypeSyntax() { await TestMissingInRegularAndScriptAsync( @"class Program { void Method() { [|System.Int32|] p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnFrameworkTypeWithNoPredefinedKeywordEquivalent() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|List|]<int> p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnIdentifierThatIsNotTypeSyntax() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { int [|p|]; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task QualifiedReplacementWhenNoUsingFound() { var code = @"class Program { [|string|] _myfield = 5; }"; var expected = @"class Program { System.String _myfield = 5; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FieldDeclaration() { var code = @"using System; class Program { [|int|] _myfield; }"; var expected = @"using System; class Program { Int32 _myfield; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FieldDeclarationWithInitializer() { var code = @"using System; class Program { [|string|] _myfield = 5; }"; var expected = @"using System; class Program { String _myfield = 5; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DelegateDeclaration() { var code = @"using System; class Program { public delegate [|int|] PerformCalculation(int x, int y); }"; var expected = @"using System; class Program { public delegate Int32 PerformCalculation(int x, int y); }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task PropertyDeclaration() { var code = @"using System; class Program { public [|long|] MyProperty { get; set; } }"; var expected = @"using System; class Program { public Int64 MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task GenericPropertyDeclaration() { var code = @"using System; using System.Collections.Generic; class Program { public List<[|long|]> MyProperty { get; set; } }"; var expected = @"using System; using System.Collections.Generic; class Program { public List<Int64> MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task QualifiedReplacementInGenericTypeParameter() { var code = @"using System.Collections.Generic; class Program { public List<[|long|]> MyProperty { get; set; } }"; var expected = @"using System.Collections.Generic; class Program { public List<System.Int64> MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MethodDeclarationReturnType() { var code = @"using System; class Program { public [|long|] Method() { } }"; var expected = @"using System; class Program { public Int64 Method() { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MethodDeclarationParameters() { var code = @"using System; class Program { public void Method([|double|] d) { } }"; var expected = @"using System; class Program { public void Method(Double d) { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task GenericMethodInvocation() { var code = @"using System; class Program { public void Method<T>() { } public void Test() { Method<[|int|]>(); } }"; var expected = @"using System; class Program { public void Method<T>() { } public void Test() { Method<Int32>(); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task LocalDeclaration() { var code = @"using System; class Program { void Method() { [|int|] f = 5; } }"; var expected = @"using System; class Program { void Method() { Int32 f = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MemberAccess() { var code = @"using System; class Program { void Method() { Console.Write([|int|].MaxValue); } }"; var expected = @"using System; class Program { void Method() { Console.Write(Int32.MaxValue); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MemberAccess2() { var code = @"using System; class Program { void Method() { var x = [|int|].Parse(""1""); } }"; var expected = @"using System; class Program { void Method() { var x = Int32.Parse(""1""); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DocCommentTriviaCrefExpression() { var code = @"using System; class Program { /// <see cref=""[|int|].MaxValue""/> void Method() { } }"; var expected = @"using System; class Program { /// <see cref=""Int32.MaxValue""/> void Method() { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DefaultExpression() { var code = @"using System; class Program { void Method() { var v = default([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = default(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task TypeOfExpression() { var code = @"using System; class Program { void Method() { var v = typeof([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = typeof(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NameOfExpression() { var code = @"using System; class Program { void Method() { var v = nameof([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = nameof(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FormalParametersWithinLambdaExression() { var code = @"using System; class Program { void Method() { Func<int, int> func3 = ([|int|] z) => z + 1; } }"; var expected = @"using System; class Program { void Method() { Func<int, int> func3 = (Int32 z) => z + 1; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DelegateMethodExpression() { var code = @"using System; class Program { void Method() { Func<int, int> func7 = delegate ([|int|] dx) { return dx + 1; }; } }"; var expected = @"using System; class Program { void Method() { Func<int, int> func7 = delegate (Int32 dx) { return dx + 1; }; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ObjectCreationExpression() { var code = @"using System; class Program { void Method() { string s2 = new [|string|]('c', 1); } }"; var expected = @"using System; class Program { void Method() { string s2 = new String('c', 1); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ArrayDeclaration() { var code = @"using System; class Program { void Method() { [|int|][] k = new int[4]; } }"; var expected = @"using System; class Program { void Method() { Int32[] k = new int[4]; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ArrayInitializer() { var code = @"using System; class Program { void Method() { int[] k = new [|int|][] { 1, 2, 3 }; } }"; var expected = @"using System; class Program { void Method() { int[] k = new Int32[] { 1, 2, 3 }; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MultiDimentionalArrayAsGenericTypeParameter() { var code = @"using System; using System.Collections.Generic; class Program { void Method() { List<[|string|][][,][,,,]> a; } }"; var expected = @"using System; using System.Collections.Generic; class Program { void Method() { List<String[][,][,,,]> a; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ForStatement() { var code = @"using System; class Program { void Method() { for ([|int|] j = 0; j < 4; j++) { } } }"; var expected = @"using System; class Program { void Method() { for (Int32 j = 0; j < 4; j++) { } } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ForeachStatement() { var code = @"using System; class Program { void Method() { foreach ([|int|] item in new int[] { 1, 2, 3 }) { } } }"; var expected = @"using System; class Program { void Method() { foreach (Int32 item in new int[] { 1, 2, 3 }) { } } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task LeadingTrivia() { var code = @"using System; class Program { void Method() { // this is a comment [|int|] x = 5; } }"; var expected = @"using System; class Program { void Method() { // this is a comment Int32 x = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task TrailingTrivia() { var code = @"using System; class Program { void Method() { [|int|] /* 2 */ x = 5; } }"; var expected = @"using System; class Program { void Method() { Int32 /* 2 */ x = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } } }
// Licensed to the .NET Foundation under one or more 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.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Diagnostics.Analyzers; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.PreferFrameworkType; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.PreferFrameworkType { public partial class PreferFrameworkTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public PreferFrameworkTypeTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpPreferFrameworkTypeDiagnosticAnalyzer(), new PreferFrameworkTypeCodeFixProvider()); private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion); private readonly CodeStyleOption2<bool> offWithInfo = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion); private OptionsCollection NoFrameworkType => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo }, }; private OptionsCollection FrameworkTypeEverywhere => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo }, }; private OptionsCollection FrameworkTypeInDeclaration => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo }, }; private OptionsCollection FrameworkTypeInMemberAccess => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo }, }; [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotWhenOptionsAreNotSet() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|int|] x = 1; } }", new TestParameters(options: NoFrameworkType)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnDynamic() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|dynamic|] x = 1; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnSystemVoid() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { [|void|] Method() { } }", new TestParameters(options: FrameworkTypeEverywhere)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnUserdefinedType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|Program|] p; } }", new TestParameters(options: FrameworkTypeEverywhere)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnFrameworkType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|Int32|] p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnQualifiedTypeSyntax() { await TestMissingInRegularAndScriptAsync( @"class Program { void Method() { [|System.Int32|] p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnFrameworkTypeWithNoPredefinedKeywordEquivalent() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|List|]<int> p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnIdentifierThatIsNotTypeSyntax() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { int [|p|]; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task QualifiedReplacementWhenNoUsingFound() { var code = @"class Program { [|string|] _myfield = 5; }"; var expected = @"class Program { System.String _myfield = 5; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FieldDeclaration() { var code = @"using System; class Program { [|int|] _myfield; }"; var expected = @"using System; class Program { Int32 _myfield; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FieldDeclarationWithInitializer() { var code = @"using System; class Program { [|string|] _myfield = 5; }"; var expected = @"using System; class Program { String _myfield = 5; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DelegateDeclaration() { var code = @"using System; class Program { public delegate [|int|] PerformCalculation(int x, int y); }"; var expected = @"using System; class Program { public delegate Int32 PerformCalculation(int x, int y); }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task PropertyDeclaration() { var code = @"using System; class Program { public [|long|] MyProperty { get; set; } }"; var expected = @"using System; class Program { public Int64 MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task GenericPropertyDeclaration() { var code = @"using System; using System.Collections.Generic; class Program { public List<[|long|]> MyProperty { get; set; } }"; var expected = @"using System; using System.Collections.Generic; class Program { public List<Int64> MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task QualifiedReplacementInGenericTypeParameter() { var code = @"using System.Collections.Generic; class Program { public List<[|long|]> MyProperty { get; set; } }"; var expected = @"using System.Collections.Generic; class Program { public List<System.Int64> MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MethodDeclarationReturnType() { var code = @"using System; class Program { public [|long|] Method() { } }"; var expected = @"using System; class Program { public Int64 Method() { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MethodDeclarationParameters() { var code = @"using System; class Program { public void Method([|double|] d) { } }"; var expected = @"using System; class Program { public void Method(Double d) { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task GenericMethodInvocation() { var code = @"using System; class Program { public void Method<T>() { } public void Test() { Method<[|int|]>(); } }"; var expected = @"using System; class Program { public void Method<T>() { } public void Test() { Method<Int32>(); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task LocalDeclaration() { var code = @"using System; class Program { void Method() { [|int|] f = 5; } }"; var expected = @"using System; class Program { void Method() { Int32 f = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MemberAccess() { var code = @"using System; class Program { void Method() { Console.Write([|int|].MaxValue); } }"; var expected = @"using System; class Program { void Method() { Console.Write(Int32.MaxValue); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MemberAccess2() { var code = @"using System; class Program { void Method() { var x = [|int|].Parse(""1""); } }"; var expected = @"using System; class Program { void Method() { var x = Int32.Parse(""1""); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DocCommentTriviaCrefExpression() { var code = @"using System; class Program { /// <see cref=""[|int|].MaxValue""/> void Method() { } }"; var expected = @"using System; class Program { /// <see cref=""Int32.MaxValue""/> void Method() { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DefaultExpression() { var code = @"using System; class Program { void Method() { var v = default([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = default(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task TypeOfExpression() { var code = @"using System; class Program { void Method() { var v = typeof([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = typeof(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NameOfExpression() { var code = @"using System; class Program { void Method() { var v = nameof([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = nameof(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FormalParametersWithinLambdaExression() { var code = @"using System; class Program { void Method() { Func<int, int> func3 = ([|int|] z) => z + 1; } }"; var expected = @"using System; class Program { void Method() { Func<int, int> func3 = (Int32 z) => z + 1; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DelegateMethodExpression() { var code = @"using System; class Program { void Method() { Func<int, int> func7 = delegate ([|int|] dx) { return dx + 1; }; } }"; var expected = @"using System; class Program { void Method() { Func<int, int> func7 = delegate (Int32 dx) { return dx + 1; }; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ObjectCreationExpression() { var code = @"using System; class Program { void Method() { string s2 = new [|string|]('c', 1); } }"; var expected = @"using System; class Program { void Method() { string s2 = new String('c', 1); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ArrayDeclaration() { var code = @"using System; class Program { void Method() { [|int|][] k = new int[4]; } }"; var expected = @"using System; class Program { void Method() { Int32[] k = new int[4]; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ArrayInitializer() { var code = @"using System; class Program { void Method() { int[] k = new [|int|][] { 1, 2, 3 }; } }"; var expected = @"using System; class Program { void Method() { int[] k = new Int32[] { 1, 2, 3 }; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MultiDimentionalArrayAsGenericTypeParameter() { var code = @"using System; using System.Collections.Generic; class Program { void Method() { List<[|string|][][,][,,,]> a; } }"; var expected = @"using System; using System.Collections.Generic; class Program { void Method() { List<String[][,][,,,]> a; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ForStatement() { var code = @"using System; class Program { void Method() { for ([|int|] j = 0; j < 4; j++) { } } }"; var expected = @"using System; class Program { void Method() { for (Int32 j = 0; j < 4; j++) { } } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ForeachStatement() { var code = @"using System; class Program { void Method() { foreach ([|int|] item in new int[] { 1, 2, 3 }) { } } }"; var expected = @"using System; class Program { void Method() { foreach (Int32 item in new int[] { 1, 2, 3 }) { } } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task LeadingTrivia() { var code = @"using System; class Program { void Method() { // this is a comment [|int|] x = 5; } }"; var expected = @"using System; class Program { void Method() { // this is a comment Int32 x = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task TrailingTrivia() { var code = @"using System; class Program { void Method() { [|int|] /* 2 */ x = 5; } }"; var expected = @"using System; class Program { void Method() { Int32 /* 2 */ x = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/VisualStudio/Core/Def/Implementation/AbstractOleCommandTarget.Execute.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.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal abstract partial class AbstractOleCommandTarget { public virtual int Exec(ref Guid pguidCmdGroup, uint commandId, uint executeInformation, IntPtr pvaIn, IntPtr pvaOut) { try { this.CurrentlyExecutingCommand = commandId; // If we don't have a subject buffer, then that means we're outside our code and we should ignore it // Also, ignore the command if executeInformation indicates isn't meant to be executed. From env\msenv\core\cmdwin.cpp: // To query the parameter type list of a command, we call Exec with // the LOWORD of nCmdexecopt set to OLECMDEXECOPT_SHOWHELP (instead of // the more usual OLECMDEXECOPT_DODEFAULT), the HIWORD of nCmdexecopt // set to VSCmdOptQueryParameterList, pvaIn set to NULL, and pvaOut // pointing to a VARIANT ready to receive the result BSTR. var shouldSkipCommand = executeInformation == (((uint)VsMenus.VSCmdOptQueryParameterList << 16) | (uint)OLECMDEXECOPT.OLECMDEXECOPT_SHOWHELP); if (shouldSkipCommand || GetSubjectBufferContainingCaret() == null) { return NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut); } if (pguidCmdGroup == VSConstants.VSStd2K) { return ExecuteVisualStudio2000(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut); } else if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) { return ExecuteVisualStudio97(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut); } else { return NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut); } } finally { this.CurrentlyExecutingCommand = default; } } private int ExecuteVisualStudio97(ref Guid pguidCmdGroup, uint commandId, uint executeInformation, IntPtr pvaIn, IntPtr pvaOut) { switch ((VSConstants.VSStd97CmdID)commandId) { case VSConstants.VSStd97CmdID.Paste: case VSConstants.VSStd97CmdID.Delete: case VSConstants.VSStd97CmdID.SelectAll: case VSConstants.VSStd97CmdID.Undo: case VSConstants.VSStd97CmdID.Redo: case VSConstants.VSStd97CmdID.MultiLevelUndo: case VSConstants.VSStd97CmdID.MultiLevelRedo: GCManager.UseLowLatencyModeForProcessingUserInput(); return NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut); default: return NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut); } } protected virtual int ExecuteVisualStudio2000(ref Guid pguidCmdGroup, uint commandId, uint executeInformation, IntPtr pvaIn, IntPtr pvaOut) { switch ((VSConstants.VSStd2KCmdID)commandId) { case VSConstants.VSStd2KCmdID.TYPECHAR: case VSConstants.VSStd2KCmdID.RETURN: case VSConstants.VSStd2KCmdID.TAB: case VSConstants.VSStd2KCmdID.BACKTAB: case VSConstants.VSStd2KCmdID.HOME: case VSConstants.VSStd2KCmdID.END: case VSConstants.VSStd2KCmdID.BOL: case VSConstants.VSStd2KCmdID.BOL_EXT: case VSConstants.VSStd2KCmdID.EOL: case VSConstants.VSStd2KCmdID.EOL_EXT: case VSConstants.VSStd2KCmdID.SELECTALL: case VSConstants.VSStd2KCmdID.OPENLINEABOVE: case VSConstants.VSStd2KCmdID.OPENLINEBELOW: case VSConstants.VSStd2KCmdID.UP: case VSConstants.VSStd2KCmdID.DOWN: case VSConstants.VSStd2KCmdID.BACKSPACE: case VSConstants.VSStd2KCmdID.DELETE: case VSConstants.VSStd2KCmdID.ECMD_INSERTCOMMENT: case VSConstants.VSStd2KCmdID.COMPLETEWORD: case VSConstants.VSStd2KCmdID.SHOWMEMBERLIST: case VSConstants.VSStd2KCmdID.PARAMINFO: case VSConstants.VSStd2KCmdID.RENAME: case VSConstants.VSStd2KCmdID.EXTRACTINTERFACE: case VSConstants.VSStd2KCmdID.EXTRACTMETHOD: case VSConstants.VSStd2KCmdID.PASTE: case VSConstants.VSStd2KCmdID.INSERTSNIPPET: case VSConstants.VSStd2KCmdID.SURROUNDWITH: GCManager.UseLowLatencyModeForProcessingUserInput(); return NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut); default: return NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut); } } } }
// Licensed to the .NET Foundation under one or more 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.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal abstract partial class AbstractOleCommandTarget { public virtual int Exec(ref Guid pguidCmdGroup, uint commandId, uint executeInformation, IntPtr pvaIn, IntPtr pvaOut) { try { this.CurrentlyExecutingCommand = commandId; // If we don't have a subject buffer, then that means we're outside our code and we should ignore it // Also, ignore the command if executeInformation indicates isn't meant to be executed. From env\msenv\core\cmdwin.cpp: // To query the parameter type list of a command, we call Exec with // the LOWORD of nCmdexecopt set to OLECMDEXECOPT_SHOWHELP (instead of // the more usual OLECMDEXECOPT_DODEFAULT), the HIWORD of nCmdexecopt // set to VSCmdOptQueryParameterList, pvaIn set to NULL, and pvaOut // pointing to a VARIANT ready to receive the result BSTR. var shouldSkipCommand = executeInformation == (((uint)VsMenus.VSCmdOptQueryParameterList << 16) | (uint)OLECMDEXECOPT.OLECMDEXECOPT_SHOWHELP); if (shouldSkipCommand || GetSubjectBufferContainingCaret() == null) { return NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut); } if (pguidCmdGroup == VSConstants.VSStd2K) { return ExecuteVisualStudio2000(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut); } else if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) { return ExecuteVisualStudio97(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut); } else { return NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut); } } finally { this.CurrentlyExecutingCommand = default; } } private int ExecuteVisualStudio97(ref Guid pguidCmdGroup, uint commandId, uint executeInformation, IntPtr pvaIn, IntPtr pvaOut) { switch ((VSConstants.VSStd97CmdID)commandId) { case VSConstants.VSStd97CmdID.Paste: case VSConstants.VSStd97CmdID.Delete: case VSConstants.VSStd97CmdID.SelectAll: case VSConstants.VSStd97CmdID.Undo: case VSConstants.VSStd97CmdID.Redo: case VSConstants.VSStd97CmdID.MultiLevelUndo: case VSConstants.VSStd97CmdID.MultiLevelRedo: GCManager.UseLowLatencyModeForProcessingUserInput(); return NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut); default: return NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut); } } protected virtual int ExecuteVisualStudio2000(ref Guid pguidCmdGroup, uint commandId, uint executeInformation, IntPtr pvaIn, IntPtr pvaOut) { switch ((VSConstants.VSStd2KCmdID)commandId) { case VSConstants.VSStd2KCmdID.TYPECHAR: case VSConstants.VSStd2KCmdID.RETURN: case VSConstants.VSStd2KCmdID.TAB: case VSConstants.VSStd2KCmdID.BACKTAB: case VSConstants.VSStd2KCmdID.HOME: case VSConstants.VSStd2KCmdID.END: case VSConstants.VSStd2KCmdID.BOL: case VSConstants.VSStd2KCmdID.BOL_EXT: case VSConstants.VSStd2KCmdID.EOL: case VSConstants.VSStd2KCmdID.EOL_EXT: case VSConstants.VSStd2KCmdID.SELECTALL: case VSConstants.VSStd2KCmdID.OPENLINEABOVE: case VSConstants.VSStd2KCmdID.OPENLINEBELOW: case VSConstants.VSStd2KCmdID.UP: case VSConstants.VSStd2KCmdID.DOWN: case VSConstants.VSStd2KCmdID.BACKSPACE: case VSConstants.VSStd2KCmdID.DELETE: case VSConstants.VSStd2KCmdID.ECMD_INSERTCOMMENT: case VSConstants.VSStd2KCmdID.COMPLETEWORD: case VSConstants.VSStd2KCmdID.SHOWMEMBERLIST: case VSConstants.VSStd2KCmdID.PARAMINFO: case VSConstants.VSStd2KCmdID.RENAME: case VSConstants.VSStd2KCmdID.EXTRACTINTERFACE: case VSConstants.VSStd2KCmdID.EXTRACTMETHOD: case VSConstants.VSStd2KCmdID.PASTE: case VSConstants.VSStd2KCmdID.INSERTSNIPPET: case VSConstants.VSStd2KCmdID.SURROUNDWITH: GCManager.UseLowLatencyModeForProcessingUserInput(); return NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut); default: return NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut); } } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOptions2.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeStyle.CodeStyleHelpers; namespace Microsoft.CodeAnalysis.CodeStyle { internal static class CodeStyleOptions2 { private static readonly ImmutableArray<IOption2>.Builder s_allOptionsBuilder = ImmutableArray.CreateBuilder<IOption2>(); internal static ImmutableArray<IOption2> AllOptions { get; } private static PerLanguageOption2<T> CreateOption<T>( OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation) { var option = new PerLanguageOption2<T>( "CodeStyleOptions", group, name, defaultValue, ImmutableArray.Create(storageLocation)); s_allOptionsBuilder.Add(option); return option; } private static PerLanguageOption2<T> CreateOption<T>( OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation1, OptionStorageLocation2 storageLocation2) { var option = new PerLanguageOption2<T>( "CodeStyleOptions", group, name, defaultValue, ImmutableArray.Create(storageLocation1, storageLocation2)); s_allOptionsBuilder.Add(option); return option; } private static Option2<T> CreateCommonOption<T>(OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation) { var option = new Option2<T>( "CodeStyleOptions", group, name, defaultValue, ImmutableArray.Create(storageLocation)); s_allOptionsBuilder.Add(option); return option; } private static Option2<T> CreateCommonOption<T>( OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation1, OptionStorageLocation2 storageLocation2) { var option = new Option2<T>( "CodeStyleOptions", group, name, defaultValue, ImmutableArray.Create(storageLocation1, storageLocation2)); s_allOptionsBuilder.Add(option); return option; } /// <remarks> /// When user preferences are not yet set for a style, we fall back to the default value. /// One such default(s), is that the feature is turned on, so that codegen consumes it, /// but with silent enforcement, so that the user is not prompted about their usage. /// </remarks> internal static readonly CodeStyleOption2<bool> TrueWithSilentEnforcement = new(value: true, notification: NotificationOption2.Silent); internal static readonly CodeStyleOption2<bool> FalseWithSilentEnforcement = new(value: false, notification: NotificationOption2.Silent); internal static readonly CodeStyleOption2<bool> TrueWithSuggestionEnforcement = new(value: true, notification: NotificationOption2.Suggestion); internal static readonly CodeStyleOption2<bool> FalseWithSuggestionEnforcement = new(value: false, notification: NotificationOption2.Suggestion); private static PerLanguageOption2<CodeStyleOption2<bool>> CreateOption( OptionGroup group, string name, CodeStyleOption2<bool> defaultValue, string editorconfigKeyName, string roamingProfileStorageKeyName) => CreateOption( group, name, defaultValue, EditorConfigStorageLocation.ForBoolCodeStyleOption(editorconfigKeyName, defaultValue), new RoamingProfileStorageLocation(roamingProfileStorageKeyName)); private static PerLanguageOption2<CodeStyleOption2<bool>> CreateQualifyAccessOption(string optionName, string editorconfigKeyName) => CreateOption( CodeStyleOptionGroups.ThisOrMe, optionName, defaultValue: CodeStyleOption2<bool>.Default, editorconfigKeyName, $"TextEditor.%LANGUAGE%.Specific.{optionName}"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in field access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyFieldAccess = CreateQualifyAccessOption( nameof(QualifyFieldAccess), "dotnet_style_qualification_for_field"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in property access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyPropertyAccess = CreateQualifyAccessOption( nameof(QualifyPropertyAccess), "dotnet_style_qualification_for_property"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in method access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyMethodAccess = CreateQualifyAccessOption( nameof(QualifyMethodAccess), "dotnet_style_qualification_for_method"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in event access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyEventAccess = CreateQualifyAccessOption( nameof(QualifyEventAccess), "dotnet_style_qualification_for_event"); /// <summary> /// This option says if we should prefer keyword for Intrinsic Predefined Types in Declarations /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIntrinsicPredefinedTypeKeywordInDeclaration = CreateOption( CodeStyleOptionGroups.PredefinedTypeNameUsage, nameof(PreferIntrinsicPredefinedTypeKeywordInDeclaration), defaultValue: TrueWithSilentEnforcement, "dotnet_style_predefined_type_for_locals_parameters_members", "TextEditor.%LANGUAGE%.Specific.PreferIntrinsicPredefinedTypeKeywordInDeclaration.CodeStyle"); /// <summary> /// This option says if we should prefer keyword for Intrinsic Predefined Types in Member Access Expression /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIntrinsicPredefinedTypeKeywordInMemberAccess = CreateOption( CodeStyleOptionGroups.PredefinedTypeNameUsage, nameof(PreferIntrinsicPredefinedTypeKeywordInMemberAccess), defaultValue: TrueWithSilentEnforcement, "dotnet_style_predefined_type_for_member_access", "TextEditor.%LANGUAGE%.Specific.PreferIntrinsicPredefinedTypeKeywordInMemberAccess.CodeStyle"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferObjectInitializer = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferObjectInitializer), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_object_initializer", "TextEditor.%LANGUAGE%.Specific.PreferObjectInitializer"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCollectionInitializer = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCollectionInitializer), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_collection_initializer", "TextEditor.%LANGUAGE%.Specific.PreferCollectionInitializer"); // TODO: Should both the below "_FadeOutCode" options be added to AllOptions? internal static readonly PerLanguageOption2<bool> PreferObjectInitializer_FadeOutCode = new( "CodeStyleOptions", nameof(PreferObjectInitializer_FadeOutCode), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferObjectInitializer_FadeOutCode")); internal static readonly PerLanguageOption2<bool> PreferCollectionInitializer_FadeOutCode = new( "CodeStyleOptions", nameof(PreferCollectionInitializer_FadeOutCode), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferCollectionInitializer_FadeOutCode")); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSimplifiedBooleanExpressions = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimplifiedBooleanExpressions), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_simplified_boolean_expressions", "TextEditor.%LANGUAGE%.Specific.PreferSimplifiedBooleanExpressions"); internal static readonly PerLanguageOption2<OperatorPlacementWhenWrappingPreference> OperatorPlacementWhenWrapping = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(OperatorPlacementWhenWrapping), defaultValue: OperatorPlacementWhenWrappingPreference.BeginningOfLine, new EditorConfigStorageLocation<OperatorPlacementWhenWrappingPreference>( "dotnet_style_operator_placement_when_wrapping", OperatorPlacementUtilities.Parse, OperatorPlacementUtilities.GetEditorConfigString)); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCoalesceExpression = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCoalesceExpression), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_coalesce_expression", "TextEditor.%LANGUAGE%.Specific.PreferCoalesceExpression"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferNullPropagation = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferNullPropagation), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_null_propagation", "TextEditor.%LANGUAGE%.Specific.PreferNullPropagation"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferExplicitTupleNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferExplicitTupleNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_explicit_tuple_names", "TextEditor.%LANGUAGE%.Specific.PreferExplicitTupleNames"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferAutoProperties = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferAutoProperties), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_auto_properties", "TextEditor.%LANGUAGE%.Specific.PreferAutoProperties"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferInferredTupleNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInferredTupleNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_inferred_tuple_names", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferInferredTupleNames)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferInferredAnonymousTypeMemberNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInferredAnonymousTypeMemberNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_inferred_anonymous_type_member_names", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferInferredAnonymousTypeMemberNames)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIsNullCheckOverReferenceEqualityMethod = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferIsNullCheckOverReferenceEqualityMethod), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_is_null_check_over_reference_equality_method", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferIsNullCheckOverReferenceEqualityMethod)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferConditionalExpressionOverAssignment = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferConditionalExpressionOverAssignment), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_conditional_expression_over_assignment", "TextEditor.%LANGUAGE%.Specific.PreferConditionalExpressionOverAssignment"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferConditionalExpressionOverReturn = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferConditionalExpressionOverReturn), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_conditional_expression_over_return", "TextEditor.%LANGUAGE%.Specific.PreferConditionalExpressionOverReturn"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCompoundAssignment = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCompoundAssignment), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_compound_assignment", "TextEditor.%LANGUAGE%.Specific.PreferCompoundAssignment"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSimplifiedInterpolation = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimplifiedInterpolation), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_simplified_interpolation", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferSimplifiedInterpolation)}"); private static readonly CodeStyleOption2<UnusedParametersPreference> s_preferAllMethodsUnusedParametersPreference = new(UnusedParametersPreference.AllMethods, NotificationOption2.Suggestion); // TODO: https://github.com/dotnet/roslyn/issues/31225 tracks adding CodeQualityOption<T> and CodeQualityOptions // and moving this option to CodeQualityOptions. internal static readonly PerLanguageOption2<CodeStyleOption2<UnusedParametersPreference>> UnusedParameters = CreateOption( CodeStyleOptionGroups.Parameter, nameof(UnusedParameters), defaultValue: s_preferAllMethodsUnusedParametersPreference, new EditorConfigStorageLocation<CodeStyleOption2<UnusedParametersPreference>>( "dotnet_code_quality_unused_parameters", s => ParseUnusedParametersPreference(s, s_preferAllMethodsUnusedParametersPreference), o => GetUnusedParametersPreferenceEditorConfigString(o, s_preferAllMethodsUnusedParametersPreference)), new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(UnusedParameters)}Preference")); private static readonly CodeStyleOption2<AccessibilityModifiersRequired> s_requireAccessibilityModifiersDefault = new(AccessibilityModifiersRequired.ForNonInterfaceMembers, NotificationOption2.Silent); internal static readonly PerLanguageOption2<CodeStyleOption2<AccessibilityModifiersRequired>> RequireAccessibilityModifiers = CreateOption( CodeStyleOptionGroups.Modifier, nameof(RequireAccessibilityModifiers), defaultValue: s_requireAccessibilityModifiersDefault, new EditorConfigStorageLocation<CodeStyleOption2<AccessibilityModifiersRequired>>( "dotnet_style_require_accessibility_modifiers", s => ParseAccessibilityModifiersRequired(s, s_requireAccessibilityModifiersDefault), v => GetAccessibilityModifiersRequiredEditorConfigString(v, s_requireAccessibilityModifiersDefault)), new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.RequireAccessibilityModifiers")); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferReadonly = CreateOption( CodeStyleOptionGroups.Field, nameof(PreferReadonly), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_readonly_field", "TextEditor.%LANGUAGE%.Specific.PreferReadonly"); internal static readonly Option2<string> FileHeaderTemplate = CreateCommonOption( CodeStyleOptionGroups.Usings, nameof(FileHeaderTemplate), defaultValue: "", EditorConfigStorageLocation.ForStringOption("file_header_template", emptyStringRepresentation: "unset")); internal static readonly Option2<string> RemoveUnnecessarySuppressionExclusions = CreateCommonOption( CodeStyleOptionGroups.Suppressions, nameof(RemoveUnnecessarySuppressionExclusions), defaultValue: "", EditorConfigStorageLocation.ForStringOption("dotnet_remove_unnecessary_suppression_exclusions", emptyStringRepresentation: "none"), new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.RemoveUnnecessarySuppressionExclusions")); private static readonly BidirectionalMap<string, AccessibilityModifiersRequired> s_accessibilityModifiersRequiredMap = new(new[] { KeyValuePairUtil.Create("never", AccessibilityModifiersRequired.Never), KeyValuePairUtil.Create("always", AccessibilityModifiersRequired.Always), KeyValuePairUtil.Create("for_non_interface_members", AccessibilityModifiersRequired.ForNonInterfaceMembers), KeyValuePairUtil.Create("omit_if_default", AccessibilityModifiersRequired.OmitIfDefault), }); private static CodeStyleOption2<AccessibilityModifiersRequired> ParseAccessibilityModifiersRequired(string optionString, CodeStyleOption2<AccessibilityModifiersRequired> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notificationOpt)) { Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsKey(value)); return new CodeStyleOption2<AccessibilityModifiersRequired>(s_accessibilityModifiersRequiredMap.GetValueOrDefault(value), notificationOpt); } return s_requireAccessibilityModifiersDefault; } private static string GetAccessibilityModifiersRequiredEditorConfigString(CodeStyleOption2<AccessibilityModifiersRequired> option, CodeStyleOption2<AccessibilityModifiersRequired> defaultValue) { // If they provide 'never', they don't need a notification level. if (option.Notification == null) { Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsValue(AccessibilityModifiersRequired.Never)); return s_accessibilityModifiersRequiredMap.GetKeyOrDefault(AccessibilityModifiersRequired.Never)!; } Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsValue(option.Value)); return $"{s_accessibilityModifiersRequiredMap.GetKeyOrDefault(option.Value)}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } private static readonly CodeStyleOption2<ParenthesesPreference> s_alwaysForClarityPreference = new(ParenthesesPreference.AlwaysForClarity, NotificationOption2.Silent); private static readonly CodeStyleOption2<ParenthesesPreference> s_neverIfUnnecessaryPreference = new(ParenthesesPreference.NeverIfUnnecessary, NotificationOption2.Silent); private static PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> CreateParenthesesOption( string fieldName, CodeStyleOption2<ParenthesesPreference> defaultValue, string styleName) { return CreateOption( CodeStyleOptionGroups.Parentheses, fieldName, defaultValue, new EditorConfigStorageLocation<CodeStyleOption2<ParenthesesPreference>>( styleName, s => ParseParenthesesPreference(s, defaultValue), v => GetParenthesesPreferenceEditorConfigString(v, defaultValue)), new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{fieldName}Preference")); } internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> ArithmeticBinaryParentheses = CreateParenthesesOption( nameof(ArithmeticBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_arithmetic_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> OtherBinaryParentheses = CreateParenthesesOption( nameof(OtherBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_other_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> RelationalBinaryParentheses = CreateParenthesesOption( nameof(RelationalBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_relational_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> OtherParentheses = CreateParenthesesOption( nameof(OtherParentheses), s_neverIfUnnecessaryPreference, "dotnet_style_parentheses_in_other_operators"); private static readonly BidirectionalMap<string, ParenthesesPreference> s_parenthesesPreferenceMap = new(new[] { KeyValuePairUtil.Create("always_for_clarity", ParenthesesPreference.AlwaysForClarity), KeyValuePairUtil.Create("never_if_unnecessary", ParenthesesPreference.NeverIfUnnecessary), }); private static readonly BidirectionalMap<string, UnusedParametersPreference> s_unusedParametersPreferenceMap = new(new[] { KeyValuePairUtil.Create("non_public", UnusedParametersPreference.NonPublicMethods), KeyValuePairUtil.Create("all", UnusedParametersPreference.AllMethods), }); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSystemHashCode = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSystemHashCode), defaultValue: TrueWithSuggestionEnforcement, new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferSystemHashCode")); public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferNamespaceAndFolderMatchStructure = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferNamespaceAndFolderMatchStructure), defaultValue: TrueWithSuggestionEnforcement, editorconfigKeyName: "dotnet_style_namespace_match_folder", roamingProfileStorageKeyName: $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferNamespaceAndFolderMatchStructure)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> AllowMultipleBlankLines = CreateOption( CodeStyleOptionGroups.NewLinePreferences, nameof(AllowMultipleBlankLines), defaultValue: TrueWithSilentEnforcement, "dotnet_style_allow_multiple_blank_lines_experimental", "TextEditor.%LANGUAGE%.Specific.AllowMultipleBlankLines"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> AllowStatementImmediatelyAfterBlock = CreateOption( CodeStyleOptionGroups.NewLinePreferences, nameof(AllowStatementImmediatelyAfterBlock), defaultValue: TrueWithSilentEnforcement, "dotnet_style_allow_statement_immediately_after_block_experimental", "TextEditor.%LANGUAGE%.Specific.AllowStatementImmediatelyAfterBlock"); static CodeStyleOptions2() { // Note that the static constructor executes after all the static field initializers for the options have executed, // and each field initializer adds the created option to s_allOptionsBuilder. AllOptions = s_allOptionsBuilder.ToImmutable(); } private static CodeStyleOption2<ParenthesesPreference> ParseParenthesesPreference( string optionString, CodeStyleOption2<ParenthesesPreference> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notification)) { Debug.Assert(s_parenthesesPreferenceMap.ContainsKey(value)); return new CodeStyleOption2<ParenthesesPreference>(s_parenthesesPreferenceMap.GetValueOrDefault(value), notification); } return defaultValue; } private static string GetParenthesesPreferenceEditorConfigString(CodeStyleOption2<ParenthesesPreference> option, CodeStyleOption2<ParenthesesPreference> defaultValue) { Debug.Assert(s_parenthesesPreferenceMap.ContainsValue(option.Value)); var value = s_parenthesesPreferenceMap.GetKeyOrDefault(option.Value) ?? s_parenthesesPreferenceMap.GetKeyOrDefault(ParenthesesPreference.AlwaysForClarity); return option.Notification == null ? value! : $"{value}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } private static CodeStyleOption2<UnusedParametersPreference> ParseUnusedParametersPreference(string optionString, CodeStyleOption2<UnusedParametersPreference> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notification)) { return new CodeStyleOption2<UnusedParametersPreference>(s_unusedParametersPreferenceMap.GetValueOrDefault(value), notification); } return defaultValue; } private static string GetUnusedParametersPreferenceEditorConfigString(CodeStyleOption2<UnusedParametersPreference> option, CodeStyleOption2<UnusedParametersPreference> defaultValue) { Debug.Assert(s_unusedParametersPreferenceMap.ContainsValue(option.Value)); var value = s_unusedParametersPreferenceMap.GetKeyOrDefault(option.Value) ?? s_unusedParametersPreferenceMap.GetKeyOrDefault(defaultValue.Value); return option.Notification == null ? value! : $"{value}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } } internal static class CodeStyleOptionGroups { public static readonly OptionGroup Usings = new(CompilerExtensionsResources.Organize_usings, priority: 1); public static readonly OptionGroup ThisOrMe = new(CompilerExtensionsResources.this_dot_and_Me_dot_preferences, priority: 2); public static readonly OptionGroup PredefinedTypeNameUsage = new(CompilerExtensionsResources.Language_keywords_vs_BCL_types_preferences, priority: 3); public static readonly OptionGroup Parentheses = new(CompilerExtensionsResources.Parentheses_preferences, priority: 4); public static readonly OptionGroup Modifier = new(CompilerExtensionsResources.Modifier_preferences, priority: 5); public static readonly OptionGroup ExpressionLevelPreferences = new(CompilerExtensionsResources.Expression_level_preferences, priority: 6); public static readonly OptionGroup Field = new(CompilerExtensionsResources.Field_preferences, priority: 7); public static readonly OptionGroup Parameter = new(CompilerExtensionsResources.Parameter_preferences, priority: 8); public static readonly OptionGroup Suppressions = new(CompilerExtensionsResources.Suppression_preferences, priority: 9); public static readonly OptionGroup NewLinePreferences = new(CompilerExtensionsResources.New_line_preferences, priority: 10); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeStyle.CodeStyleHelpers; namespace Microsoft.CodeAnalysis.CodeStyle { internal static class CodeStyleOptions2 { private static readonly ImmutableArray<IOption2>.Builder s_allOptionsBuilder = ImmutableArray.CreateBuilder<IOption2>(); internal static ImmutableArray<IOption2> AllOptions { get; } private static PerLanguageOption2<T> CreateOption<T>( OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation) { var option = new PerLanguageOption2<T>( "CodeStyleOptions", group, name, defaultValue, ImmutableArray.Create(storageLocation)); s_allOptionsBuilder.Add(option); return option; } private static PerLanguageOption2<T> CreateOption<T>( OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation1, OptionStorageLocation2 storageLocation2) { var option = new PerLanguageOption2<T>( "CodeStyleOptions", group, name, defaultValue, ImmutableArray.Create(storageLocation1, storageLocation2)); s_allOptionsBuilder.Add(option); return option; } private static Option2<T> CreateCommonOption<T>(OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation) { var option = new Option2<T>( "CodeStyleOptions", group, name, defaultValue, ImmutableArray.Create(storageLocation)); s_allOptionsBuilder.Add(option); return option; } private static Option2<T> CreateCommonOption<T>( OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation1, OptionStorageLocation2 storageLocation2) { var option = new Option2<T>( "CodeStyleOptions", group, name, defaultValue, ImmutableArray.Create(storageLocation1, storageLocation2)); s_allOptionsBuilder.Add(option); return option; } /// <remarks> /// When user preferences are not yet set for a style, we fall back to the default value. /// One such default(s), is that the feature is turned on, so that codegen consumes it, /// but with silent enforcement, so that the user is not prompted about their usage. /// </remarks> internal static readonly CodeStyleOption2<bool> TrueWithSilentEnforcement = new(value: true, notification: NotificationOption2.Silent); internal static readonly CodeStyleOption2<bool> FalseWithSilentEnforcement = new(value: false, notification: NotificationOption2.Silent); internal static readonly CodeStyleOption2<bool> TrueWithSuggestionEnforcement = new(value: true, notification: NotificationOption2.Suggestion); internal static readonly CodeStyleOption2<bool> FalseWithSuggestionEnforcement = new(value: false, notification: NotificationOption2.Suggestion); private static PerLanguageOption2<CodeStyleOption2<bool>> CreateOption( OptionGroup group, string name, CodeStyleOption2<bool> defaultValue, string editorconfigKeyName, string roamingProfileStorageKeyName) => CreateOption( group, name, defaultValue, EditorConfigStorageLocation.ForBoolCodeStyleOption(editorconfigKeyName, defaultValue), new RoamingProfileStorageLocation(roamingProfileStorageKeyName)); private static PerLanguageOption2<CodeStyleOption2<bool>> CreateQualifyAccessOption(string optionName, string editorconfigKeyName) => CreateOption( CodeStyleOptionGroups.ThisOrMe, optionName, defaultValue: CodeStyleOption2<bool>.Default, editorconfigKeyName, $"TextEditor.%LANGUAGE%.Specific.{optionName}"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in field access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyFieldAccess = CreateQualifyAccessOption( nameof(QualifyFieldAccess), "dotnet_style_qualification_for_field"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in property access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyPropertyAccess = CreateQualifyAccessOption( nameof(QualifyPropertyAccess), "dotnet_style_qualification_for_property"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in method access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyMethodAccess = CreateQualifyAccessOption( nameof(QualifyMethodAccess), "dotnet_style_qualification_for_method"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in event access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyEventAccess = CreateQualifyAccessOption( nameof(QualifyEventAccess), "dotnet_style_qualification_for_event"); /// <summary> /// This option says if we should prefer keyword for Intrinsic Predefined Types in Declarations /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIntrinsicPredefinedTypeKeywordInDeclaration = CreateOption( CodeStyleOptionGroups.PredefinedTypeNameUsage, nameof(PreferIntrinsicPredefinedTypeKeywordInDeclaration), defaultValue: TrueWithSilentEnforcement, "dotnet_style_predefined_type_for_locals_parameters_members", "TextEditor.%LANGUAGE%.Specific.PreferIntrinsicPredefinedTypeKeywordInDeclaration.CodeStyle"); /// <summary> /// This option says if we should prefer keyword for Intrinsic Predefined Types in Member Access Expression /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIntrinsicPredefinedTypeKeywordInMemberAccess = CreateOption( CodeStyleOptionGroups.PredefinedTypeNameUsage, nameof(PreferIntrinsicPredefinedTypeKeywordInMemberAccess), defaultValue: TrueWithSilentEnforcement, "dotnet_style_predefined_type_for_member_access", "TextEditor.%LANGUAGE%.Specific.PreferIntrinsicPredefinedTypeKeywordInMemberAccess.CodeStyle"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferObjectInitializer = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferObjectInitializer), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_object_initializer", "TextEditor.%LANGUAGE%.Specific.PreferObjectInitializer"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCollectionInitializer = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCollectionInitializer), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_collection_initializer", "TextEditor.%LANGUAGE%.Specific.PreferCollectionInitializer"); // TODO: Should both the below "_FadeOutCode" options be added to AllOptions? internal static readonly PerLanguageOption2<bool> PreferObjectInitializer_FadeOutCode = new( "CodeStyleOptions", nameof(PreferObjectInitializer_FadeOutCode), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferObjectInitializer_FadeOutCode")); internal static readonly PerLanguageOption2<bool> PreferCollectionInitializer_FadeOutCode = new( "CodeStyleOptions", nameof(PreferCollectionInitializer_FadeOutCode), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferCollectionInitializer_FadeOutCode")); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSimplifiedBooleanExpressions = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimplifiedBooleanExpressions), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_simplified_boolean_expressions", "TextEditor.%LANGUAGE%.Specific.PreferSimplifiedBooleanExpressions"); internal static readonly PerLanguageOption2<OperatorPlacementWhenWrappingPreference> OperatorPlacementWhenWrapping = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(OperatorPlacementWhenWrapping), defaultValue: OperatorPlacementWhenWrappingPreference.BeginningOfLine, new EditorConfigStorageLocation<OperatorPlacementWhenWrappingPreference>( "dotnet_style_operator_placement_when_wrapping", OperatorPlacementUtilities.Parse, OperatorPlacementUtilities.GetEditorConfigString)); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCoalesceExpression = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCoalesceExpression), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_coalesce_expression", "TextEditor.%LANGUAGE%.Specific.PreferCoalesceExpression"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferNullPropagation = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferNullPropagation), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_null_propagation", "TextEditor.%LANGUAGE%.Specific.PreferNullPropagation"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferExplicitTupleNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferExplicitTupleNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_explicit_tuple_names", "TextEditor.%LANGUAGE%.Specific.PreferExplicitTupleNames"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferAutoProperties = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferAutoProperties), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_auto_properties", "TextEditor.%LANGUAGE%.Specific.PreferAutoProperties"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferInferredTupleNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInferredTupleNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_inferred_tuple_names", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferInferredTupleNames)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferInferredAnonymousTypeMemberNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInferredAnonymousTypeMemberNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_inferred_anonymous_type_member_names", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferInferredAnonymousTypeMemberNames)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIsNullCheckOverReferenceEqualityMethod = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferIsNullCheckOverReferenceEqualityMethod), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_is_null_check_over_reference_equality_method", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferIsNullCheckOverReferenceEqualityMethod)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferConditionalExpressionOverAssignment = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferConditionalExpressionOverAssignment), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_conditional_expression_over_assignment", "TextEditor.%LANGUAGE%.Specific.PreferConditionalExpressionOverAssignment"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferConditionalExpressionOverReturn = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferConditionalExpressionOverReturn), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_conditional_expression_over_return", "TextEditor.%LANGUAGE%.Specific.PreferConditionalExpressionOverReturn"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCompoundAssignment = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCompoundAssignment), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_compound_assignment", "TextEditor.%LANGUAGE%.Specific.PreferCompoundAssignment"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSimplifiedInterpolation = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimplifiedInterpolation), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_simplified_interpolation", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferSimplifiedInterpolation)}"); private static readonly CodeStyleOption2<UnusedParametersPreference> s_preferAllMethodsUnusedParametersPreference = new(UnusedParametersPreference.AllMethods, NotificationOption2.Suggestion); // TODO: https://github.com/dotnet/roslyn/issues/31225 tracks adding CodeQualityOption<T> and CodeQualityOptions // and moving this option to CodeQualityOptions. internal static readonly PerLanguageOption2<CodeStyleOption2<UnusedParametersPreference>> UnusedParameters = CreateOption( CodeStyleOptionGroups.Parameter, nameof(UnusedParameters), defaultValue: s_preferAllMethodsUnusedParametersPreference, new EditorConfigStorageLocation<CodeStyleOption2<UnusedParametersPreference>>( "dotnet_code_quality_unused_parameters", s => ParseUnusedParametersPreference(s, s_preferAllMethodsUnusedParametersPreference), o => GetUnusedParametersPreferenceEditorConfigString(o, s_preferAllMethodsUnusedParametersPreference)), new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(UnusedParameters)}Preference")); private static readonly CodeStyleOption2<AccessibilityModifiersRequired> s_requireAccessibilityModifiersDefault = new(AccessibilityModifiersRequired.ForNonInterfaceMembers, NotificationOption2.Silent); internal static readonly PerLanguageOption2<CodeStyleOption2<AccessibilityModifiersRequired>> RequireAccessibilityModifiers = CreateOption( CodeStyleOptionGroups.Modifier, nameof(RequireAccessibilityModifiers), defaultValue: s_requireAccessibilityModifiersDefault, new EditorConfigStorageLocation<CodeStyleOption2<AccessibilityModifiersRequired>>( "dotnet_style_require_accessibility_modifiers", s => ParseAccessibilityModifiersRequired(s, s_requireAccessibilityModifiersDefault), v => GetAccessibilityModifiersRequiredEditorConfigString(v, s_requireAccessibilityModifiersDefault)), new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.RequireAccessibilityModifiers")); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferReadonly = CreateOption( CodeStyleOptionGroups.Field, nameof(PreferReadonly), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_readonly_field", "TextEditor.%LANGUAGE%.Specific.PreferReadonly"); internal static readonly Option2<string> FileHeaderTemplate = CreateCommonOption( CodeStyleOptionGroups.Usings, nameof(FileHeaderTemplate), defaultValue: "", EditorConfigStorageLocation.ForStringOption("file_header_template", emptyStringRepresentation: "unset")); internal static readonly Option2<string> RemoveUnnecessarySuppressionExclusions = CreateCommonOption( CodeStyleOptionGroups.Suppressions, nameof(RemoveUnnecessarySuppressionExclusions), defaultValue: "", EditorConfigStorageLocation.ForStringOption("dotnet_remove_unnecessary_suppression_exclusions", emptyStringRepresentation: "none"), new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.RemoveUnnecessarySuppressionExclusions")); private static readonly BidirectionalMap<string, AccessibilityModifiersRequired> s_accessibilityModifiersRequiredMap = new(new[] { KeyValuePairUtil.Create("never", AccessibilityModifiersRequired.Never), KeyValuePairUtil.Create("always", AccessibilityModifiersRequired.Always), KeyValuePairUtil.Create("for_non_interface_members", AccessibilityModifiersRequired.ForNonInterfaceMembers), KeyValuePairUtil.Create("omit_if_default", AccessibilityModifiersRequired.OmitIfDefault), }); private static CodeStyleOption2<AccessibilityModifiersRequired> ParseAccessibilityModifiersRequired(string optionString, CodeStyleOption2<AccessibilityModifiersRequired> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notificationOpt)) { Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsKey(value)); return new CodeStyleOption2<AccessibilityModifiersRequired>(s_accessibilityModifiersRequiredMap.GetValueOrDefault(value), notificationOpt); } return s_requireAccessibilityModifiersDefault; } private static string GetAccessibilityModifiersRequiredEditorConfigString(CodeStyleOption2<AccessibilityModifiersRequired> option, CodeStyleOption2<AccessibilityModifiersRequired> defaultValue) { // If they provide 'never', they don't need a notification level. if (option.Notification == null) { Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsValue(AccessibilityModifiersRequired.Never)); return s_accessibilityModifiersRequiredMap.GetKeyOrDefault(AccessibilityModifiersRequired.Never)!; } Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsValue(option.Value)); return $"{s_accessibilityModifiersRequiredMap.GetKeyOrDefault(option.Value)}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } private static readonly CodeStyleOption2<ParenthesesPreference> s_alwaysForClarityPreference = new(ParenthesesPreference.AlwaysForClarity, NotificationOption2.Silent); private static readonly CodeStyleOption2<ParenthesesPreference> s_neverIfUnnecessaryPreference = new(ParenthesesPreference.NeverIfUnnecessary, NotificationOption2.Silent); private static PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> CreateParenthesesOption( string fieldName, CodeStyleOption2<ParenthesesPreference> defaultValue, string styleName) { return CreateOption( CodeStyleOptionGroups.Parentheses, fieldName, defaultValue, new EditorConfigStorageLocation<CodeStyleOption2<ParenthesesPreference>>( styleName, s => ParseParenthesesPreference(s, defaultValue), v => GetParenthesesPreferenceEditorConfigString(v, defaultValue)), new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{fieldName}Preference")); } internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> ArithmeticBinaryParentheses = CreateParenthesesOption( nameof(ArithmeticBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_arithmetic_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> OtherBinaryParentheses = CreateParenthesesOption( nameof(OtherBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_other_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> RelationalBinaryParentheses = CreateParenthesesOption( nameof(RelationalBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_relational_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> OtherParentheses = CreateParenthesesOption( nameof(OtherParentheses), s_neverIfUnnecessaryPreference, "dotnet_style_parentheses_in_other_operators"); private static readonly BidirectionalMap<string, ParenthesesPreference> s_parenthesesPreferenceMap = new(new[] { KeyValuePairUtil.Create("always_for_clarity", ParenthesesPreference.AlwaysForClarity), KeyValuePairUtil.Create("never_if_unnecessary", ParenthesesPreference.NeverIfUnnecessary), }); private static readonly BidirectionalMap<string, UnusedParametersPreference> s_unusedParametersPreferenceMap = new(new[] { KeyValuePairUtil.Create("non_public", UnusedParametersPreference.NonPublicMethods), KeyValuePairUtil.Create("all", UnusedParametersPreference.AllMethods), }); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSystemHashCode = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSystemHashCode), defaultValue: TrueWithSuggestionEnforcement, new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferSystemHashCode")); public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferNamespaceAndFolderMatchStructure = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferNamespaceAndFolderMatchStructure), defaultValue: TrueWithSuggestionEnforcement, editorconfigKeyName: "dotnet_style_namespace_match_folder", roamingProfileStorageKeyName: $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferNamespaceAndFolderMatchStructure)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> AllowMultipleBlankLines = CreateOption( CodeStyleOptionGroups.NewLinePreferences, nameof(AllowMultipleBlankLines), defaultValue: TrueWithSilentEnforcement, "dotnet_style_allow_multiple_blank_lines_experimental", "TextEditor.%LANGUAGE%.Specific.AllowMultipleBlankLines"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> AllowStatementImmediatelyAfterBlock = CreateOption( CodeStyleOptionGroups.NewLinePreferences, nameof(AllowStatementImmediatelyAfterBlock), defaultValue: TrueWithSilentEnforcement, "dotnet_style_allow_statement_immediately_after_block_experimental", "TextEditor.%LANGUAGE%.Specific.AllowStatementImmediatelyAfterBlock"); static CodeStyleOptions2() { // Note that the static constructor executes after all the static field initializers for the options have executed, // and each field initializer adds the created option to s_allOptionsBuilder. AllOptions = s_allOptionsBuilder.ToImmutable(); } private static CodeStyleOption2<ParenthesesPreference> ParseParenthesesPreference( string optionString, CodeStyleOption2<ParenthesesPreference> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notification)) { Debug.Assert(s_parenthesesPreferenceMap.ContainsKey(value)); return new CodeStyleOption2<ParenthesesPreference>(s_parenthesesPreferenceMap.GetValueOrDefault(value), notification); } return defaultValue; } private static string GetParenthesesPreferenceEditorConfigString(CodeStyleOption2<ParenthesesPreference> option, CodeStyleOption2<ParenthesesPreference> defaultValue) { Debug.Assert(s_parenthesesPreferenceMap.ContainsValue(option.Value)); var value = s_parenthesesPreferenceMap.GetKeyOrDefault(option.Value) ?? s_parenthesesPreferenceMap.GetKeyOrDefault(ParenthesesPreference.AlwaysForClarity); return option.Notification == null ? value! : $"{value}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } private static CodeStyleOption2<UnusedParametersPreference> ParseUnusedParametersPreference(string optionString, CodeStyleOption2<UnusedParametersPreference> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notification)) { return new CodeStyleOption2<UnusedParametersPreference>(s_unusedParametersPreferenceMap.GetValueOrDefault(value), notification); } return defaultValue; } private static string GetUnusedParametersPreferenceEditorConfigString(CodeStyleOption2<UnusedParametersPreference> option, CodeStyleOption2<UnusedParametersPreference> defaultValue) { Debug.Assert(s_unusedParametersPreferenceMap.ContainsValue(option.Value)); var value = s_unusedParametersPreferenceMap.GetKeyOrDefault(option.Value) ?? s_unusedParametersPreferenceMap.GetKeyOrDefault(defaultValue.Value); return option.Notification == null ? value! : $"{value}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } } internal static class CodeStyleOptionGroups { public static readonly OptionGroup Usings = new(CompilerExtensionsResources.Organize_usings, priority: 1); public static readonly OptionGroup ThisOrMe = new(CompilerExtensionsResources.this_dot_and_Me_dot_preferences, priority: 2); public static readonly OptionGroup PredefinedTypeNameUsage = new(CompilerExtensionsResources.Language_keywords_vs_BCL_types_preferences, priority: 3); public static readonly OptionGroup Parentheses = new(CompilerExtensionsResources.Parentheses_preferences, priority: 4); public static readonly OptionGroup Modifier = new(CompilerExtensionsResources.Modifier_preferences, priority: 5); public static readonly OptionGroup ExpressionLevelPreferences = new(CompilerExtensionsResources.Expression_level_preferences, priority: 6); public static readonly OptionGroup Field = new(CompilerExtensionsResources.Field_preferences, priority: 7); public static readonly OptionGroup Parameter = new(CompilerExtensionsResources.Parameter_preferences, priority: 8); public static readonly OptionGroup Suppressions = new(CompilerExtensionsResources.Suppression_preferences, priority: 9); public static readonly OptionGroup NewLinePreferences = new(CompilerExtensionsResources.New_line_preferences, priority: 10); } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IBlockStatement_MethodBlocks.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 Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_SubMethodBlock() Dim source = <![CDATA[ Class Program Sub Method()'BIND:"Sub Method()" If 1 > 2 Then End If End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (3 statements) (OperationKind.Block, Type: null) (Syntax: 'Sub Method( ... End Sub') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_SubNewBlock() Dim source = <![CDATA[ Class Program Sub New()'BIND:"Sub New()" If 1 > 2 Then End If End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (3 statements) (OperationKind.Block, Type: null) (Syntax: 'Sub New()'B ... End Sub') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ConstructorBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_FunctionMethodBlock() Dim source = <![CDATA[ Class Program Function Method() As Boolean'BIND:"Function Method() As Boolean" If 1 > 2 Then End If Return True End Function End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (5 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: 'Function Me ... nd Function') Locals: Local_1: Method As System.Boolean IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'Function Me ... As Boolean') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Function Me ... As Boolean') Declarators: IVariableDeclaratorOperation (Symbol: Method As System.Boolean) (OperationKind.VariableDeclarator, Type: null, IsImplicit) (Syntax: 'Function Me ... As Boolean') Initializer: null Initializer: null IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'Return True') ReturnedValue: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True') ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Function') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Function') ReturnedValue: ILocalReferenceOperation: Method (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'End Function') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_PropertyGetBlock() Dim source = <![CDATA[ Class Program ReadOnly Property Prop As Integer Get'BIND:"Get" If 1 > 2 Then End If End Get End Property End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (4 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: 'Get'BIND:"G ... End Get') Locals: Local_1: Prop As System.Int32 IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'Get') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Get') Declarators: IVariableDeclaratorOperation (Symbol: Prop As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsImplicit) (Syntax: 'Get') Initializer: null Initializer: null IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Get') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Get') ReturnedValue: ILocalReferenceOperation: Prop (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'End Get') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42355: Property 'Prop' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Get ~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AccessorBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_PropertySetBlock() Dim source = <![CDATA[ Class Program WriteOnly Property Prop As Integer Set(Value As Integer)'BIND:"Set(Value As Integer)" If 1 > 2 Then End If End Set End Property End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (3 statements) (OperationKind.Block, Type: null) (Syntax: 'Set(Value A ... End Set') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Set') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Set') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AccessorBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_CustomEventAddBlock() Dim source = <![CDATA[ Imports System Class C Public Custom Event A As Action AddHandler(value As Action)'BIND:"AddHandler(value As Action)" If 1 > 2 Then End If End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (3 statements) (OperationKind.Block, Type: null) (Syntax: 'AddHandler( ... AddHandler') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End AddHandler') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End AddHandler') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AccessorBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_CustomEventRemoveBlock() Dim source = <![CDATA[ Imports System Class C Public Custom Event A As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Action)'BIND:"RemoveHandler(value As Action)" If 1 > 2 Then End If End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (3 statements) (OperationKind.Block, Type: null) (Syntax: 'RemoveHandl ... moveHandler') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End RemoveHandler') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End RemoveHandler') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AccessorBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_CustomEventRaiseBlock() Dim source = <![CDATA[ Imports System Class C Public Custom Event A As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent()'BIND:"RaiseEvent()" If 1 > 2 Then End If End RaiseEvent End Event End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (3 statements) (OperationKind.Block, Type: null) (Syntax: 'RaiseEvent( ... RaiseEvent') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End RaiseEvent') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End RaiseEvent') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AccessorBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_OperatorBlock() Dim source = <![CDATA[ Class Program Public Shared Operator +(p As Program, i As Integer) As Integer'BIND:"Public Shared Operator +(p As Program, i As Integer) As Integer" If 1 > 2 Then End If Return 0 End Operator End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (5 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: 'Public Shar ... nd Operator') Locals: Local_1: <anonymous local> As System.Int32 IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'Public Shar ... As Integer') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Public Shar ... As Integer') Declarators: IVariableDeclaratorOperation (Symbol: <anonymous local> As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsImplicit) (Syntax: 'Public Shar ... As Integer') Initializer: null Initializer: null IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'Return 0') ReturnedValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Operator') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Operator') ReturnedValue: ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'End Operator') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of OperatorBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_MustOverrideSubMethodStatement() Dim source = " MustInherit Class Program Public MustOverride Sub Method'BIND:""Public MustOverride Sub Method"" End Class" VerifyNoOperationTreeForTest(Of MethodStatementSyntax)(source) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_InterfaceSub() Dim source = " Interface IProgram Sub Method'BIND:""Sub Method"" End Interface" VerifyNoOperationTreeForTest(Of MethodStatementSyntax)(source) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_InterfaceFunction() Dim source = " Interface IProgram Function Method() As Boolean'BIND:""Function Method() As Boolean"" End Interface" VerifyNoOperationTreeForTest(Of MethodStatementSyntax)(source) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_NormalEvent() Dim source = " Class Program Public Event A As System.Action'BIND:""Public Event A As System.Action"" End Class" VerifyNoOperationTreeForTest(Of EventStatementSyntax)(source) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_SubMethodBlock() Dim source = <![CDATA[ Class Program Sub Method()'BIND:"Sub Method()" If 1 > 2 Then End If End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (3 statements) (OperationKind.Block, Type: null) (Syntax: 'Sub Method( ... End Sub') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_SubNewBlock() Dim source = <![CDATA[ Class Program Sub New()'BIND:"Sub New()" If 1 > 2 Then End If End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (3 statements) (OperationKind.Block, Type: null) (Syntax: 'Sub New()'B ... End Sub') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ConstructorBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_FunctionMethodBlock() Dim source = <![CDATA[ Class Program Function Method() As Boolean'BIND:"Function Method() As Boolean" If 1 > 2 Then End If Return True End Function End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (5 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: 'Function Me ... nd Function') Locals: Local_1: Method As System.Boolean IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'Function Me ... As Boolean') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Function Me ... As Boolean') Declarators: IVariableDeclaratorOperation (Symbol: Method As System.Boolean) (OperationKind.VariableDeclarator, Type: null, IsImplicit) (Syntax: 'Function Me ... As Boolean') Initializer: null Initializer: null IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'Return True') ReturnedValue: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True') ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Function') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Function') ReturnedValue: ILocalReferenceOperation: Method (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'End Function') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_PropertyGetBlock() Dim source = <![CDATA[ Class Program ReadOnly Property Prop As Integer Get'BIND:"Get" If 1 > 2 Then End If End Get End Property End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (4 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: 'Get'BIND:"G ... End Get') Locals: Local_1: Prop As System.Int32 IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'Get') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Get') Declarators: IVariableDeclaratorOperation (Symbol: Prop As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsImplicit) (Syntax: 'Get') Initializer: null Initializer: null IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Get') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Get') ReturnedValue: ILocalReferenceOperation: Prop (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'End Get') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42355: Property 'Prop' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Get ~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AccessorBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_PropertySetBlock() Dim source = <![CDATA[ Class Program WriteOnly Property Prop As Integer Set(Value As Integer)'BIND:"Set(Value As Integer)" If 1 > 2 Then End If End Set End Property End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (3 statements) (OperationKind.Block, Type: null) (Syntax: 'Set(Value A ... End Set') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Set') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Set') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AccessorBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_CustomEventAddBlock() Dim source = <![CDATA[ Imports System Class C Public Custom Event A As Action AddHandler(value As Action)'BIND:"AddHandler(value As Action)" If 1 > 2 Then End If End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (3 statements) (OperationKind.Block, Type: null) (Syntax: 'AddHandler( ... AddHandler') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End AddHandler') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End AddHandler') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AccessorBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_CustomEventRemoveBlock() Dim source = <![CDATA[ Imports System Class C Public Custom Event A As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Action)'BIND:"RemoveHandler(value As Action)" If 1 > 2 Then End If End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (3 statements) (OperationKind.Block, Type: null) (Syntax: 'RemoveHandl ... moveHandler') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End RemoveHandler') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End RemoveHandler') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AccessorBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_CustomEventRaiseBlock() Dim source = <![CDATA[ Imports System Class C Public Custom Event A As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent()'BIND:"RaiseEvent()" If 1 > 2 Then End If End RaiseEvent End Event End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (3 statements) (OperationKind.Block, Type: null) (Syntax: 'RaiseEvent( ... RaiseEvent') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End RaiseEvent') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End RaiseEvent') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AccessorBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_OperatorBlock() Dim source = <![CDATA[ Class Program Public Shared Operator +(p As Program, i As Integer) As Integer'BIND:"Public Shared Operator +(p As Program, i As Integer) As Integer" If 1 > 2 Then End If Return 0 End Operator End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (5 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: 'Public Shar ... nd Operator') Locals: Local_1: <anonymous local> As System.Int32 IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'Public Shar ... As Integer') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Public Shar ... As Integer') Declarators: IVariableDeclaratorOperation (Symbol: <anonymous local> As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsImplicit) (Syntax: 'Public Shar ... As Integer') Initializer: null Initializer: null IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If 1 > 2 Th ... End If') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean, Constant: False) (Syntax: '1 > 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If 1 > 2 Th ... End If') WhenFalse: null IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'Return 0') ReturnedValue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Operator') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Operator') ReturnedValue: ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'End Operator') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of OperatorBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_MustOverrideSubMethodStatement() Dim source = " MustInherit Class Program Public MustOverride Sub Method'BIND:""Public MustOverride Sub Method"" End Class" VerifyNoOperationTreeForTest(Of MethodStatementSyntax)(source) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_InterfaceSub() Dim source = " Interface IProgram Sub Method'BIND:""Sub Method"" End Interface" VerifyNoOperationTreeForTest(Of MethodStatementSyntax)(source) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_InterfaceFunction() Dim source = " Interface IProgram Function Method() As Boolean'BIND:""Function Method() As Boolean"" End Interface" VerifyNoOperationTreeForTest(Of MethodStatementSyntax)(source) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IBlockStatement_NormalEvent() Dim source = " Class Program Public Event A As System.Action'BIND:""Public Event A As System.Action"" End Class" VerifyNoOperationTreeForTest(Of EventStatementSyntax)(source) End Sub End Class End Namespace
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/Test/Resources/Core/DiagnosticTests/ErrTestLib01.dll
MZ@ !L!This program cannot be run in DOS mode. $PEL[L! ~# @@ @,#O@`  H.text  `.rsrc@@@.reloc ` @B`#Ht  *( *( *( *( *BSJB v4.0.30319l@#~#Stringsd#USl#GUID|<#BlobG %3 81lLL "$P A S F [ F c F k F FF F . .( ?<Module>ErrTestLib01.dllANSBCD`1mscorlibSystemObjectTTest.ctorSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeErrTestLib01 7՟H=F| z\V4  TWrapNonExceptionThrowsT#n# `#_CorDllMainmscoree.dll% @0HX@\\4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0DInternalNameErrTestLib01.dll(LegalCopyright LOriginalFilenameErrTestLib01.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 3
MZ@ !L!This program cannot be run in DOS mode. $PEL[L! ~# @@ @,#O@`  H.text  `.rsrc@@@.reloc ` @B`#Ht  *( *( *( *( *BSJB v4.0.30319l@#~#Stringsd#USl#GUID|<#BlobG %3 81lLL "$P A S F [ F c F k F FF F . .( ?<Module>ErrTestLib01.dllANSBCD`1mscorlibSystemObjectTTest.ctorSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeErrTestLib01 7՟H=F| z\V4  TWrapNonExceptionThrowsT#n# `#_CorDllMainmscoree.dll% @0HX@\\4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0DInternalNameErrTestLib01.dll(LegalCopyright LOriginalFilenameErrTestLib01.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 3
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Analyzers/CSharp/Tests/UseExplicitTupleName/UseExplicitTupleNameTests.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.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UseExplicitTupleName; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExplicitTupleName { public class UseExplicitTupleNameTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseExplicitTupleNameTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new UseExplicitTupleNameDiagnosticAnalyzer(), new UseExplicitTupleNameCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestNamedTuple1() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }", @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.i; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestInArgument() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); Goo(v1.[|Item1|]); } void Goo(int i) { } }", @" class C { void M() { (int i, string s) v1 = default((int, string)); Goo(v1.i); } void Goo(int i) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestNamedTuple2() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.[|Item2|]; } }", @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestMissingOnMatchingName1() { await TestMissingInRegularAndScriptAsync( @" class C { void M() { (int, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestMissingOnMatchingName2() { await TestMissingInRegularAndScriptAsync( @" class C { void M() { (int Item1, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestWrongCasing() { await TestInRegularAndScriptAsync( @" class C { void M() { (int item1, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }", @" class C { void M() { (int item1, string s) v1 = default((int, string)); var v2 = v1.item1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestFixAll1() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.{|FixAllInDocument:Item1|}; var v3 = v1.Item2; } }", @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.i; var v3 = v1.s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestFixAll2() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, int s) v1 = default((int, int)); v1.{|FixAllInDocument:Item1|} = v1.Item2; } }", @" class C { void M() { (int i, int s) v1 = default((int, int)); v1.i = v1.s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestFalseOptionImplicitTuple() { await TestDiagnosticMissingAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferExplicitTupleNames, false, NotificationOption2.Warning))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestFalseOptionExplicitTuple() { await TestDiagnosticMissingAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.[|i|]; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferExplicitTupleNames, false, NotificationOption2.Warning))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestOnRestField() { var valueTuple8 = @" namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { } } public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> where TRest : struct { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public TRest Rest; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { } } } "; await TestDiagnosticMissingAsync( @" class C { void M() { (int, int, int, int, int, int, int, int) x = default; _ = x.[|Rest|]; } }" + valueTuple8); } } }
// Licensed to the .NET Foundation under one or more 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.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UseExplicitTupleName; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExplicitTupleName { public class UseExplicitTupleNameTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseExplicitTupleNameTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new UseExplicitTupleNameDiagnosticAnalyzer(), new UseExplicitTupleNameCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestNamedTuple1() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }", @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.i; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestInArgument() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); Goo(v1.[|Item1|]); } void Goo(int i) { } }", @" class C { void M() { (int i, string s) v1 = default((int, string)); Goo(v1.i); } void Goo(int i) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestNamedTuple2() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.[|Item2|]; } }", @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestMissingOnMatchingName1() { await TestMissingInRegularAndScriptAsync( @" class C { void M() { (int, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestMissingOnMatchingName2() { await TestMissingInRegularAndScriptAsync( @" class C { void M() { (int Item1, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestWrongCasing() { await TestInRegularAndScriptAsync( @" class C { void M() { (int item1, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }", @" class C { void M() { (int item1, string s) v1 = default((int, string)); var v2 = v1.item1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestFixAll1() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.{|FixAllInDocument:Item1|}; var v3 = v1.Item2; } }", @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.i; var v3 = v1.s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestFixAll2() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, int s) v1 = default((int, int)); v1.{|FixAllInDocument:Item1|} = v1.Item2; } }", @" class C { void M() { (int i, int s) v1 = default((int, int)); v1.i = v1.s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestFalseOptionImplicitTuple() { await TestDiagnosticMissingAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferExplicitTupleNames, false, NotificationOption2.Warning))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestFalseOptionExplicitTuple() { await TestDiagnosticMissingAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.[|i|]; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferExplicitTupleNames, false, NotificationOption2.Warning))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestOnRestField() { var valueTuple8 = @" namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { } } public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> where TRest : struct { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public TRest Rest; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { } } } "; await TestDiagnosticMissingAsync( @" class C { void M() { (int, int, int, int, int, int, int, int) x = default; _ = x.[|Rest|]; } }" + valueTuple8); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.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="../CodeStyleResources.resx"> <body> <trans-unit id="A_language_name_cannot_be_specified_for_this_option"> <source>A language name cannot be specified for this option.</source> <target state="translated">無法指定此選項的語言名稱。</target> <note /> </trans-unit> <trans-unit id="A_language_name_must_be_specified_for_this_option"> <source>A language name must be specified for this option.</source> <target state="translated">必須指定此選項的語言名稱。</target> <note /> </trans-unit> <trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized"> <source>Arrays with more than one dimension cannot be serialized.</source> <target state="translated">無法序列化包含多個維度的陣列。</target> <note /> </trans-unit> <trans-unit id="Cannot_serialize_type_0"> <source>Cannot serialize type '{0}'.</source> <target state="translated">無法將類型 '{0}' 序列化。</target> <note /> </trans-unit> <trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values"> <source>Deserialization reader for '{0}' read incorrect number of values.</source> <target state="translated">'{0}' 的還原序列化讀取器所讀取的值數目不正確。</target> <note /> </trans-unit> <trans-unit id="Error"> <source>Error</source> <target state="translated">錯誤</target> <note /> </trans-unit> <trans-unit id="Fix_formatting"> <source>Fix formatting</source> <target state="translated">修正格式化</target> <note /> </trans-unit> <trans-unit id="Indentation_and_spacing"> <source>Indentation and spacing</source> <target state="translated">縮排和間距</target> <note /> </trans-unit> <trans-unit id="New_line_preferences"> <source>New line preferences</source> <target state="translated">新行喜好設定</target> <note /> </trans-unit> <trans-unit id="None"> <source>None</source> <target state="translated">無</target> <note /> </trans-unit> <trans-unit id="Refactoring_Only"> <source>Refactoring Only</source> <target state="translated">僅重構</target> <note /> </trans-unit> <trans-unit id="Stream_is_too_long"> <source>Stream is too long.</source> <target state="translated">資料流過長。</target> <note /> </trans-unit> <trans-unit id="Suggestion"> <source>Suggestion</source> <target state="translated">建議</target> <note /> </trans-unit> <trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder"> <source>The type '{0}' is not understood by the serialization binder.</source> <target state="translated">序列化繫結器無法辨識類型 '{0}'。</target> <note /> </trans-unit> <trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer"> <source>Value too large to be represented as a 30 bit unsigned integer.</source> <target state="translated">值太大,無法呈現為 30 位元不帶正負號的整數。</target> <note /> </trans-unit> <trans-unit id="Warning"> <source>Warning</source> <target state="translated">警告</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../CodeStyleResources.resx"> <body> <trans-unit id="A_language_name_cannot_be_specified_for_this_option"> <source>A language name cannot be specified for this option.</source> <target state="translated">無法指定此選項的語言名稱。</target> <note /> </trans-unit> <trans-unit id="A_language_name_must_be_specified_for_this_option"> <source>A language name must be specified for this option.</source> <target state="translated">必須指定此選項的語言名稱。</target> <note /> </trans-unit> <trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized"> <source>Arrays with more than one dimension cannot be serialized.</source> <target state="translated">無法序列化包含多個維度的陣列。</target> <note /> </trans-unit> <trans-unit id="Cannot_serialize_type_0"> <source>Cannot serialize type '{0}'.</source> <target state="translated">無法將類型 '{0}' 序列化。</target> <note /> </trans-unit> <trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values"> <source>Deserialization reader for '{0}' read incorrect number of values.</source> <target state="translated">'{0}' 的還原序列化讀取器所讀取的值數目不正確。</target> <note /> </trans-unit> <trans-unit id="Error"> <source>Error</source> <target state="translated">錯誤</target> <note /> </trans-unit> <trans-unit id="Fix_formatting"> <source>Fix formatting</source> <target state="translated">修正格式化</target> <note /> </trans-unit> <trans-unit id="Indentation_and_spacing"> <source>Indentation and spacing</source> <target state="translated">縮排和間距</target> <note /> </trans-unit> <trans-unit id="New_line_preferences"> <source>New line preferences</source> <target state="translated">新行喜好設定</target> <note /> </trans-unit> <trans-unit id="None"> <source>None</source> <target state="translated">無</target> <note /> </trans-unit> <trans-unit id="Refactoring_Only"> <source>Refactoring Only</source> <target state="translated">僅重構</target> <note /> </trans-unit> <trans-unit id="Stream_is_too_long"> <source>Stream is too long.</source> <target state="translated">資料流過長。</target> <note /> </trans-unit> <trans-unit id="Suggestion"> <source>Suggestion</source> <target state="translated">建議</target> <note /> </trans-unit> <trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder"> <source>The type '{0}' is not understood by the serialization binder.</source> <target state="translated">序列化繫結器無法辨識類型 '{0}'。</target> <note /> </trans-unit> <trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer"> <source>Value too large to be represented as a 30 bit unsigned integer.</source> <target state="translated">值太大,無法呈現為 30 位元不帶正負號的整數。</target> <note /> </trans-unit> <trans-unit id="Warning"> <source>Warning</source> <target state="translated">警告</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Workspaces/Core/Portable/Options/IGlobalOptionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Provides services for reading and writing options. /// This will provide support for options at the global level (i.e. shared among /// all workspaces/services). /// /// In general you should not import this type directly, and should instead get an /// <see cref="IOptionService"/> from <see cref="Workspace.Services"/> /// </summary> internal interface IGlobalOptionService { /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(Option<T> option); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(Option2<T> option); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(PerLanguageOption<T> option, string? languageName); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(PerLanguageOption2<T> option, string? languageName); /// <summary> /// Gets the current value of the specific option. /// </summary> object? GetOption(OptionKey optionKey); /// <summary> /// Applies a set of options, invoking serializers if needed. /// </summary> void SetOptions(OptionSet optionSet); /// <summary> /// Gets force computed serializable options snapshot with prefetched values for the registered options applicable to the given <paramref name="languages"/> by quering the option persisters. /// </summary> SerializableOptionSet GetSerializableOptionsSnapshot(ImmutableHashSet<string> languages, IOptionService optionService); /// <summary> /// Returns the set of all registered options. /// </summary> IEnumerable<IOption> GetRegisteredOptions(); /// <summary> /// Map an <strong>.editorconfig</strong> key to a corresponding <see cref="IEditorConfigStorageLocation2"/> and /// <see cref="OptionKey"/> that can be used to read and write the value stored in an <see cref="OptionSet"/>. /// </summary> /// <param name="key">The <strong>.editorconfig</strong> key.</param> /// <param name="language">The language to use for the <paramref name="optionKey"/>, if the matching option has /// <see cref="IOption.IsPerLanguage"/> set.</param> /// <param name="storageLocation">The <see cref="IEditorConfigStorageLocation2"/> for the key.</param> /// <param name="optionKey">The <see cref="OptionKey"/> for the key and language.</param> /// <returns><see langword="true"/> if a matching option was found; otherwise, <see langword="false"/>.</returns> bool TryMapEditorConfigKeyToOption(string key, string? language, [NotNullWhen(true)] out IEditorConfigStorageLocation2? storageLocation, out OptionKey optionKey); /// <summary> /// Returns the set of all registered serializable options applicable for the given <paramref name="languages"/>. /// </summary> ImmutableHashSet<IOption> GetRegisteredSerializableOptions(ImmutableHashSet<string> languages); event EventHandler<OptionChangedEventArgs>? OptionChanged; /// <summary> /// Refreshes the stored value of a serialized option. This should only be called from serializers. /// </summary> void RefreshOption(OptionKey optionKey, object? newValue); /// <summary> /// Registers a workspace with the option service. /// </summary> void RegisterWorkspace(Workspace workspace); /// <summary> /// Unregisters a workspace from the option service. /// </summary> void UnregisterWorkspace(Workspace workspace); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Provides services for reading and writing options. /// This will provide support for options at the global level (i.e. shared among /// all workspaces/services). /// /// In general you should not import this type directly, and should instead get an /// <see cref="IOptionService"/> from <see cref="Workspace.Services"/> /// </summary> internal interface IGlobalOptionService { /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(Option<T> option); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(Option2<T> option); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(PerLanguageOption<T> option, string? languageName); /// <summary> /// Gets the current value of the specific option. /// </summary> T? GetOption<T>(PerLanguageOption2<T> option, string? languageName); /// <summary> /// Gets the current value of the specific option. /// </summary> object? GetOption(OptionKey optionKey); /// <summary> /// Applies a set of options, invoking serializers if needed. /// </summary> void SetOptions(OptionSet optionSet); /// <summary> /// Gets force computed serializable options snapshot with prefetched values for the registered options applicable to the given <paramref name="languages"/> by quering the option persisters. /// </summary> SerializableOptionSet GetSerializableOptionsSnapshot(ImmutableHashSet<string> languages, IOptionService optionService); /// <summary> /// Returns the set of all registered options. /// </summary> IEnumerable<IOption> GetRegisteredOptions(); /// <summary> /// Map an <strong>.editorconfig</strong> key to a corresponding <see cref="IEditorConfigStorageLocation2"/> and /// <see cref="OptionKey"/> that can be used to read and write the value stored in an <see cref="OptionSet"/>. /// </summary> /// <param name="key">The <strong>.editorconfig</strong> key.</param> /// <param name="language">The language to use for the <paramref name="optionKey"/>, if the matching option has /// <see cref="IOption.IsPerLanguage"/> set.</param> /// <param name="storageLocation">The <see cref="IEditorConfigStorageLocation2"/> for the key.</param> /// <param name="optionKey">The <see cref="OptionKey"/> for the key and language.</param> /// <returns><see langword="true"/> if a matching option was found; otherwise, <see langword="false"/>.</returns> bool TryMapEditorConfigKeyToOption(string key, string? language, [NotNullWhen(true)] out IEditorConfigStorageLocation2? storageLocation, out OptionKey optionKey); /// <summary> /// Returns the set of all registered serializable options applicable for the given <paramref name="languages"/>. /// </summary> ImmutableHashSet<IOption> GetRegisteredSerializableOptions(ImmutableHashSet<string> languages); event EventHandler<OptionChangedEventArgs>? OptionChanged; /// <summary> /// Refreshes the stored value of a serialized option. This should only be called from serializers. /// </summary> void RefreshOption(OptionKey optionKey, object? newValue); /// <summary> /// Registers a workspace with the option service. /// </summary> void RegisterWorkspace(Workspace workspace); /// <summary> /// Unregisters a workspace from the option service. /// </summary> void UnregisterWorkspace(Workspace workspace); } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Features/Lsif/GeneratorTest/ProjectStructureTests.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.Text Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests <UseExportProvider> Public NotInheritable Class ProjectStructureTests <Fact> Public Async Function ProjectContainsDocuments() As Task Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#" Name="TestProject" FilePath="Z:\TestProject.csproj"> <Document Name="A.cs" FilePath="Z:\A.cs"/> <Document Name="B.cs" FilePath="Z:\B.cs"/> </Project> </Workspace>)) Dim projectVertex = Assert.Single(lsif.Vertices.OfType(Of Graph.LsifProject)) Dim documentVertices = lsif.GetLinkedVertices(Of Graph.LsifDocument)(projectVertex, "contains") Dim documentA = Assert.Single(documentVertices, Function(d) d.Uri.LocalPath = "Z:\A.cs") Dim documentB = Assert.Single(documentVertices, Function(d) d.Uri.LocalPath = "Z:\B.cs") ' We don't include contents for normal files, just generated ones Assert.Null(documentA.Contents) Assert.Null(documentB.Contents) End Function <Fact> Public Async Function SourceGeneratedDocumentsIncludeContent() As Task Dim workspace = TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#" Name="TestProject" FilePath="Z:\TestProject.csproj" CommonReferences="true"> </Project> </Workspace>) workspace.OnAnalyzerReferenceAdded(workspace.CurrentSolution.ProjectIds.Single(), New TestGeneratorReference(New TestSourceGenerator.HelloWorldGenerator())) Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync(workspace) Dim projectVertex = Assert.Single(lsif.Vertices.OfType(Of Graph.LsifProject)) Dim generatedDocumentVertices = lsif.GetLinkedVertices(Of Graph.LsifDocument)(projectVertex, "contains") For Each generatedDocumentVertex In generatedDocumentVertices ' Assert the contents were included and does match the tree Dim contentBase64Encoded = generatedDocumentVertex.Contents Assert.NotNull(contentBase64Encoded) Dim contents = Encoding.UTF8.GetString(Convert.FromBase64String(contentBase64Encoded)) Dim compilation = Await workspace.CurrentSolution.Projects.Single().GetCompilationAsync() Dim tree = Assert.Single(compilation.SyntaxTrees, Function(t) t.FilePath = generatedDocumentVertex.Uri.OriginalString) Assert.Equal(tree.GetText().ToString(), contents) Next 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.Text Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests <UseExportProvider> Public NotInheritable Class ProjectStructureTests <Fact> Public Async Function ProjectContainsDocuments() As Task Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#" Name="TestProject" FilePath="Z:\TestProject.csproj"> <Document Name="A.cs" FilePath="Z:\A.cs"/> <Document Name="B.cs" FilePath="Z:\B.cs"/> </Project> </Workspace>)) Dim projectVertex = Assert.Single(lsif.Vertices.OfType(Of Graph.LsifProject)) Dim documentVertices = lsif.GetLinkedVertices(Of Graph.LsifDocument)(projectVertex, "contains") Dim documentA = Assert.Single(documentVertices, Function(d) d.Uri.LocalPath = "Z:\A.cs") Dim documentB = Assert.Single(documentVertices, Function(d) d.Uri.LocalPath = "Z:\B.cs") ' We don't include contents for normal files, just generated ones Assert.Null(documentA.Contents) Assert.Null(documentB.Contents) End Function <Fact> Public Async Function SourceGeneratedDocumentsIncludeContent() As Task Dim workspace = TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#" Name="TestProject" FilePath="Z:\TestProject.csproj" CommonReferences="true"> </Project> </Workspace>) workspace.OnAnalyzerReferenceAdded(workspace.CurrentSolution.ProjectIds.Single(), New TestGeneratorReference(New TestSourceGenerator.HelloWorldGenerator())) Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync(workspace) Dim projectVertex = Assert.Single(lsif.Vertices.OfType(Of Graph.LsifProject)) Dim generatedDocumentVertices = lsif.GetLinkedVertices(Of Graph.LsifDocument)(projectVertex, "contains") For Each generatedDocumentVertex In generatedDocumentVertices ' Assert the contents were included and does match the tree Dim contentBase64Encoded = generatedDocumentVertex.Contents Assert.NotNull(contentBase64Encoded) Dim contents = Encoding.UTF8.GetString(Convert.FromBase64String(contentBase64Encoded)) Dim compilation = Await workspace.CurrentSolution.Projects.Single().GetCompilationAsync() Dim tree = Assert.Single(compilation.SyntaxTrees, Function(t) t.FilePath = generatedDocumentVertex.Uri.OriginalString) Assert.Equal(tree.GetText().ToString(), contents) Next End Function End Class End Namespace
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Features/Core/Portable/EditAndContinue/ActiveStatementSpan.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents a span of an active statement tracked by the client editor. /// </summary> [DataContract] internal readonly struct ActiveStatementSpan : IEquatable<ActiveStatementSpan> { /// <summary> /// The corresponding <see cref="ActiveStatement.Ordinal"/>. /// </summary> [DataMember(Order = 0)] public readonly int Ordinal; /// <summary> /// Line span in the mapped document. /// </summary> [DataMember(Order = 1)] public readonly LinePositionSpan LineSpan; /// <summary> /// Flags. /// </summary> [DataMember(Order = 2)] public readonly ActiveStatementFlags Flags; /// <summary> /// The id of the unmapped document where the source of the active statement is and from where the statement might be mapped to <see cref="LineSpan"/> via <c>#line</c> directive. /// Null if unknown (not determined yet). /// </summary> [DataMember(Order = 3)] public readonly DocumentId? UnmappedDocumentId; public ActiveStatementSpan(int ordinal, LinePositionSpan lineSpan, ActiveStatementFlags flags, DocumentId? unmappedDocumentId) { Debug.Assert(ordinal >= 0); Ordinal = ordinal; LineSpan = lineSpan; Flags = flags; UnmappedDocumentId = unmappedDocumentId; } public override bool Equals(object? obj) => obj is ActiveStatementSpan other && Equals(other); public bool Equals(ActiveStatementSpan other) => Ordinal.Equals(other.Ordinal) && LineSpan.Equals(other.LineSpan) && Flags == other.Flags && UnmappedDocumentId == other.UnmappedDocumentId; public override int GetHashCode() => Hash.Combine(Ordinal, Hash.Combine(LineSpan.GetHashCode(), Hash.Combine(UnmappedDocumentId, (int)Flags))); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents a span of an active statement tracked by the client editor. /// </summary> [DataContract] internal readonly struct ActiveStatementSpan : IEquatable<ActiveStatementSpan> { /// <summary> /// The corresponding <see cref="ActiveStatement.Ordinal"/>. /// </summary> [DataMember(Order = 0)] public readonly int Ordinal; /// <summary> /// Line span in the mapped document. /// </summary> [DataMember(Order = 1)] public readonly LinePositionSpan LineSpan; /// <summary> /// Flags. /// </summary> [DataMember(Order = 2)] public readonly ActiveStatementFlags Flags; /// <summary> /// The id of the unmapped document where the source of the active statement is and from where the statement might be mapped to <see cref="LineSpan"/> via <c>#line</c> directive. /// Null if unknown (not determined yet). /// </summary> [DataMember(Order = 3)] public readonly DocumentId? UnmappedDocumentId; public ActiveStatementSpan(int ordinal, LinePositionSpan lineSpan, ActiveStatementFlags flags, DocumentId? unmappedDocumentId) { Debug.Assert(ordinal >= 0); Ordinal = ordinal; LineSpan = lineSpan; Flags = flags; UnmappedDocumentId = unmappedDocumentId; } public override bool Equals(object? obj) => obj is ActiveStatementSpan other && Equals(other); public bool Equals(ActiveStatementSpan other) => Ordinal.Equals(other.Ordinal) && LineSpan.Equals(other.LineSpan) && Flags == other.Flags && UnmappedDocumentId == other.UnmappedDocumentId; public override int GetHashCode() => Hash.Combine(Ordinal, Hash.Combine(LineSpan.GetHashCode(), Hash.Combine(UnmappedDocumentId, (int)Flags))); } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Features/Core/Portable/ExtractMethod/ExtractMethodMatrix.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.ErrorReporting; namespace Microsoft.CodeAnalysis.ExtractMethod { internal class ExtractMethodMatrix { private static readonly Dictionary<Key, VariableStyle> s_matrix; static ExtractMethodMatrix() { s_matrix = new Dictionary<Key, VariableStyle>(); BuildMatrix(); } public static bool TryGetVariableStyle( bool bestEffort, bool dataFlowIn, bool dataFlowOut, bool alwaysAssigned, bool variableDeclared, bool readInside, bool writtenInside, bool readOutside, bool writtenOutside, bool unsafeAddressTaken, out VariableStyle variableStyle) { // bug # 12258, 12114 // use "out" if "&" is taken for the variable if (unsafeAddressTaken) { variableStyle = VariableStyle.Out; return true; } var key = new Key( dataFlowIn, dataFlowOut, alwaysAssigned, variableDeclared, readInside, writtenInside, readOutside, writtenOutside); // special cases if (!s_matrix.ContainsKey(key)) { // Interesting case. Due to things like constant analysis there can be regions that // the compiler considers data not to flow in (because analysis proves that that // path will never be taken). However, the variable can still be read/written inside // the region. For purposes of extract method, we check for this case, and we // pretend it's as if data flowed into the region. if (!dataFlowIn && (readInside || writtenInside)) { key = new Key(true, dataFlowOut, alwaysAssigned, variableDeclared, readInside, writtenInside, readOutside, writtenOutside); } // another interesting case (bug # 10875) // basically, it can happen in malformed code where a variable is not properly assigned but used outside of the selection + unreachable code region // for such cases, treat it like "MoveOut" if (!dataFlowOut && !alwaysAssigned && variableDeclared && !writtenInside && readOutside) { key = new Key(dataFlowIn, /*dataFlowOut*/ true, alwaysAssigned, variableDeclared, readInside, writtenInside, readOutside, writtenOutside); } // interesting case in invalid code (bug #19136) // variable is passed by reference, and another argument is an out variable with the same name if (dataFlowIn && variableDeclared) { key = new Key(/*dataFlowIn:*/ false, dataFlowOut, alwaysAssigned, variableDeclared, readInside, writtenInside, readOutside, writtenOutside); } } if (s_matrix.TryGetValue(key, out variableStyle)) { return true; } if (bestEffort) { // In best effort mode, even though we didn't know precisely what to do, we still // allow the user to keep going, assuming that this variable is a very basic one. variableStyle = VariableStyle.InputOnly; return true; } // Some combination we didn't anticipate. Can't do anything here. Log the issue // and bail out. FatalError.ReportAndCatch(new Exception($"extract method encountered unknown states: {key.ToString()}")); return false; } private static void BuildMatrix() { // meaning of each boolean values (total of 69 different cases) // data flowin/data flow out/always assigned/variable declared/ read inside/written inside/read outside/written outside s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.MoveIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.SplitIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: false, readOutside: false, writtenOutside: true), VariableStyle.MoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: false, readOutside: true, writtenOutside: true), VariableStyle.MoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.None); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: false, readOutside: false, writtenOutside: false), VariableStyle.None); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: false, readOutside: false, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: false, readOutside: true, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.None); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.MoveIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.SplitIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: false, readOutside: false, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: false, readOutside: true, writtenOutside: true), VariableStyle.Ref); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.MoveIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.SplitIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: false, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.None); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: false, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.None); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.Ref); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Ref); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.Ref); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Ref); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: false, readOutside: true, writtenOutside: false), VariableStyle.NotUsed); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: false, readOutside: true, writtenOutside: true), VariableStyle.NotUsed); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: false, readOutside: true, writtenOutside: false), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: false, readOutside: true, writtenOutside: true), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.Out); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Out); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.Out); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Out); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: false, readOutside: false, writtenOutside: false), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: false, readOutside: false, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: false, readOutside: true, writtenOutside: false), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: false, readOutside: true, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Ref); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithErrorInput); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Ref); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithErrorInput); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Ref); } private readonly struct Key : IEquatable<Key> { public bool DataFlowIn { get; } public bool DataFlowOut { get; } public bool AlwaysAssigned { get; } public bool VariableDeclared { get; } public bool ReadInside { get; } public bool WrittenInside { get; } public bool ReadOutside { get; } public bool WrittenOutside { get; } public Key( bool dataFlowIn, bool dataFlowOut, bool alwaysAssigned, bool variableDeclared, bool readInside, bool writtenInside, bool readOutside, bool writtenOutside) : this() { DataFlowIn = dataFlowIn; DataFlowOut = dataFlowOut; AlwaysAssigned = alwaysAssigned; VariableDeclared = variableDeclared; ReadInside = readInside; WrittenInside = writtenInside; ReadOutside = readOutside; WrittenOutside = writtenOutside; } public bool Equals(Key key) { return DataFlowIn == key.DataFlowIn && DataFlowOut == key.DataFlowOut && AlwaysAssigned == key.AlwaysAssigned && VariableDeclared == key.VariableDeclared && ReadInside == key.ReadInside && WrittenInside == key.WrittenInside && ReadOutside == key.ReadOutside && WrittenOutside == key.WrittenOutside; } public override bool Equals(object obj) { if (obj is Key key) { return Equals(key); } return false; } public override int GetHashCode() { var hashCode = 0; hashCode = DataFlowIn ? 1 << 7 | hashCode : hashCode; hashCode = DataFlowOut ? 1 << 6 | hashCode : hashCode; hashCode = AlwaysAssigned ? 1 << 5 | hashCode : hashCode; hashCode = VariableDeclared ? 1 << 4 | hashCode : hashCode; hashCode = ReadInside ? 1 << 3 | hashCode : hashCode; hashCode = WrittenInside ? 1 << 2 | hashCode : hashCode; hashCode = ReadOutside ? 1 << 1 | hashCode : hashCode; hashCode = WrittenOutside ? 1 << 0 | hashCode : hashCode; return hashCode; } public override string ToString() => GetHashCode().ToString("X"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.ErrorReporting; namespace Microsoft.CodeAnalysis.ExtractMethod { internal class ExtractMethodMatrix { private static readonly Dictionary<Key, VariableStyle> s_matrix; static ExtractMethodMatrix() { s_matrix = new Dictionary<Key, VariableStyle>(); BuildMatrix(); } public static bool TryGetVariableStyle( bool bestEffort, bool dataFlowIn, bool dataFlowOut, bool alwaysAssigned, bool variableDeclared, bool readInside, bool writtenInside, bool readOutside, bool writtenOutside, bool unsafeAddressTaken, out VariableStyle variableStyle) { // bug # 12258, 12114 // use "out" if "&" is taken for the variable if (unsafeAddressTaken) { variableStyle = VariableStyle.Out; return true; } var key = new Key( dataFlowIn, dataFlowOut, alwaysAssigned, variableDeclared, readInside, writtenInside, readOutside, writtenOutside); // special cases if (!s_matrix.ContainsKey(key)) { // Interesting case. Due to things like constant analysis there can be regions that // the compiler considers data not to flow in (because analysis proves that that // path will never be taken). However, the variable can still be read/written inside // the region. For purposes of extract method, we check for this case, and we // pretend it's as if data flowed into the region. if (!dataFlowIn && (readInside || writtenInside)) { key = new Key(true, dataFlowOut, alwaysAssigned, variableDeclared, readInside, writtenInside, readOutside, writtenOutside); } // another interesting case (bug # 10875) // basically, it can happen in malformed code where a variable is not properly assigned but used outside of the selection + unreachable code region // for such cases, treat it like "MoveOut" if (!dataFlowOut && !alwaysAssigned && variableDeclared && !writtenInside && readOutside) { key = new Key(dataFlowIn, /*dataFlowOut*/ true, alwaysAssigned, variableDeclared, readInside, writtenInside, readOutside, writtenOutside); } // interesting case in invalid code (bug #19136) // variable is passed by reference, and another argument is an out variable with the same name if (dataFlowIn && variableDeclared) { key = new Key(/*dataFlowIn:*/ false, dataFlowOut, alwaysAssigned, variableDeclared, readInside, writtenInside, readOutside, writtenOutside); } } if (s_matrix.TryGetValue(key, out variableStyle)) { return true; } if (bestEffort) { // In best effort mode, even though we didn't know precisely what to do, we still // allow the user to keep going, assuming that this variable is a very basic one. variableStyle = VariableStyle.InputOnly; return true; } // Some combination we didn't anticipate. Can't do anything here. Log the issue // and bail out. FatalError.ReportAndCatch(new Exception($"extract method encountered unknown states: {key.ToString()}")); return false; } private static void BuildMatrix() { // meaning of each boolean values (total of 69 different cases) // data flowin/data flow out/always assigned/variable declared/ read inside/written inside/read outside/written outside s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.MoveIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.SplitIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: false, readOutside: false, writtenOutside: true), VariableStyle.MoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: false, readOutside: true, writtenOutside: true), VariableStyle.MoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.None); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: false, readOutside: false, writtenOutside: false), VariableStyle.None); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: false, readOutside: false, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: false, readOutside: true, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.None); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.MoveIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.SplitIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: false, readOutside: false, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: false, readOutside: true, writtenOutside: true), VariableStyle.Ref); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.MoveIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.SplitIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitIn); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: false, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.None); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: false, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.None); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.SplitOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.Ref); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Ref); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.Ref); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Ref); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: false, readOutside: true, writtenOutside: false), VariableStyle.NotUsed); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: false, readOutside: true, writtenOutside: true), VariableStyle.NotUsed); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: false, readOutside: true, writtenOutside: false), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: false, readOutside: true, writtenOutside: true), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: false, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.Out); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Out); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.Out); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Out); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: true, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: false, dataFlowOut: true, alwaysAssigned: true, variableDeclared: true, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.OutWithMoveOut); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: false, readOutside: false, writtenOutside: false), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: false, readOutside: false, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: false, readOutside: true, writtenOutside: false), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: false, readOutside: true, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: false), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: false, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.InputOnly); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: false, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Ref); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithErrorInput); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: true, alwaysAssigned: false, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Ref); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: false), VariableStyle.OutWithErrorInput); s_matrix.Add(new Key(dataFlowIn: true, dataFlowOut: true, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: true, readOutside: true, writtenOutside: true), VariableStyle.Ref); } private readonly struct Key : IEquatable<Key> { public bool DataFlowIn { get; } public bool DataFlowOut { get; } public bool AlwaysAssigned { get; } public bool VariableDeclared { get; } public bool ReadInside { get; } public bool WrittenInside { get; } public bool ReadOutside { get; } public bool WrittenOutside { get; } public Key( bool dataFlowIn, bool dataFlowOut, bool alwaysAssigned, bool variableDeclared, bool readInside, bool writtenInside, bool readOutside, bool writtenOutside) : this() { DataFlowIn = dataFlowIn; DataFlowOut = dataFlowOut; AlwaysAssigned = alwaysAssigned; VariableDeclared = variableDeclared; ReadInside = readInside; WrittenInside = writtenInside; ReadOutside = readOutside; WrittenOutside = writtenOutside; } public bool Equals(Key key) { return DataFlowIn == key.DataFlowIn && DataFlowOut == key.DataFlowOut && AlwaysAssigned == key.AlwaysAssigned && VariableDeclared == key.VariableDeclared && ReadInside == key.ReadInside && WrittenInside == key.WrittenInside && ReadOutside == key.ReadOutside && WrittenOutside == key.WrittenOutside; } public override bool Equals(object obj) { if (obj is Key key) { return Equals(key); } return false; } public override int GetHashCode() { var hashCode = 0; hashCode = DataFlowIn ? 1 << 7 | hashCode : hashCode; hashCode = DataFlowOut ? 1 << 6 | hashCode : hashCode; hashCode = AlwaysAssigned ? 1 << 5 | hashCode : hashCode; hashCode = VariableDeclared ? 1 << 4 | hashCode : hashCode; hashCode = ReadInside ? 1 << 3 | hashCode : hashCode; hashCode = WrittenInside ? 1 << 2 | hashCode : hashCode; hashCode = ReadOutside ? 1 << 1 | hashCode : hashCode; hashCode = WrittenOutside ? 1 << 0 | hashCode : hashCode; return hashCode; } public override string ToString() => GetHashCode().ToString("X"); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./docs/features/local-functions.md
Local Functions =============== This feature is to support the definition of functions in block scope. TODO: _WRITE SPEC_ Syntax Grammar ============== This grammar is represented as a diff from the current spec grammar. ```diff declaration_statement : local_variable_declaration ';' | local_constant_declaration ';' + | local_function_declaration ; +local_function_declaration + : local_function_header local_function_body + ; +local_function_header + : local_function_modifier* return_type identifier type_parameter_list? + '(' formal_parameter_list? ')' type_parameter_constraints_clauses + ; +local_function_modifier + : 'async' + | 'unsafe' + ; +local_function_body + : block + | arrow_expression_body + ; ``` Local functions may use variables defined in the enclosing scope. The current implementation requires that every variable read inside a local function be definitely assigned, as if executing the local function at its point of definition. Also, the local function definition must have been "executed" at any use point. After experimenting with that a bit (for example, it is not possible to define two mutually recursive local functions), we've since revised how we want the definite assignment to work. The revision (not yet implemented) is that all local variables read in a local function must be definitely assigned at each invocation of the local function. That's actually more subtle than it sounds, and there is a bunch of work remaining to make it work. Once it is done you'll be able to move your local functions to the end of its enclosing block. The new definite assignment rules are incompatible with inferring the return type of a local function, so we'll likely be removing support for inferring the return type. Unless you convert a local function to a delegate, capturing is done into frames that are value types. That means you don't get any GC pressure from using local functions with capturing.
Local Functions =============== This feature is to support the definition of functions in block scope. TODO: _WRITE SPEC_ Syntax Grammar ============== This grammar is represented as a diff from the current spec grammar. ```diff declaration_statement : local_variable_declaration ';' | local_constant_declaration ';' + | local_function_declaration ; +local_function_declaration + : local_function_header local_function_body + ; +local_function_header + : local_function_modifier* return_type identifier type_parameter_list? + '(' formal_parameter_list? ')' type_parameter_constraints_clauses + ; +local_function_modifier + : 'async' + | 'unsafe' + ; +local_function_body + : block + | arrow_expression_body + ; ``` Local functions may use variables defined in the enclosing scope. The current implementation requires that every variable read inside a local function be definitely assigned, as if executing the local function at its point of definition. Also, the local function definition must have been "executed" at any use point. After experimenting with that a bit (for example, it is not possible to define two mutually recursive local functions), we've since revised how we want the definite assignment to work. The revision (not yet implemented) is that all local variables read in a local function must be definitely assigned at each invocation of the local function. That's actually more subtle than it sounds, and there is a bunch of work remaining to make it work. Once it is done you'll be able to move your local functions to the end of its enclosing block. The new definite assignment rules are incompatible with inferring the return type of a local function, so we'll likely be removing support for inferring the return type. Unless you convert a local function to a delegate, capturing is done into frames that are value types. That means you don't get any GC pressure from using local functions with capturing.
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/VisualStudio/Xaml/Impl/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; using System.Linq; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Xaml { internal static class Extensions { public static Guid GetProjectGuid(this VisualStudioWorkspace workspace, ProjectId projectId) => workspace.GetProjectGuid(projectId); public static string GetFilePath(this ITextView textView) => textView.TextBuffer.GetFilePath(); public static string GetFilePath(this ITextBuffer textBuffer) { if (textBuffer.Properties.TryGetProperty<ITextDocument>(typeof(ITextDocument), out var textDoc)) { return textDoc.FilePath; } return string.Empty; } public static Project GetCodeProject(this TextDocument document) { if (document.Project.SupportsCompilation) { return document.Project; } // There has to be a match return document.Project.Solution.Projects.Single(p => p.SupportsCompilation && p.FilePath == document.Project.FilePath); } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Xaml { internal static class Extensions { public static Guid GetProjectGuid(this VisualStudioWorkspace workspace, ProjectId projectId) => workspace.GetProjectGuid(projectId); public static string GetFilePath(this ITextView textView) => textView.TextBuffer.GetFilePath(); public static string GetFilePath(this ITextBuffer textBuffer) { if (textBuffer.Properties.TryGetProperty<ITextDocument>(typeof(ITextDocument), out var textDoc)) { return textDoc.FilePath; } return string.Empty; } public static Project GetCodeProject(this TextDocument document) { if (document.Project.SupportsCompilation) { return document.Project; } // There has to be a match return document.Project.Solution.Projects.Single(p => p.SupportsCompilation && p.FilePath == document.Project.FilePath); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/Test/Resources/Core/SymbolsTests/NoPia/LocalTypes3.dll
MZ@ !L!This program cannot be run in DOS mode. $PELnkmL! & @@ @T&W@`  H.text  `.rsrc@ @@.reloc `@B&H l( *0 +*0 +*0 +*0 +*0 +*0 +*( *( *( *BSJB v4.0.30319l@#~#Strings@#USH#GUIDX#BlobG %3  B;p ,Dd% + 1 5 U P I X Ol X ^$ d/ j> M I  I  I  I I !I1I9I AIII .;.3+#\gr}VVVY  <Module>mscorlibLocalTypes3C31`1C32`1I32`1C33I31`1SystemObject.ctorTest1I1Test2Test3Test4Test5System.Collections.GenericList`1Test6TSSystem.Runtime.CompilerServicesCompilerGeneratedAttributeSystem.Runtime.InteropServicesInterfaceTypeAttributeComInterfaceTypeGuidAttributeTypeIdentifierAttributeCompilationRelaxationsAttributeRuntimeCompatibilityAttributeLocalTypes3.dll B+N>ހrqz\V4                      )$27e3e649-994b-4f58-b3c6-f8089a5f2c01 TWrapNonExceptionThrows|&& &_CorDllMainmscoree.dll% @0HX@TT4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0@InternalNameLocalTypes3.dll(LegalCopyright HOriginalFilenameLocalTypes3.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 6
MZ@ !L!This program cannot be run in DOS mode. $PELnkmL! & @@ @T&W@`  H.text  `.rsrc@ @@.reloc `@B&H l( *0 +*0 +*0 +*0 +*0 +*0 +*( *( *( *BSJB v4.0.30319l@#~#Strings@#USH#GUIDX#BlobG %3  B;p ,Dd% + 1 5 U P I X Ol X ^$ d/ j> M I  I  I  I I !I1I9I AIII .;.3+#\gr}VVVY  <Module>mscorlibLocalTypes3C31`1C32`1I32`1C33I31`1SystemObject.ctorTest1I1Test2Test3Test4Test5System.Collections.GenericList`1Test6TSSystem.Runtime.CompilerServicesCompilerGeneratedAttributeSystem.Runtime.InteropServicesInterfaceTypeAttributeComInterfaceTypeGuidAttributeTypeIdentifierAttributeCompilationRelaxationsAttributeRuntimeCompatibilityAttributeLocalTypes3.dll B+N>ހrqz\V4                      )$27e3e649-994b-4f58-b3c6-f8089a5f2c01 TWrapNonExceptionThrows|&& &_CorDllMainmscoree.dll% @0HX@TT4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0@InternalNameLocalTypes3.dll(LegalCopyright HOriginalFilenameLocalTypes3.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 6
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/Core/Portable/Collections/ConcurrentCache.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { // very simple cache with a specified size. // expiration policy is "new entry wins over old entry if hashed into the same bucket" internal class ConcurrentCache<TKey, TValue> : CachingBase<ConcurrentCache<TKey, TValue>.Entry> where TKey : notnull { private readonly IEqualityComparer<TKey> _keyComparer; // class, to ensure atomic updates. internal class Entry { internal readonly int hash; internal readonly TKey key; internal readonly TValue value; internal Entry(int hash, TKey key, TValue value) { this.hash = hash; this.key = key; this.value = value; } } public ConcurrentCache(int size, IEqualityComparer<TKey> keyComparer) : base(size) { _keyComparer = keyComparer; } public ConcurrentCache(int size) : this(size, EqualityComparer<TKey>.Default) { } public bool TryAdd(TKey key, TValue value) { var hash = _keyComparer.GetHashCode(key); var idx = hash & mask; var entry = this.entries[idx]; if (entry != null && entry.hash == hash && _keyComparer.Equals(entry.key, key)) { return false; } entries[idx] = new Entry(hash, key, value); return true; } public bool TryGetValue(TKey key, [MaybeNullWhen(returnValue: false)] out TValue value) { int hash = _keyComparer.GetHashCode(key); int idx = hash & mask; var entry = this.entries[idx]; if (entry != null && entry.hash == hash && _keyComparer.Equals(entry.key, key)) { value = entry.value; return true; } value = default!; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { // very simple cache with a specified size. // expiration policy is "new entry wins over old entry if hashed into the same bucket" internal class ConcurrentCache<TKey, TValue> : CachingBase<ConcurrentCache<TKey, TValue>.Entry> where TKey : notnull { private readonly IEqualityComparer<TKey> _keyComparer; // class, to ensure atomic updates. internal class Entry { internal readonly int hash; internal readonly TKey key; internal readonly TValue value; internal Entry(int hash, TKey key, TValue value) { this.hash = hash; this.key = key; this.value = value; } } public ConcurrentCache(int size, IEqualityComparer<TKey> keyComparer) : base(size) { _keyComparer = keyComparer; } public ConcurrentCache(int size) : this(size, EqualityComparer<TKey>.Default) { } public bool TryAdd(TKey key, TValue value) { var hash = _keyComparer.GetHashCode(key); var idx = hash & mask; var entry = this.entries[idx]; if (entry != null && entry.hash == hash && _keyComparer.Equals(entry.key, key)) { return false; } entries[idx] = new Entry(hash, key, value); return true; } public bool TryGetValue(TKey key, [MaybeNullWhen(returnValue: false)] out TValue value) { int hash = _keyComparer.GetHashCode(key); int idx = hash & mask; var entry = this.entries[idx]; if (entry != null && entry.hash == hash && _keyComparer.Equals(entry.key, key)) { value = entry.value; return true; } value = default!; return false; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/CSharp/Test/Symbol/Symbols/Metadata/PE/BaseTypeResolution.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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using CSReferenceManager = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.ReferenceManager; using System.Reflection.Metadata; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE { public class BaseTypeResolution : CSharpTestBase { [Fact] public void Test1() { var assembly = MetadataTestHelpers.GetSymbolForReference(Net40.mscorlib); TestBaseTypeResolutionHelper1(assembly); var assemblies = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[] { TestReferences.SymbolsTests.MDTestLib1, TestReferences.SymbolsTests.MDTestLib2, Net40.mscorlib }); TestBaseTypeResolutionHelper2(assemblies); assemblies = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[] { TestReferences.SymbolsTests.MDTestLib1, TestReferences.SymbolsTests.MDTestLib2 }); // TestBaseTypeResolutionHelper3(assemblies); // TODO(alekseyt): this test is not valid. See email of 7/23/2010 for explanation. assemblies = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[] { TestReferences.SymbolsTests.MultiModule.Assembly, TestReferences.SymbolsTests.MultiModule.Consumer }); TestBaseTypeResolutionHelper4(assemblies); } private void TestBaseTypeResolutionHelper1(AssemblySymbol assembly) { var module0 = assembly.Modules[0]; var sys = module0.GlobalNamespace.GetMembers("System"); var collections = ((NamespaceSymbol)sys[0]).GetMembers("Collections"); var generic = ((NamespaceSymbol)collections[0]).GetMembers("Generic"); var dictionary = ((NamespaceSymbol)generic[0]).GetMembers("Dictionary"); var @base = ((NamedTypeSymbol)dictionary[0]).BaseType(); AssertBaseType(@base, "System.Object"); Assert.Null(@base.BaseType()); var concurrent = ((NamespaceSymbol)collections[0]).GetMembers("Concurrent"); var orderablePartitioners = ((NamespaceSymbol)concurrent[0]).GetMembers("OrderablePartitioner"); NamedTypeSymbol orderablePartitioner = null; foreach (var p in orderablePartitioners) { var t = p as NamedTypeSymbol; if ((object)t != null && t.Arity == 1) { orderablePartitioner = t; break; } } @base = orderablePartitioner.BaseType(); AssertBaseType(@base, "System.Collections.Concurrent.Partitioner<TSource>"); Assert.Same(((NamedTypeSymbol)@base).TypeArguments()[0], orderablePartitioner.TypeParameters[0]); var partitioners = ((NamespaceSymbol)concurrent[0]).GetMembers("Partitioner"); NamedTypeSymbol partitioner = null; foreach (var p in partitioners) { var t = p as NamedTypeSymbol; if ((object)t != null && t.Arity == 0) { partitioner = t; break; } } Assert.NotNull(partitioner); } private void TestBaseTypeResolutionHelper2(AssemblySymbol[] assemblies) { var module1 = assemblies[0].Modules[0]; var module2 = assemblies[1].Modules[0]; var varTC2 = module1.GlobalNamespace.GetTypeMembers("TC2").Single(); var varTC3 = module1.GlobalNamespace.GetTypeMembers("TC3").Single(); var varTC4 = module1.GlobalNamespace.GetTypeMembers("TC4").Single(); AssertBaseType(varTC2.BaseType(), "C1<TC2_T1>.C2<TC2_T2>"); AssertBaseType(varTC3.BaseType(), "C1<TC3_T1>.C3"); AssertBaseType(varTC4.BaseType(), "C1<TC4_T1>.C3.C4<TC4_T2>"); var varC1 = module1.GlobalNamespace.GetTypeMembers("C1").Single(); AssertBaseType(varC1.BaseType(), "System.Object"); Assert.Equal(0, varC1.Interfaces().Length); var varTC5 = module2.GlobalNamespace.GetTypeMembers("TC5").Single(); var varTC6 = module2.GlobalNamespace.GetTypeMembers("TC6").Single(); var varTC7 = module2.GlobalNamespace.GetTypeMembers("TC7").Single(); var varTC8 = module2.GlobalNamespace.GetTypeMembers("TC8").Single(); var varTC9 = varTC6.GetTypeMembers("TC9").Single(); AssertBaseType(varTC5.BaseType(), "C1<TC5_T1>.C2<TC5_T2>"); AssertBaseType(varTC6.BaseType(), "C1<TC6_T1>.C3"); AssertBaseType(varTC7.BaseType(), "C1<TC7_T1>.C3.C4<TC7_T2>"); AssertBaseType(varTC8.BaseType(), "C1<System.Type>"); AssertBaseType(varTC9.BaseType(), "TC6<TC6_T1>"); var varCorTypes = module2.GlobalNamespace.GetMembers("CorTypes").OfType<NamespaceSymbol>().Single(); var varCorTypes_Derived = varCorTypes.GetTypeMembers("Derived").Single(); AssertBaseType(varCorTypes_Derived.BaseType(), "CorTypes.NS.Base<System.Boolean, System.SByte, System.Byte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, System.UInt64, System.Single, System.Double, System.Char, System.String, System.IntPtr, System.UIntPtr, System.Object>"); var varCorTypes_Derived1 = varCorTypes.GetTypeMembers("Derived1").Single(); AssertBaseType(varCorTypes_Derived1.BaseType(), "CorTypes.Base<System.Int32[], System.Double[,]>"); var varI101 = module1.GlobalNamespace.GetTypeMembers("I101").Single(); var varI102 = module1.GlobalNamespace.GetTypeMembers("I102").Single(); var varC203 = module1.GlobalNamespace.GetTypeMembers("C203").Single(); Assert.Equal(1, varC203.Interfaces().Length); Assert.Same(varI101, varC203.Interfaces()[0]); var varC204 = module1.GlobalNamespace.GetTypeMembers("C204").Single(); Assert.Equal(2, varC204.Interfaces().Length); Assert.Same(varI101, varC204.Interfaces()[0]); Assert.Same(varI102, varC204.Interfaces()[1]); } private void TestBaseTypeResolutionHelper3(AssemblySymbol[] assemblies) { var module1 = assemblies[0].Modules[0]; var module2 = assemblies[1].Modules[0]; var varCorTypes = module2.GlobalNamespace.GetMembers("CorTypes").OfType<NamespaceSymbol>().Single(); var varCorTypes_Derived = varCorTypes.GetTypeMembers("Derived").Single(); AssertBaseType(varCorTypes_Derived.BaseType(), "CorTypes.NS.Base<System.Boolean,System.SByte,System.Byte,System.Int16,System.UInt16,System.Int32,System.UInt32,System.Int64,System.UInt64,System.Single,System.Double,System.Char,System.String,System.IntPtr,System.UIntPtr,System.Object>"); foreach (var arg in varCorTypes_Derived.BaseType().TypeArguments()) { Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(arg); } } private void TestBaseTypeResolutionHelper4(AssemblySymbol[] assemblies) { var module1 = assemblies[0].Modules[0]; var module2 = assemblies[0].Modules[1]; var module3 = assemblies[0].Modules[2]; var module0 = assemblies[1].Modules[0]; var derived1 = module0.GlobalNamespace.GetTypeMembers("Derived1").Single(); var base1 = derived1.BaseType(); var derived2 = module0.GlobalNamespace.GetTypeMembers("Derived2").Single(); var base2 = derived2.BaseType(); var derived3 = module0.GlobalNamespace.GetTypeMembers("Derived3").Single(); var base3 = derived3.BaseType(); AssertBaseType(base1, "Class1"); AssertBaseType(base2, "Class2"); AssertBaseType(base3, "Class3"); Assert.Same(base1, module1.GlobalNamespace.GetTypeMembers("Class1").Single()); Assert.Same(base2, module2.GlobalNamespace.GetTypeMembers("Class2").Single()); Assert.Same(base3, module3.GlobalNamespace.GetTypeMembers("Class3").Single()); return; } internal static void AssertBaseType(TypeSymbol @base, string name) { Assert.NotEqual(SymbolKind.ErrorType, @base.Kind); Assert.Equal(name, @base.ToTestDisplayString()); } [Fact] public void Test2() { var assemblies = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[] { TestReferences.SymbolsTests.DifferByCase.Consumer, TestReferences.SymbolsTests.DifferByCase.TypeAndNamespaceDifferByCase }); var module0 = assemblies[0].Modules[0] as PEModuleSymbol; var module1 = assemblies[1].Modules[0] as PEModuleSymbol; var bases = new HashSet<NamedTypeSymbol>(); var localTC1 = module0.GlobalNamespace.GetTypeMembers("TC1").Single(); var base1 = localTC1.BaseType(); bases.Add(base1); Assert.NotEqual(SymbolKind.ErrorType, base1.Kind); Assert.Equal("SomeName.Dummy", base1.ToTestDisplayString()); var localTC2 = module0.GlobalNamespace.GetTypeMembers("TC2").Single(); var base2 = localTC2.BaseType(); bases.Add(base2); Assert.NotEqual(SymbolKind.ErrorType, base2.Kind); Assert.Equal("somEnamE", base2.ToTestDisplayString()); var localTC3 = module0.GlobalNamespace.GetTypeMembers("TC3").Single(); var base3 = localTC3.BaseType(); bases.Add(base3); Assert.NotEqual(SymbolKind.ErrorType, base3.Kind); Assert.Equal("somEnamE1", base3.ToTestDisplayString()); var localTC4 = module0.GlobalNamespace.GetTypeMembers("TC4").Single(); var base4 = localTC4.BaseType(); bases.Add(base4); Assert.NotEqual(SymbolKind.ErrorType, base4.Kind); Assert.Equal("SomeName1", base4.ToTestDisplayString()); var localTC5 = module0.GlobalNamespace.GetTypeMembers("TC5").Single(); var base5 = localTC5.BaseType(); bases.Add(base5); Assert.NotEqual(SymbolKind.ErrorType, base5.Kind); Assert.Equal("somEnamE2.OtherName", base5.ToTestDisplayString()); var localTC6 = module0.GlobalNamespace.GetTypeMembers("TC6").Single(); var base6 = localTC6.BaseType(); bases.Add(base6); Assert.NotEqual(SymbolKind.ErrorType, base6.Kind); Assert.Equal("SomeName2.OtherName", base6.ToTestDisplayString()); var localTC7 = module0.GlobalNamespace.GetTypeMembers("TC7").Single(); var base7 = localTC7.BaseType(); bases.Add(base7); Assert.NotEqual(SymbolKind.ErrorType, base7.Kind); Assert.Equal("NestingClass.somEnamE3", base7.ToTestDisplayString()); var localTC8 = module0.GlobalNamespace.GetTypeMembers("TC8").Single(); var base8 = localTC8.BaseType(); bases.Add(base8); Assert.NotEqual(SymbolKind.ErrorType, base8.Kind); Assert.Equal("NestingClass.SomeName3", base8.ToTestDisplayString()); Assert.Equal(8, bases.Count); Assert.Equal(base1, module1.TypeHandleToTypeMap[((PENamedTypeSymbol)base1).Handle]); Assert.Equal(base2, module1.TypeHandleToTypeMap[((PENamedTypeSymbol)base2).Handle]); Assert.Equal(base3, module1.TypeHandleToTypeMap[((PENamedTypeSymbol)base3).Handle]); Assert.Equal(base4, module1.TypeHandleToTypeMap[((PENamedTypeSymbol)base4).Handle]); Assert.Equal(base5, module1.TypeHandleToTypeMap[((PENamedTypeSymbol)base5).Handle]); Assert.Equal(base6, module1.TypeHandleToTypeMap[((PENamedTypeSymbol)base6).Handle]); Assert.Equal(base7, module1.TypeHandleToTypeMap[((PENamedTypeSymbol)base7).Handle]); Assert.Equal(base8, module1.TypeHandleToTypeMap[((PENamedTypeSymbol)base8).Handle]); Assert.Equal(base1, module0.TypeRefHandleToTypeMap[(TypeReferenceHandle)module0.Module.GetBaseTypeOfTypeOrThrow(((PENamedTypeSymbol)localTC1).Handle)]); Assert.Equal(base2, module0.TypeRefHandleToTypeMap[(TypeReferenceHandle)module0.Module.GetBaseTypeOfTypeOrThrow(((PENamedTypeSymbol)localTC2).Handle)]); Assert.Equal(base3, module0.TypeRefHandleToTypeMap[(TypeReferenceHandle)module0.Module.GetBaseTypeOfTypeOrThrow(((PENamedTypeSymbol)localTC3).Handle)]); Assert.Equal(base4, module0.TypeRefHandleToTypeMap[(TypeReferenceHandle)module0.Module.GetBaseTypeOfTypeOrThrow(((PENamedTypeSymbol)localTC4).Handle)]); Assert.Equal(base5, module0.TypeRefHandleToTypeMap[(TypeReferenceHandle)module0.Module.GetBaseTypeOfTypeOrThrow(((PENamedTypeSymbol)localTC5).Handle)]); Assert.Equal(base6, module0.TypeRefHandleToTypeMap[(TypeReferenceHandle)module0.Module.GetBaseTypeOfTypeOrThrow(((PENamedTypeSymbol)localTC6).Handle)]); Assert.Equal(base7, module0.TypeRefHandleToTypeMap[(TypeReferenceHandle)module0.Module.GetBaseTypeOfTypeOrThrow(((PENamedTypeSymbol)localTC7).Handle)]); Assert.Equal(base8, module0.TypeRefHandleToTypeMap[(TypeReferenceHandle)module0.Module.GetBaseTypeOfTypeOrThrow(((PENamedTypeSymbol)localTC8).Handle)]); var assembly1 = (MetadataOrSourceAssemblySymbol)assemblies[1]; Assert.Equal(base1, assembly1.CachedTypeByEmittedName(base1.ToTestDisplayString())); Assert.Equal(base2, assembly1.CachedTypeByEmittedName(base2.ToTestDisplayString())); Assert.Equal(base3, assembly1.CachedTypeByEmittedName(base3.ToTestDisplayString())); Assert.Equal(base4, assembly1.CachedTypeByEmittedName(base4.ToTestDisplayString())); Assert.Equal(base5, assembly1.CachedTypeByEmittedName(base5.ToTestDisplayString())); Assert.Equal(base6, assembly1.CachedTypeByEmittedName(base6.ToTestDisplayString())); Assert.Equal(base7.ContainingType, assembly1.CachedTypeByEmittedName(base7.ContainingType.ToTestDisplayString())); Assert.Equal(7, assembly1.EmittedNameToTypeMapCount); } [Fact] public void Test3() { var mscorlibRef = Net40.mscorlib; var c1 = CSharpCompilation.Create("Test", references: new MetadataReference[] { mscorlibRef }); Assert.Equal("System.Object", ((SourceModuleSymbol)c1.Assembly.Modules[0]).GetCorLibType(SpecialType.System_Object).ToTestDisplayString()); var localMTTestLib1Ref = TestReferences.SymbolsTests.V1.MTTestLib1.dll; var c2 = CSharpCompilation.Create("Test2", references: new MetadataReference[] { localMTTestLib1Ref }); Assert.Equal("System.Object[missing]", ((SourceModuleSymbol)c2.Assembly.Modules[0]).GetCorLibType(SpecialType.System_Object).ToTestDisplayString()); } [Fact] public void CrossModuleReferences1() { var compilationDef1 = @" class Test1 : M3 { } class Test2 : M4 { } "; var crossRefModule1 = TestReferences.SymbolsTests.netModule.CrossRefModule1; var crossRefModule2 = TestReferences.SymbolsTests.netModule.CrossRefModule2; var crossRefLib = TestReferences.SymbolsTests.netModule.CrossRefLib; var compilation1 = CreateCompilation(compilationDef1, new MetadataReference[] { crossRefLib }, TestOptions.ReleaseDll); compilation1.VerifyDiagnostics(); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.False(test1.BaseType().IsErrorType()); Assert.False(test1.BaseType().BaseType().IsErrorType()); Assert.False(test2.BaseType().IsErrorType()); Assert.False(test2.BaseType().BaseType().IsErrorType()); Assert.False(test2.BaseType().BaseType().BaseType().IsErrorType()); var compilationDef2 = @" public class M3 : M1 {} public class M4 : M2 {} "; var compilation2 = CreateCompilation(compilationDef2, new MetadataReference[] { crossRefModule1, crossRefModule2 }, TestOptions.ReleaseDll); compilation2.VerifyDiagnostics(); var m3 = compilation2.GetTypeByMetadataName("M3"); var m4 = compilation2.GetTypeByMetadataName("M4"); Assert.False(m3.BaseType().IsErrorType()); Assert.False(m3.BaseType().BaseType().IsErrorType()); Assert.False(m4.BaseType().IsErrorType()); Assert.False(m4.BaseType().BaseType().IsErrorType()); var compilation3 = CreateCompilation(compilationDef2, new MetadataReference[] { crossRefModule2 }, TestOptions.ReleaseDll); m3 = compilation3.GetTypeByMetadataName("M3"); m4 = compilation3.GetTypeByMetadataName("M4"); Assert.True(m3.BaseType().IsErrorType()); Assert.False(m4.BaseType().IsErrorType()); Assert.True(m4.BaseType().BaseType().IsErrorType()); // Expected: //error CS0246: The type or namespace name 'M1' could not be found (are you missing a using directive or an // assembly reference?) //CrossRefModule2.netmodule: error CS0011: The base class or interface 'M1' in assembly 'CrossRefModule1.netmodule' // referenced by type 'M2' could not be resolved DiagnosticDescription[] errors = { // (2,19): error CS0246: The type or namespace name 'M1' could not be found (are you missing a using directive or an assembly reference?) // public class M3 : M1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "M1").WithArguments("M1"), // (5,19): error CS7079: The type 'M1' is defined in a module that has not been added. You must add the module 'CrossRefModule1.netmodule'. // public class M4 : M2 Diagnostic(ErrorCode.ERR_NoTypeDefFromModule, "M2").WithArguments("M1", "CrossRefModule1.netmodule"), // error CS8014: Reference to 'CrossRefModule1.netmodule' netmodule missing. Diagnostic(ErrorCode.ERR_MissingNetModuleReference).WithArguments("CrossRefModule1.netmodule") }; compilation3.VerifyDiagnostics(errors); } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using CSReferenceManager = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.ReferenceManager; using System.Reflection.Metadata; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE { public class BaseTypeResolution : CSharpTestBase { [Fact] public void Test1() { var assembly = MetadataTestHelpers.GetSymbolForReference(Net40.mscorlib); TestBaseTypeResolutionHelper1(assembly); var assemblies = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[] { TestReferences.SymbolsTests.MDTestLib1, TestReferences.SymbolsTests.MDTestLib2, Net40.mscorlib }); TestBaseTypeResolutionHelper2(assemblies); assemblies = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[] { TestReferences.SymbolsTests.MDTestLib1, TestReferences.SymbolsTests.MDTestLib2 }); // TestBaseTypeResolutionHelper3(assemblies); // TODO(alekseyt): this test is not valid. See email of 7/23/2010 for explanation. assemblies = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[] { TestReferences.SymbolsTests.MultiModule.Assembly, TestReferences.SymbolsTests.MultiModule.Consumer }); TestBaseTypeResolutionHelper4(assemblies); } private void TestBaseTypeResolutionHelper1(AssemblySymbol assembly) { var module0 = assembly.Modules[0]; var sys = module0.GlobalNamespace.GetMembers("System"); var collections = ((NamespaceSymbol)sys[0]).GetMembers("Collections"); var generic = ((NamespaceSymbol)collections[0]).GetMembers("Generic"); var dictionary = ((NamespaceSymbol)generic[0]).GetMembers("Dictionary"); var @base = ((NamedTypeSymbol)dictionary[0]).BaseType(); AssertBaseType(@base, "System.Object"); Assert.Null(@base.BaseType()); var concurrent = ((NamespaceSymbol)collections[0]).GetMembers("Concurrent"); var orderablePartitioners = ((NamespaceSymbol)concurrent[0]).GetMembers("OrderablePartitioner"); NamedTypeSymbol orderablePartitioner = null; foreach (var p in orderablePartitioners) { var t = p as NamedTypeSymbol; if ((object)t != null && t.Arity == 1) { orderablePartitioner = t; break; } } @base = orderablePartitioner.BaseType(); AssertBaseType(@base, "System.Collections.Concurrent.Partitioner<TSource>"); Assert.Same(((NamedTypeSymbol)@base).TypeArguments()[0], orderablePartitioner.TypeParameters[0]); var partitioners = ((NamespaceSymbol)concurrent[0]).GetMembers("Partitioner"); NamedTypeSymbol partitioner = null; foreach (var p in partitioners) { var t = p as NamedTypeSymbol; if ((object)t != null && t.Arity == 0) { partitioner = t; break; } } Assert.NotNull(partitioner); } private void TestBaseTypeResolutionHelper2(AssemblySymbol[] assemblies) { var module1 = assemblies[0].Modules[0]; var module2 = assemblies[1].Modules[0]; var varTC2 = module1.GlobalNamespace.GetTypeMembers("TC2").Single(); var varTC3 = module1.GlobalNamespace.GetTypeMembers("TC3").Single(); var varTC4 = module1.GlobalNamespace.GetTypeMembers("TC4").Single(); AssertBaseType(varTC2.BaseType(), "C1<TC2_T1>.C2<TC2_T2>"); AssertBaseType(varTC3.BaseType(), "C1<TC3_T1>.C3"); AssertBaseType(varTC4.BaseType(), "C1<TC4_T1>.C3.C4<TC4_T2>"); var varC1 = module1.GlobalNamespace.GetTypeMembers("C1").Single(); AssertBaseType(varC1.BaseType(), "System.Object"); Assert.Equal(0, varC1.Interfaces().Length); var varTC5 = module2.GlobalNamespace.GetTypeMembers("TC5").Single(); var varTC6 = module2.GlobalNamespace.GetTypeMembers("TC6").Single(); var varTC7 = module2.GlobalNamespace.GetTypeMembers("TC7").Single(); var varTC8 = module2.GlobalNamespace.GetTypeMembers("TC8").Single(); var varTC9 = varTC6.GetTypeMembers("TC9").Single(); AssertBaseType(varTC5.BaseType(), "C1<TC5_T1>.C2<TC5_T2>"); AssertBaseType(varTC6.BaseType(), "C1<TC6_T1>.C3"); AssertBaseType(varTC7.BaseType(), "C1<TC7_T1>.C3.C4<TC7_T2>"); AssertBaseType(varTC8.BaseType(), "C1<System.Type>"); AssertBaseType(varTC9.BaseType(), "TC6<TC6_T1>"); var varCorTypes = module2.GlobalNamespace.GetMembers("CorTypes").OfType<NamespaceSymbol>().Single(); var varCorTypes_Derived = varCorTypes.GetTypeMembers("Derived").Single(); AssertBaseType(varCorTypes_Derived.BaseType(), "CorTypes.NS.Base<System.Boolean, System.SByte, System.Byte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, System.UInt64, System.Single, System.Double, System.Char, System.String, System.IntPtr, System.UIntPtr, System.Object>"); var varCorTypes_Derived1 = varCorTypes.GetTypeMembers("Derived1").Single(); AssertBaseType(varCorTypes_Derived1.BaseType(), "CorTypes.Base<System.Int32[], System.Double[,]>"); var varI101 = module1.GlobalNamespace.GetTypeMembers("I101").Single(); var varI102 = module1.GlobalNamespace.GetTypeMembers("I102").Single(); var varC203 = module1.GlobalNamespace.GetTypeMembers("C203").Single(); Assert.Equal(1, varC203.Interfaces().Length); Assert.Same(varI101, varC203.Interfaces()[0]); var varC204 = module1.GlobalNamespace.GetTypeMembers("C204").Single(); Assert.Equal(2, varC204.Interfaces().Length); Assert.Same(varI101, varC204.Interfaces()[0]); Assert.Same(varI102, varC204.Interfaces()[1]); } private void TestBaseTypeResolutionHelper3(AssemblySymbol[] assemblies) { var module1 = assemblies[0].Modules[0]; var module2 = assemblies[1].Modules[0]; var varCorTypes = module2.GlobalNamespace.GetMembers("CorTypes").OfType<NamespaceSymbol>().Single(); var varCorTypes_Derived = varCorTypes.GetTypeMembers("Derived").Single(); AssertBaseType(varCorTypes_Derived.BaseType(), "CorTypes.NS.Base<System.Boolean,System.SByte,System.Byte,System.Int16,System.UInt16,System.Int32,System.UInt32,System.Int64,System.UInt64,System.Single,System.Double,System.Char,System.String,System.IntPtr,System.UIntPtr,System.Object>"); foreach (var arg in varCorTypes_Derived.BaseType().TypeArguments()) { Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(arg); } } private void TestBaseTypeResolutionHelper4(AssemblySymbol[] assemblies) { var module1 = assemblies[0].Modules[0]; var module2 = assemblies[0].Modules[1]; var module3 = assemblies[0].Modules[2]; var module0 = assemblies[1].Modules[0]; var derived1 = module0.GlobalNamespace.GetTypeMembers("Derived1").Single(); var base1 = derived1.BaseType(); var derived2 = module0.GlobalNamespace.GetTypeMembers("Derived2").Single(); var base2 = derived2.BaseType(); var derived3 = module0.GlobalNamespace.GetTypeMembers("Derived3").Single(); var base3 = derived3.BaseType(); AssertBaseType(base1, "Class1"); AssertBaseType(base2, "Class2"); AssertBaseType(base3, "Class3"); Assert.Same(base1, module1.GlobalNamespace.GetTypeMembers("Class1").Single()); Assert.Same(base2, module2.GlobalNamespace.GetTypeMembers("Class2").Single()); Assert.Same(base3, module3.GlobalNamespace.GetTypeMembers("Class3").Single()); return; } internal static void AssertBaseType(TypeSymbol @base, string name) { Assert.NotEqual(SymbolKind.ErrorType, @base.Kind); Assert.Equal(name, @base.ToTestDisplayString()); } [Fact] public void Test2() { var assemblies = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[] { TestReferences.SymbolsTests.DifferByCase.Consumer, TestReferences.SymbolsTests.DifferByCase.TypeAndNamespaceDifferByCase }); var module0 = assemblies[0].Modules[0] as PEModuleSymbol; var module1 = assemblies[1].Modules[0] as PEModuleSymbol; var bases = new HashSet<NamedTypeSymbol>(); var localTC1 = module0.GlobalNamespace.GetTypeMembers("TC1").Single(); var base1 = localTC1.BaseType(); bases.Add(base1); Assert.NotEqual(SymbolKind.ErrorType, base1.Kind); Assert.Equal("SomeName.Dummy", base1.ToTestDisplayString()); var localTC2 = module0.GlobalNamespace.GetTypeMembers("TC2").Single(); var base2 = localTC2.BaseType(); bases.Add(base2); Assert.NotEqual(SymbolKind.ErrorType, base2.Kind); Assert.Equal("somEnamE", base2.ToTestDisplayString()); var localTC3 = module0.GlobalNamespace.GetTypeMembers("TC3").Single(); var base3 = localTC3.BaseType(); bases.Add(base3); Assert.NotEqual(SymbolKind.ErrorType, base3.Kind); Assert.Equal("somEnamE1", base3.ToTestDisplayString()); var localTC4 = module0.GlobalNamespace.GetTypeMembers("TC4").Single(); var base4 = localTC4.BaseType(); bases.Add(base4); Assert.NotEqual(SymbolKind.ErrorType, base4.Kind); Assert.Equal("SomeName1", base4.ToTestDisplayString()); var localTC5 = module0.GlobalNamespace.GetTypeMembers("TC5").Single(); var base5 = localTC5.BaseType(); bases.Add(base5); Assert.NotEqual(SymbolKind.ErrorType, base5.Kind); Assert.Equal("somEnamE2.OtherName", base5.ToTestDisplayString()); var localTC6 = module0.GlobalNamespace.GetTypeMembers("TC6").Single(); var base6 = localTC6.BaseType(); bases.Add(base6); Assert.NotEqual(SymbolKind.ErrorType, base6.Kind); Assert.Equal("SomeName2.OtherName", base6.ToTestDisplayString()); var localTC7 = module0.GlobalNamespace.GetTypeMembers("TC7").Single(); var base7 = localTC7.BaseType(); bases.Add(base7); Assert.NotEqual(SymbolKind.ErrorType, base7.Kind); Assert.Equal("NestingClass.somEnamE3", base7.ToTestDisplayString()); var localTC8 = module0.GlobalNamespace.GetTypeMembers("TC8").Single(); var base8 = localTC8.BaseType(); bases.Add(base8); Assert.NotEqual(SymbolKind.ErrorType, base8.Kind); Assert.Equal("NestingClass.SomeName3", base8.ToTestDisplayString()); Assert.Equal(8, bases.Count); Assert.Equal(base1, module1.TypeHandleToTypeMap[((PENamedTypeSymbol)base1).Handle]); Assert.Equal(base2, module1.TypeHandleToTypeMap[((PENamedTypeSymbol)base2).Handle]); Assert.Equal(base3, module1.TypeHandleToTypeMap[((PENamedTypeSymbol)base3).Handle]); Assert.Equal(base4, module1.TypeHandleToTypeMap[((PENamedTypeSymbol)base4).Handle]); Assert.Equal(base5, module1.TypeHandleToTypeMap[((PENamedTypeSymbol)base5).Handle]); Assert.Equal(base6, module1.TypeHandleToTypeMap[((PENamedTypeSymbol)base6).Handle]); Assert.Equal(base7, module1.TypeHandleToTypeMap[((PENamedTypeSymbol)base7).Handle]); Assert.Equal(base8, module1.TypeHandleToTypeMap[((PENamedTypeSymbol)base8).Handle]); Assert.Equal(base1, module0.TypeRefHandleToTypeMap[(TypeReferenceHandle)module0.Module.GetBaseTypeOfTypeOrThrow(((PENamedTypeSymbol)localTC1).Handle)]); Assert.Equal(base2, module0.TypeRefHandleToTypeMap[(TypeReferenceHandle)module0.Module.GetBaseTypeOfTypeOrThrow(((PENamedTypeSymbol)localTC2).Handle)]); Assert.Equal(base3, module0.TypeRefHandleToTypeMap[(TypeReferenceHandle)module0.Module.GetBaseTypeOfTypeOrThrow(((PENamedTypeSymbol)localTC3).Handle)]); Assert.Equal(base4, module0.TypeRefHandleToTypeMap[(TypeReferenceHandle)module0.Module.GetBaseTypeOfTypeOrThrow(((PENamedTypeSymbol)localTC4).Handle)]); Assert.Equal(base5, module0.TypeRefHandleToTypeMap[(TypeReferenceHandle)module0.Module.GetBaseTypeOfTypeOrThrow(((PENamedTypeSymbol)localTC5).Handle)]); Assert.Equal(base6, module0.TypeRefHandleToTypeMap[(TypeReferenceHandle)module0.Module.GetBaseTypeOfTypeOrThrow(((PENamedTypeSymbol)localTC6).Handle)]); Assert.Equal(base7, module0.TypeRefHandleToTypeMap[(TypeReferenceHandle)module0.Module.GetBaseTypeOfTypeOrThrow(((PENamedTypeSymbol)localTC7).Handle)]); Assert.Equal(base8, module0.TypeRefHandleToTypeMap[(TypeReferenceHandle)module0.Module.GetBaseTypeOfTypeOrThrow(((PENamedTypeSymbol)localTC8).Handle)]); var assembly1 = (MetadataOrSourceAssemblySymbol)assemblies[1]; Assert.Equal(base1, assembly1.CachedTypeByEmittedName(base1.ToTestDisplayString())); Assert.Equal(base2, assembly1.CachedTypeByEmittedName(base2.ToTestDisplayString())); Assert.Equal(base3, assembly1.CachedTypeByEmittedName(base3.ToTestDisplayString())); Assert.Equal(base4, assembly1.CachedTypeByEmittedName(base4.ToTestDisplayString())); Assert.Equal(base5, assembly1.CachedTypeByEmittedName(base5.ToTestDisplayString())); Assert.Equal(base6, assembly1.CachedTypeByEmittedName(base6.ToTestDisplayString())); Assert.Equal(base7.ContainingType, assembly1.CachedTypeByEmittedName(base7.ContainingType.ToTestDisplayString())); Assert.Equal(7, assembly1.EmittedNameToTypeMapCount); } [Fact] public void Test3() { var mscorlibRef = Net40.mscorlib; var c1 = CSharpCompilation.Create("Test", references: new MetadataReference[] { mscorlibRef }); Assert.Equal("System.Object", ((SourceModuleSymbol)c1.Assembly.Modules[0]).GetCorLibType(SpecialType.System_Object).ToTestDisplayString()); var localMTTestLib1Ref = TestReferences.SymbolsTests.V1.MTTestLib1.dll; var c2 = CSharpCompilation.Create("Test2", references: new MetadataReference[] { localMTTestLib1Ref }); Assert.Equal("System.Object[missing]", ((SourceModuleSymbol)c2.Assembly.Modules[0]).GetCorLibType(SpecialType.System_Object).ToTestDisplayString()); } [Fact] public void CrossModuleReferences1() { var compilationDef1 = @" class Test1 : M3 { } class Test2 : M4 { } "; var crossRefModule1 = TestReferences.SymbolsTests.netModule.CrossRefModule1; var crossRefModule2 = TestReferences.SymbolsTests.netModule.CrossRefModule2; var crossRefLib = TestReferences.SymbolsTests.netModule.CrossRefLib; var compilation1 = CreateCompilation(compilationDef1, new MetadataReference[] { crossRefLib }, TestOptions.ReleaseDll); compilation1.VerifyDiagnostics(); var test1 = compilation1.GetTypeByMetadataName("Test1"); var test2 = compilation1.GetTypeByMetadataName("Test2"); Assert.False(test1.BaseType().IsErrorType()); Assert.False(test1.BaseType().BaseType().IsErrorType()); Assert.False(test2.BaseType().IsErrorType()); Assert.False(test2.BaseType().BaseType().IsErrorType()); Assert.False(test2.BaseType().BaseType().BaseType().IsErrorType()); var compilationDef2 = @" public class M3 : M1 {} public class M4 : M2 {} "; var compilation2 = CreateCompilation(compilationDef2, new MetadataReference[] { crossRefModule1, crossRefModule2 }, TestOptions.ReleaseDll); compilation2.VerifyDiagnostics(); var m3 = compilation2.GetTypeByMetadataName("M3"); var m4 = compilation2.GetTypeByMetadataName("M4"); Assert.False(m3.BaseType().IsErrorType()); Assert.False(m3.BaseType().BaseType().IsErrorType()); Assert.False(m4.BaseType().IsErrorType()); Assert.False(m4.BaseType().BaseType().IsErrorType()); var compilation3 = CreateCompilation(compilationDef2, new MetadataReference[] { crossRefModule2 }, TestOptions.ReleaseDll); m3 = compilation3.GetTypeByMetadataName("M3"); m4 = compilation3.GetTypeByMetadataName("M4"); Assert.True(m3.BaseType().IsErrorType()); Assert.False(m4.BaseType().IsErrorType()); Assert.True(m4.BaseType().BaseType().IsErrorType()); // Expected: //error CS0246: The type or namespace name 'M1' could not be found (are you missing a using directive or an // assembly reference?) //CrossRefModule2.netmodule: error CS0011: The base class or interface 'M1' in assembly 'CrossRefModule1.netmodule' // referenced by type 'M2' could not be resolved DiagnosticDescription[] errors = { // (2,19): error CS0246: The type or namespace name 'M1' could not be found (are you missing a using directive or an assembly reference?) // public class M3 : M1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "M1").WithArguments("M1"), // (5,19): error CS7079: The type 'M1' is defined in a module that has not been added. You must add the module 'CrossRefModule1.netmodule'. // public class M4 : M2 Diagnostic(ErrorCode.ERR_NoTypeDefFromModule, "M2").WithArguments("M1", "CrossRefModule1.netmodule"), // error CS8014: Reference to 'CrossRefModule1.netmodule' netmodule missing. Diagnostic(ErrorCode.ERR_MissingNetModuleReference).WithArguments("CrossRefModule1.netmodule") }; compilation3.VerifyDiagnostics(errors); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/VisualBasic/Portable/Emit/SynthesizedPrivateImplementationDetailsSharedConstructor.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Linq Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class SynthesizedPrivateImplementationDetailsSharedConstructor Inherits SynthesizedGlobalMethodBase Private ReadOnly _containingModule As SourceModuleSymbol Private ReadOnly _privateImplementationType As PrivateImplementationDetails Private ReadOnly _voidType As TypeSymbol Friend Sub New( containingModule As SourceModuleSymbol, privateImplementationType As PrivateImplementationDetails, voidType As NamedTypeSymbol ) MyBase.New(containingModule, WellKnownMemberNames.StaticConstructorName, privateImplementationType) _containingModule = containingModule _privateImplementationType = privateImplementationType _voidType = voidType End Sub Public Overrides ReadOnly Property IsSub As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return _voidType End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.SharedConstructor End Get End Property Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock methodBodyBinder = Nothing Dim factory As New SyntheticBoundNodeFactory(Me, Me, VisualBasicSyntaxTree.Dummy.GetRoot(), compilationState, diagnostics) Dim body As ArrayBuilder(Of BoundStatement) = ArrayBuilder(Of BoundStatement).GetInstance() ' Initialize the payload root for each kind of dynamic analysis instrumentation. ' A payload root is an array of arrays of per-method instrumentation payloads. ' For each kind of instrumentation: ' ' payloadRoot = New T(MaximumMethodDefIndex)() {} ' ' where T Is the type of the payload at each instrumentation point, and MaximumMethodDefIndex is the ' index portion of the greatest method definition token in the compilation. This guarantees that any ' method can use the index portion of its own method definition token as an index into the payload array. For Each payloadRoot As KeyValuePair(Of Integer, InstrumentationPayloadRootField) In _privateImplementationType.GetInstrumentationPayloadRoots() Dim analysisKind As Integer = payloadRoot.Key Dim payloadArrayType As ArrayTypeSymbol = DirectCast(payloadRoot.Value.Type.GetInternalSymbol(), ArrayTypeSymbol) body.Add( factory.Assignment( factory.InstrumentationPayloadRoot(analysisKind, payloadArrayType, isLValue:=True), factory.Array(payloadArrayType.ElementType, ImmutableArray.Create(factory.MaximumMethodDefIndex()), ImmutableArray(Of BoundExpression).Empty))) Next ' Initialize the module version ID (MVID) field. Dynamic instrumentation requires the MVID of the executing module, and this field makes that accessible. ' MVID = New Guid(ModuleVersionIdString) Dim guidConstructor As MethodSymbol = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Guid__ctor) If guidConstructor IsNot Nothing Then body.Add( factory.Assignment( factory.ModuleVersionId(isLValue:=True), factory.[New](guidConstructor, factory.ModuleVersionIdString()))) End If body.Add(factory.Return()) Return factory.Block(body.ToImmutableAndFree()) End Function Public Overrides ReadOnly Property ContainingModule As ModuleSymbol Get Return _containingModule End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Linq Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class SynthesizedPrivateImplementationDetailsSharedConstructor Inherits SynthesizedGlobalMethodBase Private ReadOnly _containingModule As SourceModuleSymbol Private ReadOnly _privateImplementationType As PrivateImplementationDetails Private ReadOnly _voidType As TypeSymbol Friend Sub New( containingModule As SourceModuleSymbol, privateImplementationType As PrivateImplementationDetails, voidType As NamedTypeSymbol ) MyBase.New(containingModule, WellKnownMemberNames.StaticConstructorName, privateImplementationType) _containingModule = containingModule _privateImplementationType = privateImplementationType _voidType = voidType End Sub Public Overrides ReadOnly Property IsSub As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return _voidType End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.SharedConstructor End Get End Property Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock methodBodyBinder = Nothing Dim factory As New SyntheticBoundNodeFactory(Me, Me, VisualBasicSyntaxTree.Dummy.GetRoot(), compilationState, diagnostics) Dim body As ArrayBuilder(Of BoundStatement) = ArrayBuilder(Of BoundStatement).GetInstance() ' Initialize the payload root for each kind of dynamic analysis instrumentation. ' A payload root is an array of arrays of per-method instrumentation payloads. ' For each kind of instrumentation: ' ' payloadRoot = New T(MaximumMethodDefIndex)() {} ' ' where T Is the type of the payload at each instrumentation point, and MaximumMethodDefIndex is the ' index portion of the greatest method definition token in the compilation. This guarantees that any ' method can use the index portion of its own method definition token as an index into the payload array. For Each payloadRoot As KeyValuePair(Of Integer, InstrumentationPayloadRootField) In _privateImplementationType.GetInstrumentationPayloadRoots() Dim analysisKind As Integer = payloadRoot.Key Dim payloadArrayType As ArrayTypeSymbol = DirectCast(payloadRoot.Value.Type.GetInternalSymbol(), ArrayTypeSymbol) body.Add( factory.Assignment( factory.InstrumentationPayloadRoot(analysisKind, payloadArrayType, isLValue:=True), factory.Array(payloadArrayType.ElementType, ImmutableArray.Create(factory.MaximumMethodDefIndex()), ImmutableArray(Of BoundExpression).Empty))) Next ' Initialize the module version ID (MVID) field. Dynamic instrumentation requires the MVID of the executing module, and this field makes that accessible. ' MVID = New Guid(ModuleVersionIdString) Dim guidConstructor As MethodSymbol = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Guid__ctor) If guidConstructor IsNot Nothing Then body.Add( factory.Assignment( factory.ModuleVersionId(isLValue:=True), factory.[New](guidConstructor, factory.ModuleVersionIdString()))) End If body.Add(factory.Return()) Return factory.Block(body.ToImmutableAndFree()) End Function Public Overrides ReadOnly Property ContainingModule As ModuleSymbol Get Return _containingModule End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/NuGet/Microsoft.NETCore.Compilers/Microsoft.NETCore.Compilers.Package.csproj
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <IsPackable>true</IsPackable> <NuspecPackageId>Microsoft.NETCore.Compilers</NuspecPackageId> <IncludeBuildOutput>false</IncludeBuildOutput> <DevelopmentDependency>true</DevelopmentDependency> <PackageDescription> Note: This package is deprecated. Please use Microsoft.Net.Compilers.Toolset instead CoreCLR-compatible versions of the C# and VB compilers for use in MSBuild. </PackageDescription> <TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);_GetFilesToPackage</TargetsForTfmSpecificContentInPackage> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Compilers\CSharp\csc\csc.csproj"/> <ProjectReference Include="..\..\Compilers\VisualBasic\vbc\vbc.csproj"/> <ProjectReference Include="..\..\Interactive\csi\csi.csproj"/> <ProjectReference Include="..\..\Compilers\Core\MSBuildTask\Microsoft.Build.Tasks.CodeAnalysis.csproj"/> <ProjectReference Include="..\..\Compilers\Server\VBCSCompiler\VBCSCompiler.csproj"/> </ItemGroup> <ItemGroup> <ProjectReference Update="@(ProjectReference)" Targets="Publish" ReferenceOutputAssembly="false" SkipGetTargetFrameworkProperties="true" SetTargetFramework="TargetFramework=$(TargetFramework)" /> </ItemGroup> <Target Name="_GetFilesToPackage" DependsOnTargets="InitializeCoreClrCompilerArtifacts"> <ItemGroup> <_File Include="@(CoreClrCompilerBuildArtifact)" TargetDir="build"/> <_File Include="@(CoreClrCompilerToolsArtifact)" TargetDir="tools"/> <_File Include="@(CoreClrCompilerBinArtifact)" TargetDir="tools\bincore"/> <_File Include="@(CoreClrCompilerBinRuntimesArtifact)" TargetDir="tools\bincore\runtimes"/> <_File Include="$(MSBuildProjectDirectory)\build\**\*.*" TargetDir="build" /> <TfmSpecificPackageFile Include="@(_File)" PackagePath="%(_File.TargetDir)\%(_File.RecursiveDir)%(_File.FileName)%(_File.Extension)"/> </ItemGroup> </Target> <Import Project="..\Microsoft.Net.Compilers.Toolset\CoreClrCompilerArtifacts.targets"/> </Project>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <IsPackable>true</IsPackable> <NuspecPackageId>Microsoft.NETCore.Compilers</NuspecPackageId> <IncludeBuildOutput>false</IncludeBuildOutput> <DevelopmentDependency>true</DevelopmentDependency> <PackageDescription> Note: This package is deprecated. Please use Microsoft.Net.Compilers.Toolset instead CoreCLR-compatible versions of the C# and VB compilers for use in MSBuild. </PackageDescription> <TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);_GetFilesToPackage</TargetsForTfmSpecificContentInPackage> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Compilers\CSharp\csc\csc.csproj"/> <ProjectReference Include="..\..\Compilers\VisualBasic\vbc\vbc.csproj"/> <ProjectReference Include="..\..\Interactive\csi\csi.csproj"/> <ProjectReference Include="..\..\Compilers\Core\MSBuildTask\Microsoft.Build.Tasks.CodeAnalysis.csproj"/> <ProjectReference Include="..\..\Compilers\Server\VBCSCompiler\VBCSCompiler.csproj"/> </ItemGroup> <ItemGroup> <ProjectReference Update="@(ProjectReference)" Targets="Publish" ReferenceOutputAssembly="false" SkipGetTargetFrameworkProperties="true" SetTargetFramework="TargetFramework=$(TargetFramework)" /> </ItemGroup> <Target Name="_GetFilesToPackage" DependsOnTargets="InitializeCoreClrCompilerArtifacts"> <ItemGroup> <_File Include="@(CoreClrCompilerBuildArtifact)" TargetDir="build"/> <_File Include="@(CoreClrCompilerToolsArtifact)" TargetDir="tools"/> <_File Include="@(CoreClrCompilerBinArtifact)" TargetDir="tools\bincore"/> <_File Include="@(CoreClrCompilerBinRuntimesArtifact)" TargetDir="tools\bincore\runtimes"/> <_File Include="$(MSBuildProjectDirectory)\build\**\*.*" TargetDir="build" /> <TfmSpecificPackageFile Include="@(_File)" PackagePath="%(_File.TargetDir)\%(_File.RecursiveDir)%(_File.FileName)%(_File.Extension)"/> </ItemGroup> </Target> <Import Project="..\Microsoft.Net.Compilers.Toolset\CoreClrCompilerArtifacts.targets"/> </Project>
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicSyntaxGenerator/VisualBasicSyntaxGenerator.vbproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <Platform Condition="'$(Platform)' == ''">x64</Platform> <PlatformTarget>x64</PlatformTarget> <Platforms>x64</Platforms> <OutputType>Exe</OutputType> <StartupObject>Microsoft.CodeAnalysis.VisualBasic.Internal.VBSyntaxGenerator.Program</StartupObject> <RootNamespace>Microsoft.CodeAnalysis.VisualBasic.Internal.VBSyntaxGenerator</RootNamespace> <AssemblyName>VBSyntaxGenerator</AssemblyName> <OptionStrict>Off</OptionStrict> <AutoGenerateBindingRedirects>True</AutoGenerateBindingRedirects> <TargetFramework>netcoreapp3.1</TargetFramework> <IsShipping>false</IsShipping> </PropertyGroup> <ItemGroup> <Compile Include="..\..\..\..\..\Compilers\VisualBasic\Portable\Declarations\DeclarationModifiers.vb" Link="Grammar\DeclarationModifiers.vb" /> <Compile Include="..\..\..\..\..\Compilers\VisualBasic\Portable\Syntax\SyntaxKind.vb" Link="Grammar\SyntaxKind.vb" /> </ItemGroup> <ItemGroup> <Import Include="System.Collections.ObjectModel" /> <Import Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Content Include="..\..\..\..\..\Compilers\VisualBasic\Portable\Syntax\Syntax.xml"> <Link>XML\Syntax.xml</Link> </Content> </ItemGroup> <ItemGroup> <EmbeddedResource Include="VBSyntaxModelSchema.xsd"> <LogicalName>VBSyntaxModelSchema.xsd</LogicalName> </EmbeddedResource> </ItemGroup> <ItemGroup> <None Include="..\..\..\..\..\Compilers\VisualBasic\Portable\Generated\VisualBasic.Grammar.g4" Link="Grammar\VisualBasic.Grammar.g4" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <Platform Condition="'$(Platform)' == ''">x64</Platform> <PlatformTarget>x64</PlatformTarget> <Platforms>x64</Platforms> <OutputType>Exe</OutputType> <StartupObject>Microsoft.CodeAnalysis.VisualBasic.Internal.VBSyntaxGenerator.Program</StartupObject> <RootNamespace>Microsoft.CodeAnalysis.VisualBasic.Internal.VBSyntaxGenerator</RootNamespace> <AssemblyName>VBSyntaxGenerator</AssemblyName> <OptionStrict>Off</OptionStrict> <AutoGenerateBindingRedirects>True</AutoGenerateBindingRedirects> <TargetFramework>netcoreapp3.1</TargetFramework> <IsShipping>false</IsShipping> </PropertyGroup> <ItemGroup> <Compile Include="..\..\..\..\..\Compilers\VisualBasic\Portable\Declarations\DeclarationModifiers.vb" Link="Grammar\DeclarationModifiers.vb" /> <Compile Include="..\..\..\..\..\Compilers\VisualBasic\Portable\Syntax\SyntaxKind.vb" Link="Grammar\SyntaxKind.vb" /> </ItemGroup> <ItemGroup> <Import Include="System.Collections.ObjectModel" /> <Import Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Content Include="..\..\..\..\..\Compilers\VisualBasic\Portable\Syntax\Syntax.xml"> <Link>XML\Syntax.xml</Link> </Content> </ItemGroup> <ItemGroup> <EmbeddedResource Include="VBSyntaxModelSchema.xsd"> <LogicalName>VBSyntaxModelSchema.xsd</LogicalName> </EmbeddedResource> </ItemGroup> <ItemGroup> <None Include="..\..\..\..\..\Compilers\VisualBasic\Portable\Generated\VisualBasic.Grammar.g4" Link="Grammar\VisualBasic.Grammar.g4" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AbstractSpeculationAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { /// <summary> /// Helper class to analyze the semantic effects of a speculated syntax node replacement on the parenting nodes. /// Given an expression node from a syntax tree and a new expression from a different syntax tree, /// it replaces the expression with the new expression to create a speculated syntax tree. /// It uses the original tree's semantic model to create a speculative semantic model and verifies that /// the syntax replacement doesn't break the semantics of any parenting nodes of the original expression. /// </summary> internal abstract class AbstractSpeculationAnalyzer< TExpressionSyntax, TTypeSyntax, TAttributeSyntax, TArgumentSyntax, TForEachStatementSyntax, TThrowStatementSyntax, TConversion> where TExpressionSyntax : SyntaxNode where TTypeSyntax : TExpressionSyntax where TAttributeSyntax : SyntaxNode where TArgumentSyntax : SyntaxNode where TForEachStatementSyntax : SyntaxNode where TThrowStatementSyntax : SyntaxNode where TConversion : struct { private readonly TExpressionSyntax _expression; private readonly TExpressionSyntax _newExpressionForReplace; private readonly SemanticModel _semanticModel; private readonly CancellationToken _cancellationToken; private readonly bool _skipVerificationForReplacedNode; private readonly bool _failOnOverloadResolutionFailuresInOriginalCode; private readonly bool _isNewSemanticModelSpeculativeModel; private SyntaxNode? _lazySemanticRootOfOriginalExpression; private TExpressionSyntax? _lazyReplacedExpression; private SyntaxNode? _lazySemanticRootOfReplacedExpression; private SemanticModel? _lazySpeculativeSemanticModel; /// <summary> /// Creates a semantic analyzer for speculative syntax replacement. /// </summary> /// <param name="expression">Original expression to be replaced.</param> /// <param name="newExpression">New expression to replace the original expression.</param> /// <param name="semanticModel">Semantic model of <paramref name="expression"/> node's syntax tree.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <param name="skipVerificationForReplacedNode"> /// True if semantic analysis should be skipped for the replaced node and performed starting from parent of the original and replaced nodes. /// This could be the case when custom verifications are required to be done by the caller or /// semantics of the replaced expression are different from the original expression. /// </param> /// <param name="failOnOverloadResolutionFailuresInOriginalCode"> /// True if semantic analysis should fail when any of the invocation expression ancestors of <paramref name="expression"/> in original code has overload resolution failures. /// </param> public AbstractSpeculationAnalyzer( TExpressionSyntax expression, TExpressionSyntax newExpression, SemanticModel semanticModel, CancellationToken cancellationToken, bool skipVerificationForReplacedNode = false, bool failOnOverloadResolutionFailuresInOriginalCode = false) { _expression = expression; _newExpressionForReplace = newExpression; _semanticModel = semanticModel; _cancellationToken = cancellationToken; _skipVerificationForReplacedNode = skipVerificationForReplacedNode; _failOnOverloadResolutionFailuresInOriginalCode = failOnOverloadResolutionFailuresInOriginalCode; _isNewSemanticModelSpeculativeModel = true; _lazyReplacedExpression = null; _lazySemanticRootOfOriginalExpression = null; _lazySemanticRootOfReplacedExpression = null; _lazySpeculativeSemanticModel = null; } /// <summary> /// Original expression to be replaced. /// </summary> public TExpressionSyntax OriginalExpression => _expression; /// <summary> /// First ancestor of <see cref="OriginalExpression"/> which is either a statement, attribute, constructor initializer, /// field initializer, default parameter initializer or type syntax node. /// It serves as the root node for all semantic analysis for this syntax replacement. /// </summary> public SyntaxNode SemanticRootOfOriginalExpression { get { if (_lazySemanticRootOfOriginalExpression == null) { _lazySemanticRootOfOriginalExpression = GetSemanticRootForSpeculation(this.OriginalExpression); RoslynDebug.AssertNotNull(_lazySemanticRootOfOriginalExpression); } return _lazySemanticRootOfOriginalExpression; } } /// <summary> /// Semantic model for the syntax tree corresponding to <see cref="OriginalExpression"/> /// </summary> public SemanticModel OriginalSemanticModel => _semanticModel; /// <summary> /// Node which replaces the <see cref="OriginalExpression"/>. /// Note that this node is a cloned version of <see cref="_newExpressionForReplace"/> node, which has been re-parented /// under the node to be speculated, i.e. <see cref="SemanticRootOfReplacedExpression"/>. /// </summary> public TExpressionSyntax ReplacedExpression { get { EnsureReplacedExpressionAndSemanticRoot(); return _lazyReplacedExpression; } } /// <summary> /// Node created by replacing <see cref="OriginalExpression"/> under <see cref="SemanticRootOfOriginalExpression"/> node. /// This node is used as the argument to the GetSpeculativeSemanticModel API and serves as the root node for all /// semantic analysis of the speculated tree. /// </summary> public SyntaxNode SemanticRootOfReplacedExpression { get { EnsureReplacedExpressionAndSemanticRoot(); return _lazySemanticRootOfReplacedExpression; } } /// <summary> /// Speculative semantic model used for analyzing the semantics of the new tree. /// </summary> public SemanticModel SpeculativeSemanticModel { get { EnsureSpeculativeSemanticModel(); return _lazySpeculativeSemanticModel; } } public CancellationToken CancellationToken => _cancellationToken; protected abstract SyntaxNode GetSemanticRootForSpeculation(TExpressionSyntax expression); protected virtual SyntaxNode GetSemanticRootOfReplacedExpression(SyntaxNode semanticRootOfOriginalExpression, TExpressionSyntax annotatedReplacedExpression) => semanticRootOfOriginalExpression.ReplaceNode(this.OriginalExpression, annotatedReplacedExpression); [MemberNotNull(nameof(_lazySemanticRootOfReplacedExpression), nameof(_lazyReplacedExpression))] private void EnsureReplacedExpressionAndSemanticRoot() { if (_lazySemanticRootOfReplacedExpression == null) { // Because the new expression will change identity once we replace the old // expression in its parent, we annotate it here to allow us to get back to // it after replace. var annotation = new SyntaxAnnotation(); var annotatedExpression = _newExpressionForReplace.WithAdditionalAnnotations(annotation); _lazySemanticRootOfReplacedExpression = GetSemanticRootOfReplacedExpression(this.SemanticRootOfOriginalExpression, annotatedExpression); _lazyReplacedExpression = (TExpressionSyntax)_lazySemanticRootOfReplacedExpression.GetAnnotatedNodesAndTokens(annotation).Single().AsNode()!; } else { RoslynDebug.AssertNotNull(_lazyReplacedExpression); } } [Conditional("DEBUG")] protected abstract void ValidateSpeculativeSemanticModel(SemanticModel speculativeSemanticModel, SyntaxNode nodeToSpeculate); [MemberNotNull(nameof(_lazySpeculativeSemanticModel))] private void EnsureSpeculativeSemanticModel() { if (_lazySpeculativeSemanticModel == null) { var nodeToSpeculate = this.SemanticRootOfReplacedExpression; _lazySpeculativeSemanticModel = CreateSpeculativeSemanticModel(this.SemanticRootOfOriginalExpression, nodeToSpeculate, _semanticModel); ValidateSpeculativeSemanticModel(_lazySpeculativeSemanticModel, nodeToSpeculate); } } protected abstract SemanticModel CreateSpeculativeSemanticModel(SyntaxNode originalNode, SyntaxNode nodeToSpeculate, SemanticModel semanticModel); #region Semantic comparison helpers protected virtual bool ReplacementIntroducesErrorType(TExpressionSyntax originalExpression, TExpressionSyntax newExpression) { RoslynDebug.AssertNotNull(originalExpression); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalExpression)); RoslynDebug.AssertNotNull(newExpression); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newExpression)); var originalTypeInfo = this.OriginalSemanticModel.GetTypeInfo(originalExpression); var newTypeInfo = this.SpeculativeSemanticModel.GetTypeInfo(newExpression); if (originalTypeInfo.Type == null) { return false; } return newTypeInfo.Type == null || (newTypeInfo.Type.IsErrorType() && !originalTypeInfo.Type.IsErrorType()); } protected bool TypesAreCompatible(TExpressionSyntax originalExpression, TExpressionSyntax newExpression) { RoslynDebug.AssertNotNull(originalExpression); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalExpression)); RoslynDebug.AssertNotNull(newExpression); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newExpression)); var originalTypeInfo = this.OriginalSemanticModel.GetTypeInfo(originalExpression); var newTypeInfo = this.SpeculativeSemanticModel.GetTypeInfo(newExpression); return SymbolsAreCompatible(originalTypeInfo.Type, newTypeInfo.Type); } protected bool ConvertedTypesAreCompatible(TExpressionSyntax originalExpression, TExpressionSyntax newExpression) { RoslynDebug.AssertNotNull(originalExpression); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalExpression)); RoslynDebug.AssertNotNull(newExpression); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newExpression)); var originalTypeInfo = this.OriginalSemanticModel.GetTypeInfo(originalExpression); var newTypeInfo = this.SpeculativeSemanticModel.GetTypeInfo(newExpression); return SymbolsAreCompatible(originalTypeInfo.ConvertedType, newTypeInfo.ConvertedType); } protected bool ImplicitConversionsAreCompatible(TExpressionSyntax originalExpression, TExpressionSyntax newExpression) { RoslynDebug.AssertNotNull(originalExpression); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalExpression)); RoslynDebug.AssertNotNull(newExpression); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newExpression)); return ConversionsAreCompatible(this.OriginalSemanticModel, originalExpression, this.SpeculativeSemanticModel, newExpression); } private bool ImplicitConversionsAreCompatible(TExpressionSyntax originalExpression, ITypeSymbol originalTargetType, TExpressionSyntax newExpression, ITypeSymbol newTargetType) { RoslynDebug.AssertNotNull(originalExpression); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalExpression)); RoslynDebug.AssertNotNull(newExpression); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newExpression)); RoslynDebug.AssertNotNull(originalTargetType); RoslynDebug.AssertNotNull(newTargetType); return ConversionsAreCompatible(originalExpression, originalTargetType, newExpression, newTargetType); } protected abstract bool ConversionsAreCompatible(SemanticModel model1, TExpressionSyntax expression1, SemanticModel model2, TExpressionSyntax expression2); protected abstract bool ConversionsAreCompatible(TExpressionSyntax originalExpression, ITypeSymbol originalTargetType, TExpressionSyntax newExpression, ITypeSymbol newTargetType); protected bool SymbolsAreCompatible(SyntaxNode originalNode, SyntaxNode newNode, bool requireNonNullSymbols = false) { RoslynDebug.AssertNotNull(originalNode); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalNode)); RoslynDebug.AssertNotNull(newNode); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newNode)); var originalSymbolInfo = this.OriginalSemanticModel.GetSymbolInfo(originalNode); var newSymbolInfo = this.SpeculativeSemanticModel.GetSymbolInfo(newNode); return SymbolInfosAreCompatible(originalSymbolInfo, newSymbolInfo, requireNonNullSymbols); } public static bool SymbolInfosAreCompatible(SymbolInfo originalSymbolInfo, SymbolInfo newSymbolInfo, bool performEquivalenceCheck, bool requireNonNullSymbols = false) { return originalSymbolInfo.CandidateReason == newSymbolInfo.CandidateReason && SymbolsAreCompatibleCore(originalSymbolInfo.Symbol, newSymbolInfo.Symbol, performEquivalenceCheck, requireNonNullSymbols); } protected bool SymbolInfosAreCompatible(SymbolInfo originalSymbolInfo, SymbolInfo newSymbolInfo, bool requireNonNullSymbols = false) => SymbolInfosAreCompatible(originalSymbolInfo, newSymbolInfo, performEquivalenceCheck: !_isNewSemanticModelSpeculativeModel, requireNonNullSymbols: requireNonNullSymbols); protected bool SymbolsAreCompatible(ISymbol? symbol, ISymbol? newSymbol, bool requireNonNullSymbols = false) => SymbolsAreCompatibleCore(symbol, newSymbol, performEquivalenceCheck: !_isNewSemanticModelSpeculativeModel, requireNonNullSymbols: requireNonNullSymbols); private static bool SymbolsAreCompatibleCore( ISymbol? symbol, ISymbol? newSymbol, bool performEquivalenceCheck, bool requireNonNullSymbols = false) { if (symbol == null && newSymbol == null) { return !requireNonNullSymbols; } if (symbol == null || newSymbol == null) { return false; } if (symbol.IsReducedExtension()) { symbol = ((IMethodSymbol)symbol).GetConstructedReducedFrom()!; } if (newSymbol.IsReducedExtension()) { newSymbol = ((IMethodSymbol)newSymbol).GetConstructedReducedFrom()!; } // TODO: Lambda function comparison performs syntax equality, hence is non-trivial to compare lambda methods across different compilations. // For now, just assume they are equal. if (symbol.IsAnonymousFunction()) { return newSymbol.IsAnonymousFunction(); } if (performEquivalenceCheck) { // We are comparing symbols across two semantic models (where neither is the speculative model of other one). // We will use the SymbolEquivalenceComparer to check if symbols are equivalent. return CompareAcrossSemanticModels(symbol, newSymbol); } if (symbol.Equals(newSymbol, SymbolEqualityComparer.IncludeNullability)) { return true; } if (symbol is IMethodSymbol methodSymbol && newSymbol is IMethodSymbol newMethodSymbol) { // If we have local functions, we can't use normal symbol equality for them (since that checks locations). // Have to defer to SymbolEquivalence instead. if (methodSymbol.MethodKind == MethodKind.LocalFunction && newMethodSymbol.MethodKind == MethodKind.LocalFunction) return CompareAcrossSemanticModels(methodSymbol, newMethodSymbol); // Handle equivalence of special built-in comparison operators between enum types and // it's underlying enum type. if (methodSymbol.TryGetPredefinedComparisonOperator(out var originalOp) && newMethodSymbol.TryGetPredefinedComparisonOperator(out var newOp) && originalOp == newOp) { var type = methodSymbol.ContainingType; var newType = newMethodSymbol.ContainingType; if (type != null && newType != null) { if (EnumTypesAreCompatible(type, newType) || EnumTypesAreCompatible(newType, type)) { return true; } } } } return false; } private static bool CompareAcrossSemanticModels(ISymbol symbol, ISymbol newSymbol) { // SymbolEquivalenceComparer performs Location equality checks for locals, labels, range-variables and local // functions. As we are comparing symbols from different semantic models, locations will differ. Hence // perform minimal checks for these symbol kinds. if (symbol.Kind != newSymbol.Kind) return false; if (symbol is ILocalSymbol localSymbol && newSymbol is ILocalSymbol newLocalSymbol) { return newSymbol.IsImplicitlyDeclared == symbol.IsImplicitlyDeclared && symbol.Name == newSymbol.Name && CompareAcrossSemanticModels(localSymbol.Type, newLocalSymbol.Type); } if (symbol is ILabelSymbol && newSymbol is ILabelSymbol) return symbol.Name == newSymbol.Name; if (symbol is IRangeVariableSymbol && newSymbol is IRangeVariableSymbol) return symbol.Name == newSymbol.Name; if (symbol is IParameterSymbol parameterSymbol && newSymbol is IParameterSymbol newParameterSymbol && parameterSymbol.ContainingSymbol.IsAnonymousOrLocalFunction() && newParameterSymbol.ContainingSymbol.IsAnonymousOrLocalFunction()) { return symbol.Name == newSymbol.Name && parameterSymbol.IsRefOrOut() == newParameterSymbol.IsRefOrOut() && CompareAcrossSemanticModels(parameterSymbol.Type, newParameterSymbol.Type); } if (symbol is IMethodSymbol methodSymbol && newSymbol is IMethodSymbol newMethodSymbol && methodSymbol.IsLocalFunction() && newMethodSymbol.IsLocalFunction()) { return symbol.Name == newSymbol.Name && methodSymbol.Parameters.Length == newMethodSymbol.Parameters.Length && CompareAcrossSemanticModels(methodSymbol.ReturnType, newMethodSymbol.ReturnType) && methodSymbol.Parameters.Zip(newMethodSymbol.Parameters, (p1, p2) => (p1, p2)).All( t => CompareAcrossSemanticModels(t.p1, t.p2)); } return SymbolEquivalenceComparer.Instance.Equals(symbol, newSymbol); } private static bool EnumTypesAreCompatible(INamedTypeSymbol type1, INamedTypeSymbol type2) => type1.IsEnumType() && type1.EnumUnderlyingType?.SpecialType == type2.SpecialType; #endregion /// <summary> /// Determines whether performing the given syntax replacement will change the semantics of any parenting expressions /// by performing a bottom up walk from the <see cref="OriginalExpression"/> up to <see cref="SemanticRootOfOriginalExpression"/> /// in the original tree and simultaneously walking bottom up from <see cref="ReplacedExpression"/> up to <see cref="SemanticRootOfReplacedExpression"/> /// in the speculated syntax tree and performing appropriate semantic comparisons. /// </summary> public bool ReplacementChangesSemantics() { if (this.SemanticRootOfOriginalExpression is TTypeSyntax) { var originalType = (TTypeSyntax)this.OriginalExpression; var newType = (TTypeSyntax)this.ReplacedExpression; return ReplacementBreaksTypeResolution(originalType, newType, useSpeculativeModel: false); } return ReplacementChangesSemantics( currentOriginalNode: this.OriginalExpression, currentReplacedNode: this.ReplacedExpression, originalRoot: this.SemanticRootOfOriginalExpression, skipVerificationForCurrentNode: _skipVerificationForReplacedNode); } protected abstract bool IsParenthesizedExpression([NotNullWhen(true)] SyntaxNode? node); protected bool ReplacementChangesSemantics(SyntaxNode currentOriginalNode, SyntaxNode currentReplacedNode, SyntaxNode originalRoot, bool skipVerificationForCurrentNode) { if (this.SpeculativeSemanticModel == null) { // This is possible for some broken code scenarios with parse errors, bail out gracefully here. return true; } SyntaxNode? previousOriginalNode = null, previousReplacedNode = null; while (true) { if (!skipVerificationForCurrentNode && ReplacementChangesSemanticsForNode( currentOriginalNode, currentReplacedNode, previousOriginalNode, previousReplacedNode)) { return true; } if (currentOriginalNode == originalRoot) { break; } RoslynDebug.AssertNotNull(currentOriginalNode.Parent); RoslynDebug.AssertNotNull(currentReplacedNode.Parent); previousOriginalNode = currentOriginalNode; previousReplacedNode = currentReplacedNode; currentOriginalNode = currentOriginalNode.Parent; currentReplacedNode = currentReplacedNode.Parent; skipVerificationForCurrentNode = skipVerificationForCurrentNode && IsParenthesizedExpression(currentReplacedNode); } return false; } /// <summary> /// Checks whether the semantic symbols for the <see cref="OriginalExpression"/> and <see cref="ReplacedExpression"/> are non-null and compatible. /// </summary> /// <returns></returns> public bool SymbolsForOriginalAndReplacedNodesAreCompatible() { if (this.SpeculativeSemanticModel == null) { // This is possible for some broken code scenarios with parse errors, bail out gracefully here. return false; } return SymbolsAreCompatible(this.OriginalExpression, this.ReplacedExpression, requireNonNullSymbols: true); } protected abstract bool ReplacementChangesSemanticsForNodeLanguageSpecific(SyntaxNode currentOriginalNode, SyntaxNode currentReplacedNode, SyntaxNode? previousOriginalNode, SyntaxNode? previousReplacedNode); private bool ReplacementChangesSemanticsForNode(SyntaxNode currentOriginalNode, SyntaxNode currentReplacedNode, SyntaxNode? previousOriginalNode, SyntaxNode? previousReplacedNode) { Debug.Assert(previousOriginalNode == null || previousOriginalNode.Parent == currentOriginalNode); Debug.Assert(previousReplacedNode == null || previousReplacedNode.Parent == currentReplacedNode); if (ExpressionMightReferenceMember(currentOriginalNode)) { // If replacing the node will result in a change in overload resolution, we won't remove it. var originalExpression = (TExpressionSyntax)currentOriginalNode; var newExpression = (TExpressionSyntax)currentReplacedNode; if (ReplacementBreaksExpression(originalExpression, newExpression)) { return true; } if (ReplacementBreaksSystemObjectMethodResolution(currentOriginalNode, currentReplacedNode, previousOriginalNode, previousReplacedNode)) { return true; } return !ImplicitConversionsAreCompatible(originalExpression, newExpression); } else if (currentOriginalNode is TForEachStatementSyntax originalForEachStatement) { var newForEachStatement = (TForEachStatementSyntax)currentReplacedNode; return ReplacementBreaksForEachStatement(originalForEachStatement, newForEachStatement); } else if (currentOriginalNode is TAttributeSyntax originalAttribute) { var newAttribute = (TAttributeSyntax)currentReplacedNode; return ReplacementBreaksAttribute(originalAttribute, newAttribute); } else if (currentOriginalNode is TThrowStatementSyntax originalThrowStatement) { var newThrowStatement = (TThrowStatementSyntax)currentReplacedNode; return ReplacementBreaksThrowStatement(originalThrowStatement, newThrowStatement); } else if (ReplacementChangesSemanticsForNodeLanguageSpecific(currentOriginalNode, currentReplacedNode, previousOriginalNode, previousReplacedNode)) { return true; } if (currentOriginalNode is TTypeSyntax originalType) { var newType = (TTypeSyntax)currentReplacedNode; return ReplacementBreaksTypeResolution(originalType, newType); } else if (currentOriginalNode is TExpressionSyntax originalExpression) { var newExpression = (TExpressionSyntax)currentReplacedNode; if (!ImplicitConversionsAreCompatible(originalExpression, newExpression) || ReplacementIntroducesErrorType(originalExpression, newExpression)) { return true; } } return false; } /// <summary> /// Determine if removing the cast could cause the semantics of System.Object method call to change. /// E.g. Dim b = CStr(1).GetType() is necessary, but the GetType method symbol info resolves to the same with or without the cast. /// </summary> private bool ReplacementBreaksSystemObjectMethodResolution(SyntaxNode currentOriginalNode, SyntaxNode currentReplacedNode, [NotNullWhen(true)] SyntaxNode? previousOriginalNode, [NotNullWhen(true)] SyntaxNode? previousReplacedNode) { if (previousOriginalNode != null && previousReplacedNode != null) { var originalExpressionSymbol = this.OriginalSemanticModel.GetSymbolInfo(currentOriginalNode).Symbol; var replacedExpressionSymbol = this.SpeculativeSemanticModel.GetSymbolInfo(currentReplacedNode).Symbol; if (IsSymbolSystemObjectInstanceMethod(originalExpressionSymbol) && IsSymbolSystemObjectInstanceMethod(replacedExpressionSymbol)) { var previousOriginalType = this.OriginalSemanticModel.GetTypeInfo(previousOriginalNode).Type; var previousReplacedType = this.SpeculativeSemanticModel.GetTypeInfo(previousReplacedNode).Type; if (previousReplacedType != null && previousOriginalType != null) { return !previousReplacedType.InheritsFromOrEquals(previousOriginalType); } } } return false; } /// <summary> /// Determines if the symbol is a non-overridable, non static method on System.Object (e.g. GetType) /// </summary> private static bool IsSymbolSystemObjectInstanceMethod([NotNullWhen(true)] ISymbol? symbol) { return symbol != null && symbol.IsKind(SymbolKind.Method) && symbol.ContainingType.SpecialType == SpecialType.System_Object && !symbol.IsOverridable() && !symbol.IsStaticType(); } private bool ReplacementBreaksAttribute(TAttributeSyntax attribute, TAttributeSyntax newAttribute) { var attributeSym = this.OriginalSemanticModel.GetSymbolInfo(attribute).Symbol; var newAttributeSym = this.SpeculativeSemanticModel.GetSymbolInfo(newAttribute).Symbol; return !SymbolsAreCompatible(attributeSym, newAttributeSym); } protected abstract TExpressionSyntax GetForEachStatementExpression(TForEachStatementSyntax forEachStatement); protected abstract bool IsForEachTypeInferred(TForEachStatementSyntax forEachStatement, SemanticModel semanticModel); private bool ReplacementBreaksForEachStatement(TForEachStatementSyntax forEachStatement, TForEachStatementSyntax newForEachStatement) { var forEachExpression = GetForEachStatementExpression(forEachStatement); if (forEachExpression.IsMissing || !forEachExpression.Span.Contains(_expression.SpanStart)) { return false; } // inferred variable type compatible if (IsForEachTypeInferred(forEachStatement, _semanticModel)) { var local = (ILocalSymbol)_semanticModel.GetRequiredDeclaredSymbol(forEachStatement, _cancellationToken); var newLocal = (ILocalSymbol)this.SpeculativeSemanticModel.GetRequiredDeclaredSymbol(newForEachStatement, _cancellationToken); if (!SymbolsAreCompatible(local.Type, newLocal.Type)) { return true; } } GetForEachSymbols(this.OriginalSemanticModel, forEachStatement, out var originalGetEnumerator, out var originalElementType); GetForEachSymbols(this.SpeculativeSemanticModel, newForEachStatement, out var newGetEnumerator, out var newElementType); var newForEachExpression = GetForEachStatementExpression(newForEachStatement); if (ReplacementBreaksForEachGetEnumerator(originalGetEnumerator, newGetEnumerator, newForEachExpression) || !ForEachConversionsAreCompatible(this.OriginalSemanticModel, forEachStatement, this.SpeculativeSemanticModel, newForEachStatement) || !SymbolsAreCompatible(originalElementType, newElementType)) { return true; } return false; } protected abstract bool ForEachConversionsAreCompatible(SemanticModel originalModel, TForEachStatementSyntax originalForEach, SemanticModel newModel, TForEachStatementSyntax newForEach); protected abstract void GetForEachSymbols(SemanticModel model, TForEachStatementSyntax forEach, out IMethodSymbol getEnumeratorMethod, out ITypeSymbol elementType); private bool ReplacementBreaksForEachGetEnumerator(IMethodSymbol getEnumerator, IMethodSymbol newGetEnumerator, TExpressionSyntax newForEachStatementExpression) { if (getEnumerator == null && newGetEnumerator == null) { return false; } if (getEnumerator == null || newGetEnumerator == null) { return true; } if (getEnumerator.ToSignatureDisplayString() != newGetEnumerator.ToSignatureDisplayString()) { // Note this is likely an interface member from IEnumerable but the new member may be a // GetEnumerator method on a specific type. if (getEnumerator.IsImplementableMember()) { var expressionType = this.SpeculativeSemanticModel.GetTypeInfo(newForEachStatementExpression, _cancellationToken).ConvertedType; if (expressionType != null) { var implementationMember = expressionType.FindImplementationForInterfaceMember(getEnumerator); if (implementationMember != null) { if (implementationMember.ToSignatureDisplayString() != newGetEnumerator.ToSignatureDisplayString()) { return false; } } } } return true; } return false; } protected abstract TExpressionSyntax GetThrowStatementExpression(TThrowStatementSyntax throwStatement); private bool ReplacementBreaksThrowStatement(TThrowStatementSyntax originalThrowStatement, TThrowStatementSyntax newThrowStatement) { var originalThrowExpression = GetThrowStatementExpression(originalThrowStatement); var originalThrowExpressionType = this.OriginalSemanticModel.GetTypeInfo(originalThrowExpression).Type; var newThrowExpression = GetThrowStatementExpression(newThrowStatement); var newThrowExpressionType = this.SpeculativeSemanticModel.GetTypeInfo(newThrowExpression).Type; // C# language specification requires that type of the expression passed to ThrowStatement is or derives from System.Exception. return originalThrowExpressionType.IsOrDerivesFromExceptionType(this.OriginalSemanticModel.Compilation) != newThrowExpressionType.IsOrDerivesFromExceptionType(this.SpeculativeSemanticModel.Compilation); } protected abstract bool IsInNamespaceOrTypeContext(TExpressionSyntax node); private bool ReplacementBreaksTypeResolution(TTypeSyntax type, TTypeSyntax newType, bool useSpeculativeModel = true) { var symbol = this.OriginalSemanticModel.GetSymbolInfo(type).Symbol; ISymbol? newSymbol; if (useSpeculativeModel) { newSymbol = this.SpeculativeSemanticModel.GetSymbolInfo(newType, _cancellationToken).Symbol; } else { var bindingOption = IsInNamespaceOrTypeContext(type) ? SpeculativeBindingOption.BindAsTypeOrNamespace : SpeculativeBindingOption.BindAsExpression; newSymbol = this.OriginalSemanticModel.GetSpeculativeSymbolInfo(type.SpanStart, newType, bindingOption).Symbol; } return symbol != null && !SymbolsAreCompatible(symbol, newSymbol); } protected abstract bool ExpressionMightReferenceMember([NotNullWhen(true)] SyntaxNode? node); private static bool IsDelegateInvoke(ISymbol symbol) { return symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).MethodKind == MethodKind.DelegateInvoke; } private static bool IsAnonymousDelegateInvoke(ISymbol symbol) { return IsDelegateInvoke(symbol) && symbol.ContainingType != null && symbol.ContainingType.IsAnonymousType(); } private bool ReplacementBreaksExpression(TExpressionSyntax expression, TExpressionSyntax newExpression) { var originalSymbolInfo = _semanticModel.GetSymbolInfo(expression); if (_failOnOverloadResolutionFailuresInOriginalCode && originalSymbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure) { return true; } var newSymbolInfo = this.SpeculativeSemanticModel.GetSymbolInfo(node: newExpression); var symbol = originalSymbolInfo.Symbol; var newSymbol = newSymbolInfo.Symbol; if (SymbolInfosAreCompatible(originalSymbolInfo, newSymbolInfo)) { // Original and new symbols for the invocation expression are compatible. // However, if the symbols are interface members and if the receiver symbol for one of the expressions is a possible ValueType type parameter, // and the other one is not, then there might be a boxing conversion at runtime which causes different runtime behavior. if (symbol.IsImplementableMember()) { if (IsReceiverNonUniquePossibleValueTypeParam(expression, this.OriginalSemanticModel) != IsReceiverNonUniquePossibleValueTypeParam(newExpression, this.SpeculativeSemanticModel)) { return true; } } return false; } if (symbol == null || newSymbol == null || originalSymbolInfo.CandidateReason != newSymbolInfo.CandidateReason) { return true; } if (newSymbol.IsOverride) { for (var overriddenMember = newSymbol.GetOverriddenMember(); overriddenMember != null; overriddenMember = overriddenMember.GetOverriddenMember()) { if (symbol.Equals(overriddenMember)) return !SymbolsHaveCompatibleParameterLists(symbol, newSymbol, expression); } } if (symbol.IsImplementableMember() && IsCompatibleInterfaceMemberImplementation( symbol, newSymbol, expression, newExpression, this.SpeculativeSemanticModel)) { return false; } // Allow speculated invocation expression to bind to a different method symbol if the method's containing type is a delegate type // which has a delegate variance conversion to/from the original method's containing delegate type. if (newSymbol.ContainingType.IsDelegateType() && symbol.ContainingType.IsDelegateType() && IsReferenceConversion(this.OriginalSemanticModel.Compilation, newSymbol.ContainingType, symbol.ContainingType)) { return false; } // Heuristic: If we now bind to an anonymous delegate's invoke method, assume that // this isn't a change in overload resolution. if (IsAnonymousDelegateInvoke(newSymbol)) { return false; } return true; } protected bool ReplacementBreaksCompoundAssignment( TExpressionSyntax originalLeft, TExpressionSyntax originalRight, TExpressionSyntax newLeft, TExpressionSyntax newRight) { var originalTargetType = this.OriginalSemanticModel.GetTypeInfo(originalLeft).Type; if (originalTargetType != null) { var newTargetType = this.SpeculativeSemanticModel.GetTypeInfo(newLeft).Type; return !SymbolsAreCompatible(originalTargetType, newTargetType) || !ImplicitConversionsAreCompatible(originalRight, originalTargetType, newRight, newTargetType!); } return false; } protected abstract bool IsReferenceConversion(Compilation model, ITypeSymbol sourceType, ITypeSymbol targetType); private bool IsCompatibleInterfaceMemberImplementation( ISymbol symbol, ISymbol newSymbol, TExpressionSyntax originalExpression, TExpressionSyntax newExpression, SemanticModel speculativeSemanticModel) { // In general, we don't want to remove casts to interfaces. It may have subtle changes in behavior, // especially if the types in question change in the future. For example, if a type becomes non-sealed or a // new interface impl is introduced, we may subtly break things. // // The only cases where we feel confident enough to elide the cast are: // // 1. When we have an Array/Delegate/Enum. These are such core types, and cannot be changed by teh user, // that we can trust their impls to not change. // 2. We have one of the builtin structs (like int). These are such core types, and cannot be changed by teh // user, that we can trust their impls to not change. // 3. if we have a struct and we know we have a fresh copy of it. In that case, boxing the struct to the // interface doesn't serve any purpose. var newSymbolContainingType = newSymbol.ContainingType; if (newSymbolContainingType == null) return false; var newReceiver = GetReceiver(newExpression); var newReceiverType = newReceiver != null ? speculativeSemanticModel.GetTypeInfo(newReceiver).ConvertedType : newSymbolContainingType; if (newReceiverType == null) return false; var implementationMember = newSymbolContainingType.FindImplementationForInterfaceMember(symbol); if (implementationMember == null) return false; if (!newSymbol.Equals(implementationMember)) return false; if (!SymbolsHaveCompatibleParameterLists(symbol, implementationMember, originalExpression)) return false; if (newReceiverType.IsValueType) { // Presume builtin value types are all immutable, and thus will have the same semantics when you call // interface members on them directly instead of through a boxed copy. if (newReceiverType.SpecialType != SpecialType.None) return true; // For non-builtins, only remove the boxing if we know we have a copy already. return newReceiver != null && IsReceiverUniqueInstance(newReceiver, speculativeSemanticModel); } return newSymbolContainingType.SpecialType == SpecialType.System_Array || newSymbolContainingType.SpecialType == SpecialType.System_Delegate || newSymbolContainingType.SpecialType == SpecialType.System_Enum || newSymbolContainingType.SpecialType == SpecialType.System_String; } private bool IsReceiverNonUniquePossibleValueTypeParam(TExpressionSyntax invocation, SemanticModel semanticModel) { var receiver = GetReceiver(invocation); if (receiver != null) { var receiverType = semanticModel.GetTypeInfo(receiver).Type; if (receiverType.IsKind(SymbolKind.TypeParameter) && !receiverType.IsReferenceType) { return !IsReceiverUniqueInstance(receiver, semanticModel); } } return false; } // Returns true if the given receiver expression for an invocation represents a unique copy of the underlying // object that is not referenced by any other variable. For example, if the receiver expression is produced by a // method call, property, or indexer, then it will be a fresh receiver in the case of value types. private static bool IsReceiverUniqueInstance(TExpressionSyntax receiver, SemanticModel semanticModel) { var receiverSymbol = semanticModel.GetSymbolInfo(receiver).GetAnySymbol(); if (receiverSymbol == null) return false; return receiverSymbol.IsKind(SymbolKind.Method) || receiverSymbol.IsIndexer() || receiverSymbol.IsKind(SymbolKind.Property); } protected abstract ImmutableArray<TArgumentSyntax> GetArguments(TExpressionSyntax expression); protected abstract TExpressionSyntax GetReceiver(TExpressionSyntax expression); private bool SymbolsHaveCompatibleParameterLists(ISymbol originalSymbol, ISymbol newSymbol, TExpressionSyntax originalInvocation) { if (originalSymbol.IsKind(SymbolKind.Method) || originalSymbol.IsIndexer()) { var specifiedArguments = GetArguments(originalInvocation); if (!specifiedArguments.IsDefault) { var symbolParameters = originalSymbol.GetParameters(); var newSymbolParameters = newSymbol.GetParameters(); return AreCompatibleParameterLists(specifiedArguments, symbolParameters, newSymbolParameters); } } return true; } protected abstract bool IsNamedArgument(TArgumentSyntax argument); protected abstract string GetNamedArgumentIdentifierValueText(TArgumentSyntax argument); private bool AreCompatibleParameterLists( ImmutableArray<TArgumentSyntax> specifiedArguments, ImmutableArray<IParameterSymbol> signature1Parameters, ImmutableArray<IParameterSymbol> signature2Parameters) { Debug.Assert(signature1Parameters.Length == signature2Parameters.Length); Debug.Assert(specifiedArguments.Length <= signature1Parameters.Length || (signature1Parameters.Length > 0 && !signature1Parameters.Last().IsParams)); if (signature1Parameters.Length != signature2Parameters.Length) { return false; } // If there aren't any parameters, we're OK. if (signature1Parameters.Length == 0) { return true; } // To ensure that the second parameter list is called in the same way as the // first, we need to use the specified arguments to bail out if... // // * A named argument doesn't have a corresponding parameter in the // in either parameter list, or... // // * A named argument matches a parameter that is in a different position // in the two parameter lists. // // After checking the specified arguments, we walk the unspecified parameters // in both parameter lists to ensure that they have matching default values. var specifiedParameters1 = new List<IParameterSymbol>(); var specifiedParameters2 = new List<IParameterSymbol>(); for (var i = 0; i < specifiedArguments.Length; i++) { var argument = specifiedArguments[i]; // Handle named argument if (IsNamedArgument(argument)) { var name = GetNamedArgumentIdentifierValueText(argument); var parameter1 = signature1Parameters.FirstOrDefault(p => p.Name == name); RoslynDebug.AssertNotNull(parameter1); var parameter2 = signature2Parameters.FirstOrDefault(p => p.Name == name); if (parameter2 == null) { return false; } if (signature1Parameters.IndexOf(parameter1) != signature2Parameters.IndexOf(parameter2)) { return false; } specifiedParameters1.Add(parameter1); specifiedParameters2.Add(parameter2); } else { // otherwise, treat the argument positionally, taking care to properly // handle params parameters. if (i < signature1Parameters.Length) { specifiedParameters1.Add(signature1Parameters[i]); specifiedParameters2.Add(signature2Parameters[i]); } } } // At this point, we can safely assume that specifiedParameters1 and signature2Parameters // contain parameters that appear at the same positions in their respective signatures // because we bailed out if named arguments referred to parameters at different positions. // // Now we walk the unspecified parameters to ensure that they have the same default // values. for (var i = 0; i < signature1Parameters.Length; i++) { var parameter1 = signature1Parameters[i]; if (specifiedParameters1.Contains(parameter1)) { continue; } var parameter2 = signature2Parameters[i]; Debug.Assert(parameter1.HasExplicitDefaultValue, "Expected all unspecified parameter to have default values"); Debug.Assert(parameter1.HasExplicitDefaultValue == parameter2.HasExplicitDefaultValue); if (parameter1.HasExplicitDefaultValue && parameter2.HasExplicitDefaultValue) { if (!object.Equals(parameter2.ExplicitDefaultValue, parameter1.ExplicitDefaultValue)) { return false; } if (object.Equals(parameter1.ExplicitDefaultValue, 0.0)) { RoslynDebug.Assert(object.Equals(parameter2.ExplicitDefaultValue, 0.0)); var isParam1DefaultValueNegativeZero = double.IsNegativeInfinity(1.0 / (double)parameter1.ExplicitDefaultValue); var isParam2DefaultValueNegativeZero = double.IsNegativeInfinity(1.0 / (double)parameter2.ExplicitDefaultValue); if (isParam1DefaultValueNegativeZero != isParam2DefaultValueNegativeZero) { return false; } } } } return true; } protected void GetConversions( TExpressionSyntax originalExpression, ITypeSymbol originalTargetType, TExpressionSyntax newExpression, ITypeSymbol newTargetType, out TConversion? originalConversion, out TConversion? newConversion) { originalConversion = null; newConversion = null; if (this.OriginalSemanticModel.GetTypeInfo(originalExpression).Type != null && this.SpeculativeSemanticModel.GetTypeInfo(newExpression).Type != null) { originalConversion = ClassifyConversion(this.OriginalSemanticModel, originalExpression, originalTargetType); newConversion = ClassifyConversion(this.SpeculativeSemanticModel, newExpression, newTargetType); } else { var originalConvertedTypeSymbol = this.OriginalSemanticModel.GetTypeInfo(originalExpression).ConvertedType; if (originalConvertedTypeSymbol != null) { originalConversion = ClassifyConversion(this.OriginalSemanticModel, originalConvertedTypeSymbol, originalTargetType); } var newConvertedTypeSymbol = this.SpeculativeSemanticModel.GetTypeInfo(newExpression).ConvertedType; if (newConvertedTypeSymbol != null) { newConversion = ClassifyConversion(this.SpeculativeSemanticModel, newConvertedTypeSymbol, newTargetType); } } } protected abstract TConversion ClassifyConversion(SemanticModel model, TExpressionSyntax expression, ITypeSymbol targetType); protected abstract TConversion ClassifyConversion(SemanticModel model, ITypeSymbol originalType, ITypeSymbol targetType); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { /// <summary> /// Helper class to analyze the semantic effects of a speculated syntax node replacement on the parenting nodes. /// Given an expression node from a syntax tree and a new expression from a different syntax tree, /// it replaces the expression with the new expression to create a speculated syntax tree. /// It uses the original tree's semantic model to create a speculative semantic model and verifies that /// the syntax replacement doesn't break the semantics of any parenting nodes of the original expression. /// </summary> internal abstract class AbstractSpeculationAnalyzer< TExpressionSyntax, TTypeSyntax, TAttributeSyntax, TArgumentSyntax, TForEachStatementSyntax, TThrowStatementSyntax, TConversion> where TExpressionSyntax : SyntaxNode where TTypeSyntax : TExpressionSyntax where TAttributeSyntax : SyntaxNode where TArgumentSyntax : SyntaxNode where TForEachStatementSyntax : SyntaxNode where TThrowStatementSyntax : SyntaxNode where TConversion : struct { private readonly TExpressionSyntax _expression; private readonly TExpressionSyntax _newExpressionForReplace; private readonly SemanticModel _semanticModel; private readonly CancellationToken _cancellationToken; private readonly bool _skipVerificationForReplacedNode; private readonly bool _failOnOverloadResolutionFailuresInOriginalCode; private readonly bool _isNewSemanticModelSpeculativeModel; private SyntaxNode? _lazySemanticRootOfOriginalExpression; private TExpressionSyntax? _lazyReplacedExpression; private SyntaxNode? _lazySemanticRootOfReplacedExpression; private SemanticModel? _lazySpeculativeSemanticModel; /// <summary> /// Creates a semantic analyzer for speculative syntax replacement. /// </summary> /// <param name="expression">Original expression to be replaced.</param> /// <param name="newExpression">New expression to replace the original expression.</param> /// <param name="semanticModel">Semantic model of <paramref name="expression"/> node's syntax tree.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <param name="skipVerificationForReplacedNode"> /// True if semantic analysis should be skipped for the replaced node and performed starting from parent of the original and replaced nodes. /// This could be the case when custom verifications are required to be done by the caller or /// semantics of the replaced expression are different from the original expression. /// </param> /// <param name="failOnOverloadResolutionFailuresInOriginalCode"> /// True if semantic analysis should fail when any of the invocation expression ancestors of <paramref name="expression"/> in original code has overload resolution failures. /// </param> public AbstractSpeculationAnalyzer( TExpressionSyntax expression, TExpressionSyntax newExpression, SemanticModel semanticModel, CancellationToken cancellationToken, bool skipVerificationForReplacedNode = false, bool failOnOverloadResolutionFailuresInOriginalCode = false) { _expression = expression; _newExpressionForReplace = newExpression; _semanticModel = semanticModel; _cancellationToken = cancellationToken; _skipVerificationForReplacedNode = skipVerificationForReplacedNode; _failOnOverloadResolutionFailuresInOriginalCode = failOnOverloadResolutionFailuresInOriginalCode; _isNewSemanticModelSpeculativeModel = true; _lazyReplacedExpression = null; _lazySemanticRootOfOriginalExpression = null; _lazySemanticRootOfReplacedExpression = null; _lazySpeculativeSemanticModel = null; } /// <summary> /// Original expression to be replaced. /// </summary> public TExpressionSyntax OriginalExpression => _expression; /// <summary> /// First ancestor of <see cref="OriginalExpression"/> which is either a statement, attribute, constructor initializer, /// field initializer, default parameter initializer or type syntax node. /// It serves as the root node for all semantic analysis for this syntax replacement. /// </summary> public SyntaxNode SemanticRootOfOriginalExpression { get { if (_lazySemanticRootOfOriginalExpression == null) { _lazySemanticRootOfOriginalExpression = GetSemanticRootForSpeculation(this.OriginalExpression); RoslynDebug.AssertNotNull(_lazySemanticRootOfOriginalExpression); } return _lazySemanticRootOfOriginalExpression; } } /// <summary> /// Semantic model for the syntax tree corresponding to <see cref="OriginalExpression"/> /// </summary> public SemanticModel OriginalSemanticModel => _semanticModel; /// <summary> /// Node which replaces the <see cref="OriginalExpression"/>. /// Note that this node is a cloned version of <see cref="_newExpressionForReplace"/> node, which has been re-parented /// under the node to be speculated, i.e. <see cref="SemanticRootOfReplacedExpression"/>. /// </summary> public TExpressionSyntax ReplacedExpression { get { EnsureReplacedExpressionAndSemanticRoot(); return _lazyReplacedExpression; } } /// <summary> /// Node created by replacing <see cref="OriginalExpression"/> under <see cref="SemanticRootOfOriginalExpression"/> node. /// This node is used as the argument to the GetSpeculativeSemanticModel API and serves as the root node for all /// semantic analysis of the speculated tree. /// </summary> public SyntaxNode SemanticRootOfReplacedExpression { get { EnsureReplacedExpressionAndSemanticRoot(); return _lazySemanticRootOfReplacedExpression; } } /// <summary> /// Speculative semantic model used for analyzing the semantics of the new tree. /// </summary> public SemanticModel SpeculativeSemanticModel { get { EnsureSpeculativeSemanticModel(); return _lazySpeculativeSemanticModel; } } public CancellationToken CancellationToken => _cancellationToken; protected abstract SyntaxNode GetSemanticRootForSpeculation(TExpressionSyntax expression); protected virtual SyntaxNode GetSemanticRootOfReplacedExpression(SyntaxNode semanticRootOfOriginalExpression, TExpressionSyntax annotatedReplacedExpression) => semanticRootOfOriginalExpression.ReplaceNode(this.OriginalExpression, annotatedReplacedExpression); [MemberNotNull(nameof(_lazySemanticRootOfReplacedExpression), nameof(_lazyReplacedExpression))] private void EnsureReplacedExpressionAndSemanticRoot() { if (_lazySemanticRootOfReplacedExpression == null) { // Because the new expression will change identity once we replace the old // expression in its parent, we annotate it here to allow us to get back to // it after replace. var annotation = new SyntaxAnnotation(); var annotatedExpression = _newExpressionForReplace.WithAdditionalAnnotations(annotation); _lazySemanticRootOfReplacedExpression = GetSemanticRootOfReplacedExpression(this.SemanticRootOfOriginalExpression, annotatedExpression); _lazyReplacedExpression = (TExpressionSyntax)_lazySemanticRootOfReplacedExpression.GetAnnotatedNodesAndTokens(annotation).Single().AsNode()!; } else { RoslynDebug.AssertNotNull(_lazyReplacedExpression); } } [Conditional("DEBUG")] protected abstract void ValidateSpeculativeSemanticModel(SemanticModel speculativeSemanticModel, SyntaxNode nodeToSpeculate); [MemberNotNull(nameof(_lazySpeculativeSemanticModel))] private void EnsureSpeculativeSemanticModel() { if (_lazySpeculativeSemanticModel == null) { var nodeToSpeculate = this.SemanticRootOfReplacedExpression; _lazySpeculativeSemanticModel = CreateSpeculativeSemanticModel(this.SemanticRootOfOriginalExpression, nodeToSpeculate, _semanticModel); ValidateSpeculativeSemanticModel(_lazySpeculativeSemanticModel, nodeToSpeculate); } } protected abstract SemanticModel CreateSpeculativeSemanticModel(SyntaxNode originalNode, SyntaxNode nodeToSpeculate, SemanticModel semanticModel); #region Semantic comparison helpers protected virtual bool ReplacementIntroducesErrorType(TExpressionSyntax originalExpression, TExpressionSyntax newExpression) { RoslynDebug.AssertNotNull(originalExpression); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalExpression)); RoslynDebug.AssertNotNull(newExpression); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newExpression)); var originalTypeInfo = this.OriginalSemanticModel.GetTypeInfo(originalExpression); var newTypeInfo = this.SpeculativeSemanticModel.GetTypeInfo(newExpression); if (originalTypeInfo.Type == null) { return false; } return newTypeInfo.Type == null || (newTypeInfo.Type.IsErrorType() && !originalTypeInfo.Type.IsErrorType()); } protected bool TypesAreCompatible(TExpressionSyntax originalExpression, TExpressionSyntax newExpression) { RoslynDebug.AssertNotNull(originalExpression); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalExpression)); RoslynDebug.AssertNotNull(newExpression); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newExpression)); var originalTypeInfo = this.OriginalSemanticModel.GetTypeInfo(originalExpression); var newTypeInfo = this.SpeculativeSemanticModel.GetTypeInfo(newExpression); return SymbolsAreCompatible(originalTypeInfo.Type, newTypeInfo.Type); } protected bool ConvertedTypesAreCompatible(TExpressionSyntax originalExpression, TExpressionSyntax newExpression) { RoslynDebug.AssertNotNull(originalExpression); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalExpression)); RoslynDebug.AssertNotNull(newExpression); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newExpression)); var originalTypeInfo = this.OriginalSemanticModel.GetTypeInfo(originalExpression); var newTypeInfo = this.SpeculativeSemanticModel.GetTypeInfo(newExpression); return SymbolsAreCompatible(originalTypeInfo.ConvertedType, newTypeInfo.ConvertedType); } protected bool ImplicitConversionsAreCompatible(TExpressionSyntax originalExpression, TExpressionSyntax newExpression) { RoslynDebug.AssertNotNull(originalExpression); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalExpression)); RoslynDebug.AssertNotNull(newExpression); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newExpression)); return ConversionsAreCompatible(this.OriginalSemanticModel, originalExpression, this.SpeculativeSemanticModel, newExpression); } private bool ImplicitConversionsAreCompatible(TExpressionSyntax originalExpression, ITypeSymbol originalTargetType, TExpressionSyntax newExpression, ITypeSymbol newTargetType) { RoslynDebug.AssertNotNull(originalExpression); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalExpression)); RoslynDebug.AssertNotNull(newExpression); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newExpression)); RoslynDebug.AssertNotNull(originalTargetType); RoslynDebug.AssertNotNull(newTargetType); return ConversionsAreCompatible(originalExpression, originalTargetType, newExpression, newTargetType); } protected abstract bool ConversionsAreCompatible(SemanticModel model1, TExpressionSyntax expression1, SemanticModel model2, TExpressionSyntax expression2); protected abstract bool ConversionsAreCompatible(TExpressionSyntax originalExpression, ITypeSymbol originalTargetType, TExpressionSyntax newExpression, ITypeSymbol newTargetType); protected bool SymbolsAreCompatible(SyntaxNode originalNode, SyntaxNode newNode, bool requireNonNullSymbols = false) { RoslynDebug.AssertNotNull(originalNode); Debug.Assert(this.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalNode)); RoslynDebug.AssertNotNull(newNode); Debug.Assert(this.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newNode)); var originalSymbolInfo = this.OriginalSemanticModel.GetSymbolInfo(originalNode); var newSymbolInfo = this.SpeculativeSemanticModel.GetSymbolInfo(newNode); return SymbolInfosAreCompatible(originalSymbolInfo, newSymbolInfo, requireNonNullSymbols); } public static bool SymbolInfosAreCompatible(SymbolInfo originalSymbolInfo, SymbolInfo newSymbolInfo, bool performEquivalenceCheck, bool requireNonNullSymbols = false) { return originalSymbolInfo.CandidateReason == newSymbolInfo.CandidateReason && SymbolsAreCompatibleCore(originalSymbolInfo.Symbol, newSymbolInfo.Symbol, performEquivalenceCheck, requireNonNullSymbols); } protected bool SymbolInfosAreCompatible(SymbolInfo originalSymbolInfo, SymbolInfo newSymbolInfo, bool requireNonNullSymbols = false) => SymbolInfosAreCompatible(originalSymbolInfo, newSymbolInfo, performEquivalenceCheck: !_isNewSemanticModelSpeculativeModel, requireNonNullSymbols: requireNonNullSymbols); protected bool SymbolsAreCompatible(ISymbol? symbol, ISymbol? newSymbol, bool requireNonNullSymbols = false) => SymbolsAreCompatibleCore(symbol, newSymbol, performEquivalenceCheck: !_isNewSemanticModelSpeculativeModel, requireNonNullSymbols: requireNonNullSymbols); private static bool SymbolsAreCompatibleCore( ISymbol? symbol, ISymbol? newSymbol, bool performEquivalenceCheck, bool requireNonNullSymbols = false) { if (symbol == null && newSymbol == null) { return !requireNonNullSymbols; } if (symbol == null || newSymbol == null) { return false; } if (symbol.IsReducedExtension()) { symbol = ((IMethodSymbol)symbol).GetConstructedReducedFrom()!; } if (newSymbol.IsReducedExtension()) { newSymbol = ((IMethodSymbol)newSymbol).GetConstructedReducedFrom()!; } // TODO: Lambda function comparison performs syntax equality, hence is non-trivial to compare lambda methods across different compilations. // For now, just assume they are equal. if (symbol.IsAnonymousFunction()) { return newSymbol.IsAnonymousFunction(); } if (performEquivalenceCheck) { // We are comparing symbols across two semantic models (where neither is the speculative model of other one). // We will use the SymbolEquivalenceComparer to check if symbols are equivalent. return CompareAcrossSemanticModels(symbol, newSymbol); } if (symbol.Equals(newSymbol, SymbolEqualityComparer.IncludeNullability)) { return true; } if (symbol is IMethodSymbol methodSymbol && newSymbol is IMethodSymbol newMethodSymbol) { // If we have local functions, we can't use normal symbol equality for them (since that checks locations). // Have to defer to SymbolEquivalence instead. if (methodSymbol.MethodKind == MethodKind.LocalFunction && newMethodSymbol.MethodKind == MethodKind.LocalFunction) return CompareAcrossSemanticModels(methodSymbol, newMethodSymbol); // Handle equivalence of special built-in comparison operators between enum types and // it's underlying enum type. if (methodSymbol.TryGetPredefinedComparisonOperator(out var originalOp) && newMethodSymbol.TryGetPredefinedComparisonOperator(out var newOp) && originalOp == newOp) { var type = methodSymbol.ContainingType; var newType = newMethodSymbol.ContainingType; if (type != null && newType != null) { if (EnumTypesAreCompatible(type, newType) || EnumTypesAreCompatible(newType, type)) { return true; } } } } return false; } private static bool CompareAcrossSemanticModels(ISymbol symbol, ISymbol newSymbol) { // SymbolEquivalenceComparer performs Location equality checks for locals, labels, range-variables and local // functions. As we are comparing symbols from different semantic models, locations will differ. Hence // perform minimal checks for these symbol kinds. if (symbol.Kind != newSymbol.Kind) return false; if (symbol is ILocalSymbol localSymbol && newSymbol is ILocalSymbol newLocalSymbol) { return newSymbol.IsImplicitlyDeclared == symbol.IsImplicitlyDeclared && symbol.Name == newSymbol.Name && CompareAcrossSemanticModels(localSymbol.Type, newLocalSymbol.Type); } if (symbol is ILabelSymbol && newSymbol is ILabelSymbol) return symbol.Name == newSymbol.Name; if (symbol is IRangeVariableSymbol && newSymbol is IRangeVariableSymbol) return symbol.Name == newSymbol.Name; if (symbol is IParameterSymbol parameterSymbol && newSymbol is IParameterSymbol newParameterSymbol && parameterSymbol.ContainingSymbol.IsAnonymousOrLocalFunction() && newParameterSymbol.ContainingSymbol.IsAnonymousOrLocalFunction()) { return symbol.Name == newSymbol.Name && parameterSymbol.IsRefOrOut() == newParameterSymbol.IsRefOrOut() && CompareAcrossSemanticModels(parameterSymbol.Type, newParameterSymbol.Type); } if (symbol is IMethodSymbol methodSymbol && newSymbol is IMethodSymbol newMethodSymbol && methodSymbol.IsLocalFunction() && newMethodSymbol.IsLocalFunction()) { return symbol.Name == newSymbol.Name && methodSymbol.Parameters.Length == newMethodSymbol.Parameters.Length && CompareAcrossSemanticModels(methodSymbol.ReturnType, newMethodSymbol.ReturnType) && methodSymbol.Parameters.Zip(newMethodSymbol.Parameters, (p1, p2) => (p1, p2)).All( t => CompareAcrossSemanticModels(t.p1, t.p2)); } return SymbolEquivalenceComparer.Instance.Equals(symbol, newSymbol); } private static bool EnumTypesAreCompatible(INamedTypeSymbol type1, INamedTypeSymbol type2) => type1.IsEnumType() && type1.EnumUnderlyingType?.SpecialType == type2.SpecialType; #endregion /// <summary> /// Determines whether performing the given syntax replacement will change the semantics of any parenting expressions /// by performing a bottom up walk from the <see cref="OriginalExpression"/> up to <see cref="SemanticRootOfOriginalExpression"/> /// in the original tree and simultaneously walking bottom up from <see cref="ReplacedExpression"/> up to <see cref="SemanticRootOfReplacedExpression"/> /// in the speculated syntax tree and performing appropriate semantic comparisons. /// </summary> public bool ReplacementChangesSemantics() { if (this.SemanticRootOfOriginalExpression is TTypeSyntax) { var originalType = (TTypeSyntax)this.OriginalExpression; var newType = (TTypeSyntax)this.ReplacedExpression; return ReplacementBreaksTypeResolution(originalType, newType, useSpeculativeModel: false); } return ReplacementChangesSemantics( currentOriginalNode: this.OriginalExpression, currentReplacedNode: this.ReplacedExpression, originalRoot: this.SemanticRootOfOriginalExpression, skipVerificationForCurrentNode: _skipVerificationForReplacedNode); } protected abstract bool IsParenthesizedExpression([NotNullWhen(true)] SyntaxNode? node); protected bool ReplacementChangesSemantics(SyntaxNode currentOriginalNode, SyntaxNode currentReplacedNode, SyntaxNode originalRoot, bool skipVerificationForCurrentNode) { if (this.SpeculativeSemanticModel == null) { // This is possible for some broken code scenarios with parse errors, bail out gracefully here. return true; } SyntaxNode? previousOriginalNode = null, previousReplacedNode = null; while (true) { if (!skipVerificationForCurrentNode && ReplacementChangesSemanticsForNode( currentOriginalNode, currentReplacedNode, previousOriginalNode, previousReplacedNode)) { return true; } if (currentOriginalNode == originalRoot) { break; } RoslynDebug.AssertNotNull(currentOriginalNode.Parent); RoslynDebug.AssertNotNull(currentReplacedNode.Parent); previousOriginalNode = currentOriginalNode; previousReplacedNode = currentReplacedNode; currentOriginalNode = currentOriginalNode.Parent; currentReplacedNode = currentReplacedNode.Parent; skipVerificationForCurrentNode = skipVerificationForCurrentNode && IsParenthesizedExpression(currentReplacedNode); } return false; } /// <summary> /// Checks whether the semantic symbols for the <see cref="OriginalExpression"/> and <see cref="ReplacedExpression"/> are non-null and compatible. /// </summary> /// <returns></returns> public bool SymbolsForOriginalAndReplacedNodesAreCompatible() { if (this.SpeculativeSemanticModel == null) { // This is possible for some broken code scenarios with parse errors, bail out gracefully here. return false; } return SymbolsAreCompatible(this.OriginalExpression, this.ReplacedExpression, requireNonNullSymbols: true); } protected abstract bool ReplacementChangesSemanticsForNodeLanguageSpecific(SyntaxNode currentOriginalNode, SyntaxNode currentReplacedNode, SyntaxNode? previousOriginalNode, SyntaxNode? previousReplacedNode); private bool ReplacementChangesSemanticsForNode(SyntaxNode currentOriginalNode, SyntaxNode currentReplacedNode, SyntaxNode? previousOriginalNode, SyntaxNode? previousReplacedNode) { Debug.Assert(previousOriginalNode == null || previousOriginalNode.Parent == currentOriginalNode); Debug.Assert(previousReplacedNode == null || previousReplacedNode.Parent == currentReplacedNode); if (ExpressionMightReferenceMember(currentOriginalNode)) { // If replacing the node will result in a change in overload resolution, we won't remove it. var originalExpression = (TExpressionSyntax)currentOriginalNode; var newExpression = (TExpressionSyntax)currentReplacedNode; if (ReplacementBreaksExpression(originalExpression, newExpression)) { return true; } if (ReplacementBreaksSystemObjectMethodResolution(currentOriginalNode, currentReplacedNode, previousOriginalNode, previousReplacedNode)) { return true; } return !ImplicitConversionsAreCompatible(originalExpression, newExpression); } else if (currentOriginalNode is TForEachStatementSyntax originalForEachStatement) { var newForEachStatement = (TForEachStatementSyntax)currentReplacedNode; return ReplacementBreaksForEachStatement(originalForEachStatement, newForEachStatement); } else if (currentOriginalNode is TAttributeSyntax originalAttribute) { var newAttribute = (TAttributeSyntax)currentReplacedNode; return ReplacementBreaksAttribute(originalAttribute, newAttribute); } else if (currentOriginalNode is TThrowStatementSyntax originalThrowStatement) { var newThrowStatement = (TThrowStatementSyntax)currentReplacedNode; return ReplacementBreaksThrowStatement(originalThrowStatement, newThrowStatement); } else if (ReplacementChangesSemanticsForNodeLanguageSpecific(currentOriginalNode, currentReplacedNode, previousOriginalNode, previousReplacedNode)) { return true; } if (currentOriginalNode is TTypeSyntax originalType) { var newType = (TTypeSyntax)currentReplacedNode; return ReplacementBreaksTypeResolution(originalType, newType); } else if (currentOriginalNode is TExpressionSyntax originalExpression) { var newExpression = (TExpressionSyntax)currentReplacedNode; if (!ImplicitConversionsAreCompatible(originalExpression, newExpression) || ReplacementIntroducesErrorType(originalExpression, newExpression)) { return true; } } return false; } /// <summary> /// Determine if removing the cast could cause the semantics of System.Object method call to change. /// E.g. Dim b = CStr(1).GetType() is necessary, but the GetType method symbol info resolves to the same with or without the cast. /// </summary> private bool ReplacementBreaksSystemObjectMethodResolution(SyntaxNode currentOriginalNode, SyntaxNode currentReplacedNode, [NotNullWhen(true)] SyntaxNode? previousOriginalNode, [NotNullWhen(true)] SyntaxNode? previousReplacedNode) { if (previousOriginalNode != null && previousReplacedNode != null) { var originalExpressionSymbol = this.OriginalSemanticModel.GetSymbolInfo(currentOriginalNode).Symbol; var replacedExpressionSymbol = this.SpeculativeSemanticModel.GetSymbolInfo(currentReplacedNode).Symbol; if (IsSymbolSystemObjectInstanceMethod(originalExpressionSymbol) && IsSymbolSystemObjectInstanceMethod(replacedExpressionSymbol)) { var previousOriginalType = this.OriginalSemanticModel.GetTypeInfo(previousOriginalNode).Type; var previousReplacedType = this.SpeculativeSemanticModel.GetTypeInfo(previousReplacedNode).Type; if (previousReplacedType != null && previousOriginalType != null) { return !previousReplacedType.InheritsFromOrEquals(previousOriginalType); } } } return false; } /// <summary> /// Determines if the symbol is a non-overridable, non static method on System.Object (e.g. GetType) /// </summary> private static bool IsSymbolSystemObjectInstanceMethod([NotNullWhen(true)] ISymbol? symbol) { return symbol != null && symbol.IsKind(SymbolKind.Method) && symbol.ContainingType.SpecialType == SpecialType.System_Object && !symbol.IsOverridable() && !symbol.IsStaticType(); } private bool ReplacementBreaksAttribute(TAttributeSyntax attribute, TAttributeSyntax newAttribute) { var attributeSym = this.OriginalSemanticModel.GetSymbolInfo(attribute).Symbol; var newAttributeSym = this.SpeculativeSemanticModel.GetSymbolInfo(newAttribute).Symbol; return !SymbolsAreCompatible(attributeSym, newAttributeSym); } protected abstract TExpressionSyntax GetForEachStatementExpression(TForEachStatementSyntax forEachStatement); protected abstract bool IsForEachTypeInferred(TForEachStatementSyntax forEachStatement, SemanticModel semanticModel); private bool ReplacementBreaksForEachStatement(TForEachStatementSyntax forEachStatement, TForEachStatementSyntax newForEachStatement) { var forEachExpression = GetForEachStatementExpression(forEachStatement); if (forEachExpression.IsMissing || !forEachExpression.Span.Contains(_expression.SpanStart)) { return false; } // inferred variable type compatible if (IsForEachTypeInferred(forEachStatement, _semanticModel)) { var local = (ILocalSymbol)_semanticModel.GetRequiredDeclaredSymbol(forEachStatement, _cancellationToken); var newLocal = (ILocalSymbol)this.SpeculativeSemanticModel.GetRequiredDeclaredSymbol(newForEachStatement, _cancellationToken); if (!SymbolsAreCompatible(local.Type, newLocal.Type)) { return true; } } GetForEachSymbols(this.OriginalSemanticModel, forEachStatement, out var originalGetEnumerator, out var originalElementType); GetForEachSymbols(this.SpeculativeSemanticModel, newForEachStatement, out var newGetEnumerator, out var newElementType); var newForEachExpression = GetForEachStatementExpression(newForEachStatement); if (ReplacementBreaksForEachGetEnumerator(originalGetEnumerator, newGetEnumerator, newForEachExpression) || !ForEachConversionsAreCompatible(this.OriginalSemanticModel, forEachStatement, this.SpeculativeSemanticModel, newForEachStatement) || !SymbolsAreCompatible(originalElementType, newElementType)) { return true; } return false; } protected abstract bool ForEachConversionsAreCompatible(SemanticModel originalModel, TForEachStatementSyntax originalForEach, SemanticModel newModel, TForEachStatementSyntax newForEach); protected abstract void GetForEachSymbols(SemanticModel model, TForEachStatementSyntax forEach, out IMethodSymbol getEnumeratorMethod, out ITypeSymbol elementType); private bool ReplacementBreaksForEachGetEnumerator(IMethodSymbol getEnumerator, IMethodSymbol newGetEnumerator, TExpressionSyntax newForEachStatementExpression) { if (getEnumerator == null && newGetEnumerator == null) { return false; } if (getEnumerator == null || newGetEnumerator == null) { return true; } if (getEnumerator.ToSignatureDisplayString() != newGetEnumerator.ToSignatureDisplayString()) { // Note this is likely an interface member from IEnumerable but the new member may be a // GetEnumerator method on a specific type. if (getEnumerator.IsImplementableMember()) { var expressionType = this.SpeculativeSemanticModel.GetTypeInfo(newForEachStatementExpression, _cancellationToken).ConvertedType; if (expressionType != null) { var implementationMember = expressionType.FindImplementationForInterfaceMember(getEnumerator); if (implementationMember != null) { if (implementationMember.ToSignatureDisplayString() != newGetEnumerator.ToSignatureDisplayString()) { return false; } } } } return true; } return false; } protected abstract TExpressionSyntax GetThrowStatementExpression(TThrowStatementSyntax throwStatement); private bool ReplacementBreaksThrowStatement(TThrowStatementSyntax originalThrowStatement, TThrowStatementSyntax newThrowStatement) { var originalThrowExpression = GetThrowStatementExpression(originalThrowStatement); var originalThrowExpressionType = this.OriginalSemanticModel.GetTypeInfo(originalThrowExpression).Type; var newThrowExpression = GetThrowStatementExpression(newThrowStatement); var newThrowExpressionType = this.SpeculativeSemanticModel.GetTypeInfo(newThrowExpression).Type; // C# language specification requires that type of the expression passed to ThrowStatement is or derives from System.Exception. return originalThrowExpressionType.IsOrDerivesFromExceptionType(this.OriginalSemanticModel.Compilation) != newThrowExpressionType.IsOrDerivesFromExceptionType(this.SpeculativeSemanticModel.Compilation); } protected abstract bool IsInNamespaceOrTypeContext(TExpressionSyntax node); private bool ReplacementBreaksTypeResolution(TTypeSyntax type, TTypeSyntax newType, bool useSpeculativeModel = true) { var symbol = this.OriginalSemanticModel.GetSymbolInfo(type).Symbol; ISymbol? newSymbol; if (useSpeculativeModel) { newSymbol = this.SpeculativeSemanticModel.GetSymbolInfo(newType, _cancellationToken).Symbol; } else { var bindingOption = IsInNamespaceOrTypeContext(type) ? SpeculativeBindingOption.BindAsTypeOrNamespace : SpeculativeBindingOption.BindAsExpression; newSymbol = this.OriginalSemanticModel.GetSpeculativeSymbolInfo(type.SpanStart, newType, bindingOption).Symbol; } return symbol != null && !SymbolsAreCompatible(symbol, newSymbol); } protected abstract bool ExpressionMightReferenceMember([NotNullWhen(true)] SyntaxNode? node); private static bool IsDelegateInvoke(ISymbol symbol) { return symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).MethodKind == MethodKind.DelegateInvoke; } private static bool IsAnonymousDelegateInvoke(ISymbol symbol) { return IsDelegateInvoke(symbol) && symbol.ContainingType != null && symbol.ContainingType.IsAnonymousType(); } private bool ReplacementBreaksExpression(TExpressionSyntax expression, TExpressionSyntax newExpression) { var originalSymbolInfo = _semanticModel.GetSymbolInfo(expression); if (_failOnOverloadResolutionFailuresInOriginalCode && originalSymbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure) { return true; } var newSymbolInfo = this.SpeculativeSemanticModel.GetSymbolInfo(node: newExpression); var symbol = originalSymbolInfo.Symbol; var newSymbol = newSymbolInfo.Symbol; if (SymbolInfosAreCompatible(originalSymbolInfo, newSymbolInfo)) { // Original and new symbols for the invocation expression are compatible. // However, if the symbols are interface members and if the receiver symbol for one of the expressions is a possible ValueType type parameter, // and the other one is not, then there might be a boxing conversion at runtime which causes different runtime behavior. if (symbol.IsImplementableMember()) { if (IsReceiverNonUniquePossibleValueTypeParam(expression, this.OriginalSemanticModel) != IsReceiverNonUniquePossibleValueTypeParam(newExpression, this.SpeculativeSemanticModel)) { return true; } } return false; } if (symbol == null || newSymbol == null || originalSymbolInfo.CandidateReason != newSymbolInfo.CandidateReason) { return true; } if (newSymbol.IsOverride) { for (var overriddenMember = newSymbol.GetOverriddenMember(); overriddenMember != null; overriddenMember = overriddenMember.GetOverriddenMember()) { if (symbol.Equals(overriddenMember)) return !SymbolsHaveCompatibleParameterLists(symbol, newSymbol, expression); } } if (symbol.IsImplementableMember() && IsCompatibleInterfaceMemberImplementation( symbol, newSymbol, expression, newExpression, this.SpeculativeSemanticModel)) { return false; } // Allow speculated invocation expression to bind to a different method symbol if the method's containing type is a delegate type // which has a delegate variance conversion to/from the original method's containing delegate type. if (newSymbol.ContainingType.IsDelegateType() && symbol.ContainingType.IsDelegateType() && IsReferenceConversion(this.OriginalSemanticModel.Compilation, newSymbol.ContainingType, symbol.ContainingType)) { return false; } // Heuristic: If we now bind to an anonymous delegate's invoke method, assume that // this isn't a change in overload resolution. if (IsAnonymousDelegateInvoke(newSymbol)) { return false; } return true; } protected bool ReplacementBreaksCompoundAssignment( TExpressionSyntax originalLeft, TExpressionSyntax originalRight, TExpressionSyntax newLeft, TExpressionSyntax newRight) { var originalTargetType = this.OriginalSemanticModel.GetTypeInfo(originalLeft).Type; if (originalTargetType != null) { var newTargetType = this.SpeculativeSemanticModel.GetTypeInfo(newLeft).Type; return !SymbolsAreCompatible(originalTargetType, newTargetType) || !ImplicitConversionsAreCompatible(originalRight, originalTargetType, newRight, newTargetType!); } return false; } protected abstract bool IsReferenceConversion(Compilation model, ITypeSymbol sourceType, ITypeSymbol targetType); private bool IsCompatibleInterfaceMemberImplementation( ISymbol symbol, ISymbol newSymbol, TExpressionSyntax originalExpression, TExpressionSyntax newExpression, SemanticModel speculativeSemanticModel) { // In general, we don't want to remove casts to interfaces. It may have subtle changes in behavior, // especially if the types in question change in the future. For example, if a type becomes non-sealed or a // new interface impl is introduced, we may subtly break things. // // The only cases where we feel confident enough to elide the cast are: // // 1. When we have an Array/Delegate/Enum. These are such core types, and cannot be changed by teh user, // that we can trust their impls to not change. // 2. We have one of the builtin structs (like int). These are such core types, and cannot be changed by teh // user, that we can trust their impls to not change. // 3. if we have a struct and we know we have a fresh copy of it. In that case, boxing the struct to the // interface doesn't serve any purpose. var newSymbolContainingType = newSymbol.ContainingType; if (newSymbolContainingType == null) return false; var newReceiver = GetReceiver(newExpression); var newReceiverType = newReceiver != null ? speculativeSemanticModel.GetTypeInfo(newReceiver).ConvertedType : newSymbolContainingType; if (newReceiverType == null) return false; var implementationMember = newSymbolContainingType.FindImplementationForInterfaceMember(symbol); if (implementationMember == null) return false; if (!newSymbol.Equals(implementationMember)) return false; if (!SymbolsHaveCompatibleParameterLists(symbol, implementationMember, originalExpression)) return false; if (newReceiverType.IsValueType) { // Presume builtin value types are all immutable, and thus will have the same semantics when you call // interface members on them directly instead of through a boxed copy. if (newReceiverType.SpecialType != SpecialType.None) return true; // For non-builtins, only remove the boxing if we know we have a copy already. return newReceiver != null && IsReceiverUniqueInstance(newReceiver, speculativeSemanticModel); } return newSymbolContainingType.SpecialType == SpecialType.System_Array || newSymbolContainingType.SpecialType == SpecialType.System_Delegate || newSymbolContainingType.SpecialType == SpecialType.System_Enum || newSymbolContainingType.SpecialType == SpecialType.System_String; } private bool IsReceiverNonUniquePossibleValueTypeParam(TExpressionSyntax invocation, SemanticModel semanticModel) { var receiver = GetReceiver(invocation); if (receiver != null) { var receiverType = semanticModel.GetTypeInfo(receiver).Type; if (receiverType.IsKind(SymbolKind.TypeParameter) && !receiverType.IsReferenceType) { return !IsReceiverUniqueInstance(receiver, semanticModel); } } return false; } // Returns true if the given receiver expression for an invocation represents a unique copy of the underlying // object that is not referenced by any other variable. For example, if the receiver expression is produced by a // method call, property, or indexer, then it will be a fresh receiver in the case of value types. private static bool IsReceiverUniqueInstance(TExpressionSyntax receiver, SemanticModel semanticModel) { var receiverSymbol = semanticModel.GetSymbolInfo(receiver).GetAnySymbol(); if (receiverSymbol == null) return false; return receiverSymbol.IsKind(SymbolKind.Method) || receiverSymbol.IsIndexer() || receiverSymbol.IsKind(SymbolKind.Property); } protected abstract ImmutableArray<TArgumentSyntax> GetArguments(TExpressionSyntax expression); protected abstract TExpressionSyntax GetReceiver(TExpressionSyntax expression); private bool SymbolsHaveCompatibleParameterLists(ISymbol originalSymbol, ISymbol newSymbol, TExpressionSyntax originalInvocation) { if (originalSymbol.IsKind(SymbolKind.Method) || originalSymbol.IsIndexer()) { var specifiedArguments = GetArguments(originalInvocation); if (!specifiedArguments.IsDefault) { var symbolParameters = originalSymbol.GetParameters(); var newSymbolParameters = newSymbol.GetParameters(); return AreCompatibleParameterLists(specifiedArguments, symbolParameters, newSymbolParameters); } } return true; } protected abstract bool IsNamedArgument(TArgumentSyntax argument); protected abstract string GetNamedArgumentIdentifierValueText(TArgumentSyntax argument); private bool AreCompatibleParameterLists( ImmutableArray<TArgumentSyntax> specifiedArguments, ImmutableArray<IParameterSymbol> signature1Parameters, ImmutableArray<IParameterSymbol> signature2Parameters) { Debug.Assert(signature1Parameters.Length == signature2Parameters.Length); Debug.Assert(specifiedArguments.Length <= signature1Parameters.Length || (signature1Parameters.Length > 0 && !signature1Parameters.Last().IsParams)); if (signature1Parameters.Length != signature2Parameters.Length) { return false; } // If there aren't any parameters, we're OK. if (signature1Parameters.Length == 0) { return true; } // To ensure that the second parameter list is called in the same way as the // first, we need to use the specified arguments to bail out if... // // * A named argument doesn't have a corresponding parameter in the // in either parameter list, or... // // * A named argument matches a parameter that is in a different position // in the two parameter lists. // // After checking the specified arguments, we walk the unspecified parameters // in both parameter lists to ensure that they have matching default values. var specifiedParameters1 = new List<IParameterSymbol>(); var specifiedParameters2 = new List<IParameterSymbol>(); for (var i = 0; i < specifiedArguments.Length; i++) { var argument = specifiedArguments[i]; // Handle named argument if (IsNamedArgument(argument)) { var name = GetNamedArgumentIdentifierValueText(argument); var parameter1 = signature1Parameters.FirstOrDefault(p => p.Name == name); RoslynDebug.AssertNotNull(parameter1); var parameter2 = signature2Parameters.FirstOrDefault(p => p.Name == name); if (parameter2 == null) { return false; } if (signature1Parameters.IndexOf(parameter1) != signature2Parameters.IndexOf(parameter2)) { return false; } specifiedParameters1.Add(parameter1); specifiedParameters2.Add(parameter2); } else { // otherwise, treat the argument positionally, taking care to properly // handle params parameters. if (i < signature1Parameters.Length) { specifiedParameters1.Add(signature1Parameters[i]); specifiedParameters2.Add(signature2Parameters[i]); } } } // At this point, we can safely assume that specifiedParameters1 and signature2Parameters // contain parameters that appear at the same positions in their respective signatures // because we bailed out if named arguments referred to parameters at different positions. // // Now we walk the unspecified parameters to ensure that they have the same default // values. for (var i = 0; i < signature1Parameters.Length; i++) { var parameter1 = signature1Parameters[i]; if (specifiedParameters1.Contains(parameter1)) { continue; } var parameter2 = signature2Parameters[i]; Debug.Assert(parameter1.HasExplicitDefaultValue, "Expected all unspecified parameter to have default values"); Debug.Assert(parameter1.HasExplicitDefaultValue == parameter2.HasExplicitDefaultValue); if (parameter1.HasExplicitDefaultValue && parameter2.HasExplicitDefaultValue) { if (!object.Equals(parameter2.ExplicitDefaultValue, parameter1.ExplicitDefaultValue)) { return false; } if (object.Equals(parameter1.ExplicitDefaultValue, 0.0)) { RoslynDebug.Assert(object.Equals(parameter2.ExplicitDefaultValue, 0.0)); var isParam1DefaultValueNegativeZero = double.IsNegativeInfinity(1.0 / (double)parameter1.ExplicitDefaultValue); var isParam2DefaultValueNegativeZero = double.IsNegativeInfinity(1.0 / (double)parameter2.ExplicitDefaultValue); if (isParam1DefaultValueNegativeZero != isParam2DefaultValueNegativeZero) { return false; } } } } return true; } protected void GetConversions( TExpressionSyntax originalExpression, ITypeSymbol originalTargetType, TExpressionSyntax newExpression, ITypeSymbol newTargetType, out TConversion? originalConversion, out TConversion? newConversion) { originalConversion = null; newConversion = null; if (this.OriginalSemanticModel.GetTypeInfo(originalExpression).Type != null && this.SpeculativeSemanticModel.GetTypeInfo(newExpression).Type != null) { originalConversion = ClassifyConversion(this.OriginalSemanticModel, originalExpression, originalTargetType); newConversion = ClassifyConversion(this.SpeculativeSemanticModel, newExpression, newTargetType); } else { var originalConvertedTypeSymbol = this.OriginalSemanticModel.GetTypeInfo(originalExpression).ConvertedType; if (originalConvertedTypeSymbol != null) { originalConversion = ClassifyConversion(this.OriginalSemanticModel, originalConvertedTypeSymbol, originalTargetType); } var newConvertedTypeSymbol = this.SpeculativeSemanticModel.GetTypeInfo(newExpression).ConvertedType; if (newConvertedTypeSymbol != null) { newConversion = ClassifyConversion(this.SpeculativeSemanticModel, newConvertedTypeSymbol, newTargetType); } } } protected abstract TConversion ClassifyConversion(SemanticModel model, TExpressionSyntax expression, ITypeSymbol targetType); protected abstract TConversion ClassifyConversion(SemanticModel model, ITypeSymbol originalType, ITypeSymbol targetType); } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.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="../Resources.resx"> <body> <trans-unit id="DynamicView"> <source>Dynamic View</source> <target state="translated">Visualizzazione dinamica</target> <note>IDynamicMetaObjectProvider and System.__ComObject expansion</note> </trans-unit> <trans-unit id="DynamicViewNotDynamic"> <source>Only COM or Dynamic objects can have Dynamic View</source> <target state="translated">La Visualizzazione dinamica è consentita solo per oggetti COM o dinamici</target> <note>Cannot use "dynamic" format specifier on a non-dynamic type</note> </trans-unit> <trans-unit id="DynamicViewValueWarning"> <source>Expanding the Dynamic View will get the dynamic members for the object</source> <target state="translated">Se si espande la Visualizzazione dinamica, si otterranno i membri dinamici per l'oggetto</target> <note>Warning reported in Dynamic View value</note> </trans-unit> <trans-unit id="ErrorName"> <source>Error</source> <target state="translated">Errore</target> <note>Error result name</note> </trans-unit> <trans-unit id="ExceptionThrown"> <source>'{0}' threw an exception of type '{1}'</source> <target state="translated">'{0}' ha generato un'eccezione di tipo '{1}'</target> <note>Threw an exception while evaluating a value.</note> </trans-unit> <trans-unit id="HostValueNotFound"> <source>Cannot provide the value: host value not found</source> <target state="translated">Non è possibile specificare il valore: il valore host non è stato trovato</target> <note /> </trans-unit> <trans-unit id="InvalidPointerDereference"> <source>Cannot dereference '{0}'. The pointer is not valid.</source> <target state="translated">Non è possibile dereferenziare '{0}'. Il puntatore non è valido.</target> <note>Invalid pointer dereference</note> </trans-unit> <trans-unit id="NativeView"> <source>Native View</source> <target state="translated">Visualizzazione nativa</target> <note>Native COM object expansion</note> </trans-unit> <trans-unit id="NativeViewNotNativeDebugging"> <source>To inspect the native object, enable native code debugging.</source> <target state="translated">Per ispezionare l'oggetto nativo, abilitare il debug del codice nativo.</target> <note>Display value of Native View node when native debugging is not enabled</note> </trans-unit> <trans-unit id="NonPublicMembers"> <source>Non-Public members</source> <target state="translated">Membri non pubblici</target> <note>Non-public type members</note> </trans-unit> <trans-unit id="RawView"> <source>Raw View</source> <target state="translated">Visualizzazione non elaborata</target> <note>DebuggerTypeProxy "Raw View"</note> </trans-unit> <trans-unit id="ResultsView"> <source>Results View</source> <target state="translated">Visualizzazione risultati</target> <note>IEnumerable results expansion</note> </trans-unit> <trans-unit id="ResultsViewNoSystemCore"> <source>Results View requires System.Core.dll to be referenced</source> <target state="translated">La Visualizzazione risultati richiede il riferimento a System.Core.dll</target> <note>"results" format specifier requires System.Core.dll</note> </trans-unit> <trans-unit id="ResultsViewNotEnumerable"> <source>Only Enumerable types can have Results View</source> <target state="translated">Solo i tipi Enumerable possono disporre di una Visualizzazione risultati</target> <note>Cannot use "results" format specifier on non-enumerable type</note> </trans-unit> <trans-unit id="ResultsViewValueWarning"> <source>Expanding the Results View will enumerate the IEnumerable</source> <target state="translated">L'espansione della Visualizzazione risultati enumera IEnumerable</target> <note>Warning reported in Results View value</note> </trans-unit> <trans-unit id="SharedMembers"> <source>Shared members</source> <target state="translated">Membri condivisi</target> <note>Shared type members (VB only)</note> </trans-unit> <trans-unit id="StaticMembers"> <source>Static members</source> <target state="translated">Membri statici</target> <note>Static type members (C# only)</note> </trans-unit> <trans-unit id="TypeVariablesName"> <source>Type variables</source> <target state="translated">Variabili di tipo</target> <note>Type variables result name</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="../Resources.resx"> <body> <trans-unit id="DynamicView"> <source>Dynamic View</source> <target state="translated">Visualizzazione dinamica</target> <note>IDynamicMetaObjectProvider and System.__ComObject expansion</note> </trans-unit> <trans-unit id="DynamicViewNotDynamic"> <source>Only COM or Dynamic objects can have Dynamic View</source> <target state="translated">La Visualizzazione dinamica è consentita solo per oggetti COM o dinamici</target> <note>Cannot use "dynamic" format specifier on a non-dynamic type</note> </trans-unit> <trans-unit id="DynamicViewValueWarning"> <source>Expanding the Dynamic View will get the dynamic members for the object</source> <target state="translated">Se si espande la Visualizzazione dinamica, si otterranno i membri dinamici per l'oggetto</target> <note>Warning reported in Dynamic View value</note> </trans-unit> <trans-unit id="ErrorName"> <source>Error</source> <target state="translated">Errore</target> <note>Error result name</note> </trans-unit> <trans-unit id="ExceptionThrown"> <source>'{0}' threw an exception of type '{1}'</source> <target state="translated">'{0}' ha generato un'eccezione di tipo '{1}'</target> <note>Threw an exception while evaluating a value.</note> </trans-unit> <trans-unit id="HostValueNotFound"> <source>Cannot provide the value: host value not found</source> <target state="translated">Non è possibile specificare il valore: il valore host non è stato trovato</target> <note /> </trans-unit> <trans-unit id="InvalidPointerDereference"> <source>Cannot dereference '{0}'. The pointer is not valid.</source> <target state="translated">Non è possibile dereferenziare '{0}'. Il puntatore non è valido.</target> <note>Invalid pointer dereference</note> </trans-unit> <trans-unit id="NativeView"> <source>Native View</source> <target state="translated">Visualizzazione nativa</target> <note>Native COM object expansion</note> </trans-unit> <trans-unit id="NativeViewNotNativeDebugging"> <source>To inspect the native object, enable native code debugging.</source> <target state="translated">Per ispezionare l'oggetto nativo, abilitare il debug del codice nativo.</target> <note>Display value of Native View node when native debugging is not enabled</note> </trans-unit> <trans-unit id="NonPublicMembers"> <source>Non-Public members</source> <target state="translated">Membri non pubblici</target> <note>Non-public type members</note> </trans-unit> <trans-unit id="RawView"> <source>Raw View</source> <target state="translated">Visualizzazione non elaborata</target> <note>DebuggerTypeProxy "Raw View"</note> </trans-unit> <trans-unit id="ResultsView"> <source>Results View</source> <target state="translated">Visualizzazione risultati</target> <note>IEnumerable results expansion</note> </trans-unit> <trans-unit id="ResultsViewNoSystemCore"> <source>Results View requires System.Core.dll to be referenced</source> <target state="translated">La Visualizzazione risultati richiede il riferimento a System.Core.dll</target> <note>"results" format specifier requires System.Core.dll</note> </trans-unit> <trans-unit id="ResultsViewNotEnumerable"> <source>Only Enumerable types can have Results View</source> <target state="translated">Solo i tipi Enumerable possono disporre di una Visualizzazione risultati</target> <note>Cannot use "results" format specifier on non-enumerable type</note> </trans-unit> <trans-unit id="ResultsViewValueWarning"> <source>Expanding the Results View will enumerate the IEnumerable</source> <target state="translated">L'espansione della Visualizzazione risultati enumera IEnumerable</target> <note>Warning reported in Results View value</note> </trans-unit> <trans-unit id="SharedMembers"> <source>Shared members</source> <target state="translated">Membri condivisi</target> <note>Shared type members (VB only)</note> </trans-unit> <trans-unit id="StaticMembers"> <source>Static members</source> <target state="translated">Membri statici</target> <note>Static type members (C# only)</note> </trans-unit> <trans-unit id="TypeVariablesName"> <source>Type variables</source> <target state="translated">Variabili di tipo</target> <note>Type variables result name</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/Core/Portable/Text/SourceTextContainer.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.Text { /// <summary> /// An object that contains an instance of a SourceText and raises events when its current instance /// changes. /// </summary> public abstract class SourceTextContainer { /// <summary> /// The current text instance. /// </summary> public abstract SourceText CurrentText { get; } /// <summary> /// Raised when the current text instance changes. /// </summary> public abstract event EventHandler<TextChangeEventArgs> TextChanged; } }
// Licensed to the .NET Foundation under one or more 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.Text { /// <summary> /// An object that contains an instance of a SourceText and raises events when its current instance /// changes. /// </summary> public abstract class SourceTextContainer { /// <summary> /// The current text instance. /// </summary> public abstract SourceText CurrentText { get; } /// <summary> /// Raised when the current text instance changes. /// </summary> public abstract event EventHandler<TextChangeEventArgs> TextChanged; } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/EditorFeatures/Core/EmbeddedLanguages/DateAndTime/DateAndTimeEmbeddedLanguageEditorFeatures.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.EmbeddedLanguages; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.DateAndTime { internal class DateAndTimeEmbeddedLanguageEditorFeatures : DateAndTimeEmbeddedLanguageFeatures, IEmbeddedLanguageEditorFeatures { public IBraceMatcher BraceMatcher { get; } public DateAndTimeEmbeddedLanguageEditorFeatures(EmbeddedLanguageInfo info) : base(info) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.EmbeddedLanguages; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.DateAndTime { internal class DateAndTimeEmbeddedLanguageEditorFeatures : DateAndTimeEmbeddedLanguageFeatures, IEmbeddedLanguageEditorFeatures { public IBraceMatcher BraceMatcher { get; } public DateAndTimeEmbeddedLanguageEditorFeatures(EmbeddedLanguageInfo info) : base(info) { } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./docs/contributing/API Review Process.md
# API Review Process .NET has a long-standing history of taking API usability extremely seriously. Thus, we generally review every single API that is added to the product. This page discusses how we conduct design reviews for the Roslyn components. ## Which APIs should be reviewed? The rule of thumb is that we (**dotnet/roslyn**) review every public API that is being added to this repository in the CodeAnalysis (compiler), Workspaces, Features, and EditorFeatures libraries. APIs in the LanguageServices dlls are not usually reviewed as they are not intended for general consumption; they are for use in Visual Studio, and we don't have a compat bar for these APIs. ## Steps 1. **Requester files an issue**. The issue description should contain a speclet that represents a sketch of the new APIs, including samples on how the APIs are being used. The goal isn't to get a complete API list, but a good handle on how the new APIs would roughly look like and in what scenarios they are being used. Please use [this template](https://github.com/dotnet/roslyn/issues/new?template=api-suggestion.md). The issue should have the labels `Feature Request` and `Concept-API`. [Here](https://github.com/dotnet/roslyn/issues/53410) is a good example of a strong API proposal. 2. **We assign an owner**. We'll assign a dedicated owner from our side that sponsors the issue. This is usually [the area owner](../area-owners.md#areas) for which the API proposal or design change request was filed. 3. **Discussion**. The goal of the discussion is to help the assignee to decide whether we want to pursue the proposal or not. In this phase, the goal isn't necessarily to perform an in-depth review; rather, we want to make sure that the proposal is actionable, i.e. has a concrete design, a sketch of the APIs and some code samples that show how it should be used. If changes are necessary, the owner will set the label `api-needs-work`. To make the changes, the requester should edit the top-most issue description. This allows folks joining later to understand the most recent proposal. To avoid confusion, the requester can maintain a tiny change log, like a bolded "Updates:" followed by a bullet point list of the updates that were being made. When you the feedback is addressed, the requester should notify the owner to re-review the changes. 4. **Owner makes decision**. When the owner believes enough information is available to make a decision, they will update the issue accordingly: * **Mark for review**. If the owner believes the proposal is actionable, they will label the issue with `api-ready-for-review`. * **Close as not actionable**. In case the issue didn't get enough traction to be distilled into a concrete proposal, the owner will close the issue. * **Close as won't fix as proposed**. Sometimes, the issue that is raised is a good one but the owner thinks the concrete proposal is not the right way to tackle the problem. In most cases, the owner will try to steer the discussion in a direction that results in a design that we believe is appropriate. However, for some proposals the problem is at the heart of the design which can't easily be changed without starting a new proposal. In those cases, the owner will close the issue and explain the issue the design has. * **Close as won't fix**. Similarly, if proposal is taking the product in a direction we simply don't want to go, the issue might also get closed. In that case, the problem isn't the proposed design but in the issue itself. 5. **API gets reviewed**. The group conducting the review is called *RAR*, which stands for *Roslyn API Reviewers*. In the review, we'll take notes and provide feedback. After the review, we'll publish the notes in the [API Review repository](https://github.com/dotnet/apireviews) and at the end of the relevant issue. Multiple outcomes are possible: * **Approved**. In this case the label `api-ready-for-review` is replaced with `api-approved`. * **Needs work**. If we believe the proposal isn't ready yet, we'll replace the label `api-ready-for-review` with `api-needs-work`. * **Rejected**. If we believe the proposal isn't a direction we want to pursue, we'll simply write a comment and close the issue. ## Review schedule There are three methods to get an API review (this section applies to API area owners, but is included for transparency into the process): * **Get into the backlog**. Generally speaking, filing an issue in `dotnet/roslyn` and applying the label `api-ready-for-review` on it will make your issue show up during API reviews. The downside is that we generally walk the backlog oldest-newest, so your issue might not be looked at for a while. Progress of issues can be tracked via <https://apireview.net/backlog?g=Roslyn>. * **Fast track**. If you need to bypass the backlog apply both `api-ready-for-review` and `blocking`. All blocking issues are looked at before we walk the backlog. * **Dedicated review**. If an issue you are the area owner for needs an hour or longer, send an email to roslynapiowners and we book dedicated time. We also book dedicated time for language feature APIs: any APIs added as part of a new language feature need to have a dedicated review session. Rule of thumb: if the API proposal has more than a dozen APIs, the APIs have complex policy, or the APIs are part of a feature branch, then you need 60 min or more. When in doubt, send mail to roslynapiowners. The API review board currently meets every 2 weeks. ## Pull requests Pull requests against **dotnet/roslyn** that add new public API shouldn't be submitted before getting approval. Also, we don't want to get work in progress (WIP) PR's. The reason being that we want to reduce the number pending PRs so that we can focus on the work the community expects we take action on. If you want to collaborate with other people on the design, feel free to perform the work in a branch in your own fork. If you want to track your TODOs in the description of a PR, you can always submit a PR against your own fork. Also, feel free to advertise your PR by linking it from the issue you filed against **dotnet/roslyn** in the first step above. For **dotnet/roslyn** team members, PRs are allowed to be submitted and merged before a full API review session, but you should have sign-off from the area owner, and the API is expected to be covered in a formal review session before being shipped. For such issues, please work with the API area owner to make sure that the issue is marked blocking appropriately so it will be covered in short order.
# API Review Process .NET has a long-standing history of taking API usability extremely seriously. Thus, we generally review every single API that is added to the product. This page discusses how we conduct design reviews for the Roslyn components. ## Which APIs should be reviewed? The rule of thumb is that we (**dotnet/roslyn**) review every public API that is being added to this repository in the CodeAnalysis (compiler), Workspaces, Features, and EditorFeatures libraries. APIs in the LanguageServices dlls are not usually reviewed as they are not intended for general consumption; they are for use in Visual Studio, and we don't have a compat bar for these APIs. ## Steps 1. **Requester files an issue**. The issue description should contain a speclet that represents a sketch of the new APIs, including samples on how the APIs are being used. The goal isn't to get a complete API list, but a good handle on how the new APIs would roughly look like and in what scenarios they are being used. Please use [this template](https://github.com/dotnet/roslyn/issues/new?template=api-suggestion.md). The issue should have the labels `Feature Request` and `Concept-API`. [Here](https://github.com/dotnet/roslyn/issues/53410) is a good example of a strong API proposal. 2. **We assign an owner**. We'll assign a dedicated owner from our side that sponsors the issue. This is usually [the area owner](../area-owners.md#areas) for which the API proposal or design change request was filed. 3. **Discussion**. The goal of the discussion is to help the assignee to decide whether we want to pursue the proposal or not. In this phase, the goal isn't necessarily to perform an in-depth review; rather, we want to make sure that the proposal is actionable, i.e. has a concrete design, a sketch of the APIs and some code samples that show how it should be used. If changes are necessary, the owner will set the label `api-needs-work`. To make the changes, the requester should edit the top-most issue description. This allows folks joining later to understand the most recent proposal. To avoid confusion, the requester can maintain a tiny change log, like a bolded "Updates:" followed by a bullet point list of the updates that were being made. When you the feedback is addressed, the requester should notify the owner to re-review the changes. 4. **Owner makes decision**. When the owner believes enough information is available to make a decision, they will update the issue accordingly: * **Mark for review**. If the owner believes the proposal is actionable, they will label the issue with `api-ready-for-review`. * **Close as not actionable**. In case the issue didn't get enough traction to be distilled into a concrete proposal, the owner will close the issue. * **Close as won't fix as proposed**. Sometimes, the issue that is raised is a good one but the owner thinks the concrete proposal is not the right way to tackle the problem. In most cases, the owner will try to steer the discussion in a direction that results in a design that we believe is appropriate. However, for some proposals the problem is at the heart of the design which can't easily be changed without starting a new proposal. In those cases, the owner will close the issue and explain the issue the design has. * **Close as won't fix**. Similarly, if proposal is taking the product in a direction we simply don't want to go, the issue might also get closed. In that case, the problem isn't the proposed design but in the issue itself. 5. **API gets reviewed**. The group conducting the review is called *RAR*, which stands for *Roslyn API Reviewers*. In the review, we'll take notes and provide feedback. After the review, we'll publish the notes in the [API Review repository](https://github.com/dotnet/apireviews) and at the end of the relevant issue. Multiple outcomes are possible: * **Approved**. In this case the label `api-ready-for-review` is replaced with `api-approved`. * **Needs work**. If we believe the proposal isn't ready yet, we'll replace the label `api-ready-for-review` with `api-needs-work`. * **Rejected**. If we believe the proposal isn't a direction we want to pursue, we'll simply write a comment and close the issue. ## Review schedule There are three methods to get an API review (this section applies to API area owners, but is included for transparency into the process): * **Get into the backlog**. Generally speaking, filing an issue in `dotnet/roslyn` and applying the label `api-ready-for-review` on it will make your issue show up during API reviews. The downside is that we generally walk the backlog oldest-newest, so your issue might not be looked at for a while. Progress of issues can be tracked via <https://apireview.net/backlog?g=Roslyn>. * **Fast track**. If you need to bypass the backlog apply both `api-ready-for-review` and `blocking`. All blocking issues are looked at before we walk the backlog. * **Dedicated review**. If an issue you are the area owner for needs an hour or longer, send an email to roslynapiowners and we book dedicated time. We also book dedicated time for language feature APIs: any APIs added as part of a new language feature need to have a dedicated review session. Rule of thumb: if the API proposal has more than a dozen APIs, the APIs have complex policy, or the APIs are part of a feature branch, then you need 60 min or more. When in doubt, send mail to roslynapiowners. The API review board currently meets every 2 weeks. ## Pull requests Pull requests against **dotnet/roslyn** that add new public API shouldn't be submitted before getting approval. Also, we don't want to get work in progress (WIP) PR's. The reason being that we want to reduce the number pending PRs so that we can focus on the work the community expects we take action on. If you want to collaborate with other people on the design, feel free to perform the work in a branch in your own fork. If you want to track your TODOs in the description of a PR, you can always submit a PR against your own fork. Also, feel free to advertise your PR by linking it from the issue you filed against **dotnet/roslyn** in the first step above. For **dotnet/roslyn** team members, PRs are allowed to be submitted and merged before a full API review session, but you should have sign-off from the area owner, and the API is expected to be covered in a formal review session before being shipped. For such issues, please work with the API area owner to make sure that the issue is marked blocking appropriately so it will be covered in short order.
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/EditorFeatures/CSharp/SplitStringLiteral/SplitStringLiteralCommandHandler.SimpleStringSplitter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.Formatting.FormattingOptions; namespace Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral { internal partial class SplitStringLiteralCommandHandler { private class SimpleStringSplitter : StringSplitter { private const char QuoteCharacter = '"'; private readonly SyntaxToken _token; public SimpleStringSplitter( Document document, int position, SyntaxNode root, SourceText sourceText, SyntaxToken token, bool useTabs, int tabSize, IndentStyle indentStyle, CancellationToken cancellationToken) : base(document, position, root, sourceText, useTabs, tabSize, indentStyle, cancellationToken) { _token = token; } // Don't split @"" strings. They already support directly embedding newlines. protected override bool CheckToken() => !_token.IsVerbatimStringLiteral(); protected override SyntaxNode GetNodeToReplace() => _token.Parent; protected override BinaryExpressionSyntax CreateSplitString() { // TODO(cyrusn): Deal with the positoin being after a \ character var prefix = SourceText.GetSubText(TextSpan.FromBounds(_token.SpanStart, CursorPosition)).ToString(); var suffix = SourceText.GetSubText(TextSpan.FromBounds(CursorPosition, _token.Span.End)).ToString(); var firstToken = SyntaxFactory.Token( _token.LeadingTrivia, _token.Kind(), text: prefix + QuoteCharacter, valueText: "", trailing: SyntaxFactory.TriviaList(SyntaxFactory.ElasticSpace)); var secondToken = SyntaxFactory.Token( default, _token.Kind(), text: QuoteCharacter + suffix, valueText: "", trailing: _token.TrailingTrivia); var leftExpression = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, firstToken); var rightExpression = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, secondToken); return SyntaxFactory.BinaryExpression( SyntaxKind.AddExpression, leftExpression, PlusNewLineToken, rightExpression.WithAdditionalAnnotations(RightNodeAnnotation)); } protected override int StringOpenQuoteLength() => "\"".Length; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.Formatting.FormattingOptions; namespace Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral { internal partial class SplitStringLiteralCommandHandler { private class SimpleStringSplitter : StringSplitter { private const char QuoteCharacter = '"'; private readonly SyntaxToken _token; public SimpleStringSplitter( Document document, int position, SyntaxNode root, SourceText sourceText, SyntaxToken token, bool useTabs, int tabSize, IndentStyle indentStyle, CancellationToken cancellationToken) : base(document, position, root, sourceText, useTabs, tabSize, indentStyle, cancellationToken) { _token = token; } // Don't split @"" strings. They already support directly embedding newlines. protected override bool CheckToken() => !_token.IsVerbatimStringLiteral(); protected override SyntaxNode GetNodeToReplace() => _token.Parent; protected override BinaryExpressionSyntax CreateSplitString() { // TODO(cyrusn): Deal with the positoin being after a \ character var prefix = SourceText.GetSubText(TextSpan.FromBounds(_token.SpanStart, CursorPosition)).ToString(); var suffix = SourceText.GetSubText(TextSpan.FromBounds(CursorPosition, _token.Span.End)).ToString(); var firstToken = SyntaxFactory.Token( _token.LeadingTrivia, _token.Kind(), text: prefix + QuoteCharacter, valueText: "", trailing: SyntaxFactory.TriviaList(SyntaxFactory.ElasticSpace)); var secondToken = SyntaxFactory.Token( default, _token.Kind(), text: QuoteCharacter + suffix, valueText: "", trailing: _token.TrailingTrivia); var leftExpression = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, firstToken); var rightExpression = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, secondToken); return SyntaxFactory.BinaryExpression( SyntaxKind.AddExpression, leftExpression, PlusNewLineToken, rightExpression.WithAdditionalAnnotations(RightNodeAnnotation)); } protected override int StringOpenQuoteLength() => "\"".Length; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/EditorFeatures/Core/Shared/Preview/PredefinedPreviewTaggerKeys.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Editor.Shared.Preview { internal static class PredefinedPreviewTaggerKeys { public static readonly object DefinitionHighlightingSpansKey = new(); public static readonly object ReferenceHighlightingSpansKey = new(); public static readonly object WrittenReferenceHighlightingSpansKey = new(); public static readonly object ConflictSpansKey = new(); public static readonly object WarningSpansKey = new(); public static readonly object SuppressDiagnosticsSpansKey = new(); public static readonly object StaticClassificationSpansKey = new(); } }
// Licensed to the .NET Foundation under one or more 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.Shared.Preview { internal static class PredefinedPreviewTaggerKeys { public static readonly object DefinitionHighlightingSpansKey = new(); public static readonly object ReferenceHighlightingSpansKey = new(); public static readonly object WrittenReferenceHighlightingSpansKey = new(); public static readonly object ConflictSpansKey = new(); public static readonly object WarningSpansKey = new(); public static readonly object SuppressDiagnosticsSpansKey = new(); public static readonly object StaticClassificationSpansKey = new(); } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/VisualBasic/Portable/CodeGen/Optimizer/StackScheduler.Rewriter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGen Partial Friend Class StackScheduler ''' <summary> ''' Rewrites the tree to account for destructive nature of stack local reads. ''' ''' Typically, last read stays as-is and local is destroyed by the read. ''' Intermediate reads are rewritten as Dups - ''' ''' NotLastUse(X_stackLocal) ===> NotLastUse(Dup) ''' LastUse(X_stackLocal) ===> LastUse(X_stackLocal) ''' ''' </summary> Private NotInheritable Class Rewriter Inherits BoundTreeRewriterWithStackGuard Private _nodeCounter As Integer = 0 Private ReadOnly _info As Dictionary(Of LocalSymbol, LocalDefUseInfo) = Nothing Private Sub New(info As Dictionary(Of LocalSymbol, LocalDefUseInfo)) Me._info = info End Sub Public Shared Function Rewrite(src As BoundStatement, info As Dictionary(Of LocalSymbol, LocalDefUseInfo)) As BoundStatement Dim scheduler As New Rewriter(info) Return DirectCast(scheduler.Visit(src), BoundStatement) End Function Public Overrides Function Visit(node As BoundNode) As BoundNode Dim result As BoundNode = Nothing ' rewriting constants may undo constant folding and make thing worse. ' so we will not go into constant nodes. ' CodeGen will not do that either. Dim asExpression = TryCast(node, BoundExpression) If asExpression IsNot Nothing AndAlso asExpression.ConstantValueOpt IsNot Nothing Then result = node Else result = MyBase.Visit(node) End If Me._nodeCounter += 1 Return result End Function Public Overrides Function VisitBinaryOperator(node As BoundBinaryOperator) As BoundNode ' Do not blow the stack due to a deep recursion on the left. Dim child As BoundExpression = node.Left If child.Kind <> BoundKind.BinaryOperator OrElse child.ConstantValueOpt IsNot Nothing Then Return VisitBinaryOperatorSimple(node) End If Dim stack = ArrayBuilder(Of BoundBinaryOperator).GetInstance() stack.Push(node) Dim binary As BoundBinaryOperator = DirectCast(child, BoundBinaryOperator) Do stack.Push(binary) child = binary.Left If child.Kind <> BoundKind.BinaryOperator OrElse child.ConstantValueOpt IsNot Nothing Then Exit Do End If binary = DirectCast(child, BoundBinaryOperator) Loop Dim left = DirectCast(Me.Visit(child), BoundExpression) Do binary = stack.Pop() Dim right = DirectCast(Me.Visit(binary.Right), BoundExpression) Dim type As TypeSymbol = Me.VisitType(binary.Type) left = binary.Update(binary.OperatorKind, left, right, binary.Checked, binary.ConstantValueOpt, type) If stack.Count = 0 Then Exit Do End If Me._nodeCounter += 1 Loop Debug.Assert(binary Is node) stack.Free() Return left End Function Private Function VisitBinaryOperatorSimple(node As BoundBinaryOperator) As BoundNode Return MyBase.VisitBinaryOperator(node) End Function Private Shared Function IsLastAccess(locInfo As LocalDefUseInfo, counter As Integer) As Boolean Return locInfo.localDefs.Any(Function(d) counter = d.Start AndAlso counter = d.End) End Function Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode Dim locInfo As LocalDefUseInfo = Nothing If Not _info.TryGetValue(node.LocalSymbol, locInfo) Then Return MyBase.VisitLocal(node) End If ' not the last access, emit Dup. If Not IsLastAccess(locInfo, _nodeCounter) Then Return New BoundDup(node.Syntax, node.LocalSymbol.IsByRef, node.Type) End If ' last access - leave the node as is. Emit will do nothing expecting the node on the stack Return MyBase.VisitLocal(node) End Function ' TODO: Why?? 'Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode ' Dim arguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Arguments) ' Debug.Assert(node.InitializerOpt Is Nothing) ' Dim type As TypeSymbol = Me.VisitType(node.Type) ' Return node.Update(node.ConstructorOpt, arguments, node.InitializerOpt, type) 'End Function Public Overrides Function VisitReferenceAssignment(node As BoundReferenceAssignment) As BoundNode Dim locInfo As LocalDefUseInfo = Nothing Dim left = DirectCast(node.ByRefLocal, BoundLocal) ' store to something that is not special. (operands still could be rewritten) If Not _info.TryGetValue(left.LocalSymbol, locInfo) Then Return MyBase.VisitReferenceAssignment(node) End If ' we do not need to visit lhs, just update the counter to be in sync Me._nodeCounter += 1 ' Visit the expression being assigned Dim right = DirectCast(Me.Visit(node.LValue), BoundExpression) ' this should not be the last store, why would be created such a variable after all??? Debug.Assert(locInfo.localDefs.Any(Function(d) _nodeCounter = d.Start AndAlso _nodeCounter <= d.End)) If IsLastAccess(locInfo, _nodeCounter) Then ' assigned local is not used later => just emit the Right Return right End If ' assigned local used later - keep assignment. ' codegen will keep value on stack when sees assignment "stackLocal = expr" Return node.Update(left, right, node.IsLValue, node.Type) End Function ' default visitor for AssignmentOperator that ignores LeftOnTheRightOpt Private Function VisitAssignmentOperatorDefault(node As BoundAssignmentOperator) As BoundNode Dim left As BoundExpression = DirectCast(Me.Visit(node.Left), BoundExpression) Dim right As BoundExpression = DirectCast(Me.Visit(node.Right), BoundExpression) Debug.Assert(node.LeftOnTheRightOpt Is Nothing) Return node.Update(left, Nothing, right, node.SuppressObjectClone, node.Type) End Function Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode Dim locInfo As LocalDefUseInfo = Nothing Dim left = TryCast(node.Left, BoundLocal) ' store to something that is not special. (operands still could be rewritten) If left Is Nothing OrElse Not _info.TryGetValue(left.LocalSymbol, locInfo) Then Return VisitAssignmentOperatorDefault(node) End If ' indirect local store is not special. (operands still could be rewritten) ' NOTE: if Lhs is a stack local, it will be handled as a read and possibly duped. Dim isIndirectLocalStore = left.LocalSymbol.IsByRef If isIndirectLocalStore Then Return VisitAssignmentOperatorDefault(node) End If '== here we have a regular write to a stack local ' ' we do not need to visit lhs, because we do not read the local, ' just update the counter to be in sync. ' ' if this is the last store, we just push the rhs ' otherwise record a store. ' fake visiting of left Me._nodeCounter += 1 ' Left on the right should be Nothing by this time Debug.Assert(node.LeftOnTheRightOpt Is Nothing) ' do not visit left-on-the-right ' Me.nodeCounter += 1 ' visit right Dim right = DirectCast(Me.Visit(node.Right), BoundExpression) ' do actual assignment Debug.Assert(locInfo.localDefs.Any(Function(d) _nodeCounter = d.Start AndAlso _nodeCounter <= d.End)) Dim isLast As Boolean = IsLastAccess(locInfo, _nodeCounter) If isLast Then ' assigned local is not used later => just emit the Right Return right Else ' assigned local used later - keep assignment. ' codegen will keep value on stack when sees assignment "stackLocal = expr" Return node.Update(left, node.LeftOnTheRightOpt, right, node.SuppressObjectClone, node.Type) End If End Function Public Overrides Function VisitLoweredConditionalAccess(node As BoundLoweredConditionalAccess) As BoundNode Dim receiverOrCondition As BoundExpression = DirectCast(Me.Visit(node.ReceiverOrCondition), BoundExpression) Dim whenNotNull As BoundExpression = DirectCast(Me.Visit(node.WhenNotNull), BoundExpression) Dim whenNullOpt As BoundExpression = node.WhenNullOpt If whenNullOpt IsNot Nothing Then whenNullOpt = DirectCast(Me.Visit(whenNullOpt), BoundExpression) End If Return node.Update(receiverOrCondition, node.CaptureReceiver, node.PlaceholderId, whenNotNull, whenNullOpt, node.Type) End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGen Partial Friend Class StackScheduler ''' <summary> ''' Rewrites the tree to account for destructive nature of stack local reads. ''' ''' Typically, last read stays as-is and local is destroyed by the read. ''' Intermediate reads are rewritten as Dups - ''' ''' NotLastUse(X_stackLocal) ===> NotLastUse(Dup) ''' LastUse(X_stackLocal) ===> LastUse(X_stackLocal) ''' ''' </summary> Private NotInheritable Class Rewriter Inherits BoundTreeRewriterWithStackGuard Private _nodeCounter As Integer = 0 Private ReadOnly _info As Dictionary(Of LocalSymbol, LocalDefUseInfo) = Nothing Private Sub New(info As Dictionary(Of LocalSymbol, LocalDefUseInfo)) Me._info = info End Sub Public Shared Function Rewrite(src As BoundStatement, info As Dictionary(Of LocalSymbol, LocalDefUseInfo)) As BoundStatement Dim scheduler As New Rewriter(info) Return DirectCast(scheduler.Visit(src), BoundStatement) End Function Public Overrides Function Visit(node As BoundNode) As BoundNode Dim result As BoundNode = Nothing ' rewriting constants may undo constant folding and make thing worse. ' so we will not go into constant nodes. ' CodeGen will not do that either. Dim asExpression = TryCast(node, BoundExpression) If asExpression IsNot Nothing AndAlso asExpression.ConstantValueOpt IsNot Nothing Then result = node Else result = MyBase.Visit(node) End If Me._nodeCounter += 1 Return result End Function Public Overrides Function VisitBinaryOperator(node As BoundBinaryOperator) As BoundNode ' Do not blow the stack due to a deep recursion on the left. Dim child As BoundExpression = node.Left If child.Kind <> BoundKind.BinaryOperator OrElse child.ConstantValueOpt IsNot Nothing Then Return VisitBinaryOperatorSimple(node) End If Dim stack = ArrayBuilder(Of BoundBinaryOperator).GetInstance() stack.Push(node) Dim binary As BoundBinaryOperator = DirectCast(child, BoundBinaryOperator) Do stack.Push(binary) child = binary.Left If child.Kind <> BoundKind.BinaryOperator OrElse child.ConstantValueOpt IsNot Nothing Then Exit Do End If binary = DirectCast(child, BoundBinaryOperator) Loop Dim left = DirectCast(Me.Visit(child), BoundExpression) Do binary = stack.Pop() Dim right = DirectCast(Me.Visit(binary.Right), BoundExpression) Dim type As TypeSymbol = Me.VisitType(binary.Type) left = binary.Update(binary.OperatorKind, left, right, binary.Checked, binary.ConstantValueOpt, type) If stack.Count = 0 Then Exit Do End If Me._nodeCounter += 1 Loop Debug.Assert(binary Is node) stack.Free() Return left End Function Private Function VisitBinaryOperatorSimple(node As BoundBinaryOperator) As BoundNode Return MyBase.VisitBinaryOperator(node) End Function Private Shared Function IsLastAccess(locInfo As LocalDefUseInfo, counter As Integer) As Boolean Return locInfo.localDefs.Any(Function(d) counter = d.Start AndAlso counter = d.End) End Function Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode Dim locInfo As LocalDefUseInfo = Nothing If Not _info.TryGetValue(node.LocalSymbol, locInfo) Then Return MyBase.VisitLocal(node) End If ' not the last access, emit Dup. If Not IsLastAccess(locInfo, _nodeCounter) Then Return New BoundDup(node.Syntax, node.LocalSymbol.IsByRef, node.Type) End If ' last access - leave the node as is. Emit will do nothing expecting the node on the stack Return MyBase.VisitLocal(node) End Function ' TODO: Why?? 'Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode ' Dim arguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Arguments) ' Debug.Assert(node.InitializerOpt Is Nothing) ' Dim type As TypeSymbol = Me.VisitType(node.Type) ' Return node.Update(node.ConstructorOpt, arguments, node.InitializerOpt, type) 'End Function Public Overrides Function VisitReferenceAssignment(node As BoundReferenceAssignment) As BoundNode Dim locInfo As LocalDefUseInfo = Nothing Dim left = DirectCast(node.ByRefLocal, BoundLocal) ' store to something that is not special. (operands still could be rewritten) If Not _info.TryGetValue(left.LocalSymbol, locInfo) Then Return MyBase.VisitReferenceAssignment(node) End If ' we do not need to visit lhs, just update the counter to be in sync Me._nodeCounter += 1 ' Visit the expression being assigned Dim right = DirectCast(Me.Visit(node.LValue), BoundExpression) ' this should not be the last store, why would be created such a variable after all??? Debug.Assert(locInfo.localDefs.Any(Function(d) _nodeCounter = d.Start AndAlso _nodeCounter <= d.End)) If IsLastAccess(locInfo, _nodeCounter) Then ' assigned local is not used later => just emit the Right Return right End If ' assigned local used later - keep assignment. ' codegen will keep value on stack when sees assignment "stackLocal = expr" Return node.Update(left, right, node.IsLValue, node.Type) End Function ' default visitor for AssignmentOperator that ignores LeftOnTheRightOpt Private Function VisitAssignmentOperatorDefault(node As BoundAssignmentOperator) As BoundNode Dim left As BoundExpression = DirectCast(Me.Visit(node.Left), BoundExpression) Dim right As BoundExpression = DirectCast(Me.Visit(node.Right), BoundExpression) Debug.Assert(node.LeftOnTheRightOpt Is Nothing) Return node.Update(left, Nothing, right, node.SuppressObjectClone, node.Type) End Function Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode Dim locInfo As LocalDefUseInfo = Nothing Dim left = TryCast(node.Left, BoundLocal) ' store to something that is not special. (operands still could be rewritten) If left Is Nothing OrElse Not _info.TryGetValue(left.LocalSymbol, locInfo) Then Return VisitAssignmentOperatorDefault(node) End If ' indirect local store is not special. (operands still could be rewritten) ' NOTE: if Lhs is a stack local, it will be handled as a read and possibly duped. Dim isIndirectLocalStore = left.LocalSymbol.IsByRef If isIndirectLocalStore Then Return VisitAssignmentOperatorDefault(node) End If '== here we have a regular write to a stack local ' ' we do not need to visit lhs, because we do not read the local, ' just update the counter to be in sync. ' ' if this is the last store, we just push the rhs ' otherwise record a store. ' fake visiting of left Me._nodeCounter += 1 ' Left on the right should be Nothing by this time Debug.Assert(node.LeftOnTheRightOpt Is Nothing) ' do not visit left-on-the-right ' Me.nodeCounter += 1 ' visit right Dim right = DirectCast(Me.Visit(node.Right), BoundExpression) ' do actual assignment Debug.Assert(locInfo.localDefs.Any(Function(d) _nodeCounter = d.Start AndAlso _nodeCounter <= d.End)) Dim isLast As Boolean = IsLastAccess(locInfo, _nodeCounter) If isLast Then ' assigned local is not used later => just emit the Right Return right Else ' assigned local used later - keep assignment. ' codegen will keep value on stack when sees assignment "stackLocal = expr" Return node.Update(left, node.LeftOnTheRightOpt, right, node.SuppressObjectClone, node.Type) End If End Function Public Overrides Function VisitLoweredConditionalAccess(node As BoundLoweredConditionalAccess) As BoundNode Dim receiverOrCondition As BoundExpression = DirectCast(Me.Visit(node.ReceiverOrCondition), BoundExpression) Dim whenNotNull As BoundExpression = DirectCast(Me.Visit(node.WhenNotNull), BoundExpression) Dim whenNullOpt As BoundExpression = node.WhenNullOpt If whenNullOpt IsNot Nothing Then whenNullOpt = DirectCast(Me.Visit(whenNullOpt), BoundExpression) End If Return node.Update(receiverOrCondition, node.CaptureReceiver, node.PlaceholderId, whenNotNull, whenNullOpt, node.Type) End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/VisualStudio/CSharp/Test/PersistentStorage/Mocks/AuthorizationServiceMock.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. // Copy of https://devdiv.visualstudio.com/DevDiv/_git/VS.CloudCache?path=%2Ftest%2FMicrosoft.VisualStudio.Cache.Tests%2FMocks&_a=contents&version=GBmain // Try to keep in sync and avoid unnecessary changes here. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceHub.Framework.Services; #pragma warning disable CS0067 // events that are never used namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks { internal class AuthorizationServiceMock : IAuthorizationService { public event EventHandler? CredentialsChanged; public event EventHandler? AuthorizationChanged; internal bool Allow { get; set; } = true; public ValueTask<bool> CheckAuthorizationAsync(ProtectedOperation operation, CancellationToken cancellationToken = default) { return new ValueTask<bool>(this.Allow); } public ValueTask<IReadOnlyDictionary<string, string>> GetCredentialsAsync(CancellationToken cancellationToken = default) { throw new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // Copy of https://devdiv.visualstudio.com/DevDiv/_git/VS.CloudCache?path=%2Ftest%2FMicrosoft.VisualStudio.Cache.Tests%2FMocks&_a=contents&version=GBmain // Try to keep in sync and avoid unnecessary changes here. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceHub.Framework.Services; #pragma warning disable CS0067 // events that are never used namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks { internal class AuthorizationServiceMock : IAuthorizationService { public event EventHandler? CredentialsChanged; public event EventHandler? AuthorizationChanged; internal bool Allow { get; set; } = true; public ValueTask<bool> CheckAuthorizationAsync(ProtectedOperation operation, CancellationToken cancellationToken = default) { return new ValueTask<bool>(this.Allow); } public ValueTask<IReadOnlyDictionary<string, string>> GetCredentialsAsync(CancellationToken cancellationToken = default) { throw new NotImplementedException(); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/EditorFeatures/TestUtilities2/Intellisense/IIntelliSenseTestState.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense Friend Interface IIntelliSenseTestState Property CurrentSignatureHelpPresenterSession As TestSignatureHelpPresenterSession End Interface End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense Friend Interface IIntelliSenseTestState Property CurrentSignatureHelpPresenterSession As TestSignatureHelpPresenterSession End Interface End Namespace
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/EditorFeatures/Core/IInlineRenameSession.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.Editor { internal class InlineRenameSessionInfo { /// <summary> /// Whether or not the entity at the selected location can be renamed. /// </summary> public bool CanRename { get; } /// <summary> /// Provides the reason that can be displayed to the user if the entity at the selected /// location cannot be renamed. /// </summary> public string LocalizedErrorMessage { get; } /// <summary> /// The session created if it was possible to rename the entity. /// </summary> public IInlineRenameSession Session { get; } internal InlineRenameSessionInfo(string localizedErrorMessage) { this.CanRename = false; this.LocalizedErrorMessage = localizedErrorMessage; } internal InlineRenameSessionInfo(IInlineRenameSession session) { this.CanRename = true; this.Session = session; } } internal interface IInlineRenameSession { /// <summary> /// Cancels the rename session, and undoes any edits that had been performed by the session. /// </summary> void Cancel(); /// <summary> /// Dismisses the rename session, completing the rename operation across all files. /// </summary> void Commit(bool previewChanges = 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 namespace Microsoft.CodeAnalysis.Editor { internal class InlineRenameSessionInfo { /// <summary> /// Whether or not the entity at the selected location can be renamed. /// </summary> public bool CanRename { get; } /// <summary> /// Provides the reason that can be displayed to the user if the entity at the selected /// location cannot be renamed. /// </summary> public string LocalizedErrorMessage { get; } /// <summary> /// The session created if it was possible to rename the entity. /// </summary> public IInlineRenameSession Session { get; } internal InlineRenameSessionInfo(string localizedErrorMessage) { this.CanRename = false; this.LocalizedErrorMessage = localizedErrorMessage; } internal InlineRenameSessionInfo(IInlineRenameSession session) { this.CanRename = true; this.Session = session; } } internal interface IInlineRenameSession { /// <summary> /// Cancels the rename session, and undoes any edits that had been performed by the session. /// </summary> void Cancel(); /// <summary> /// Dismisses the rename session, completing the rename operation across all files. /// </summary> void Commit(bool previewChanges = false); } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/ExtensionMethods/ExtensionMethodTests.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.IO Imports Microsoft.CodeAnalysis.CSharp Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods Public Class ExtensionMethodTests : Inherits BasicTestBase <Fact> Public Sub DetectingExtensionAttributeOnImport1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="DetectingExtensionAttributeOnImport"> <file name="a.vb"> Module Module1 Sub Main() End Sub End Module </file> </compilation>, {Net40.SystemCore}) Dim enumerable As NamedTypeSymbol = compilation1.GetTypeByMetadataName("System.Linq.Enumerable") Assert.True(enumerable.ContainingAssembly.MightContainExtensionMethods) Assert.True(enumerable.ContainingModule.MightContainExtensionMethods) Assert.True(enumerable.MightContainExtensionMethods) For Each [select] As MethodSymbol In enumerable.GetMembers("Select") Assert.True([select].IsExtensionMethod) Next End Sub <Fact> Public Sub DetectingExtensionAttributeOnImport2() Dim customIL = <![CDATA[ .assembly extern mscorlib { } .assembly extern System.Core { } .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .module '<<GeneratedFileName>>.dll' // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi Module1 extends [mscorlib]System.Object { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Module1::.ctor .method private specialname rtspecialname static void .cctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::.cctor .method public static void Test1(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test1 .method public specialname static int32 get_Test2() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test2 .method public specialname static int32 get_Test3() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test3 .method public specialname static void set_Test3(int32 'value') cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::set_Test3 .method public static void Test4() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test4 .method public static void Test5([opt] int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] = int32(0x00000000) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test5 .method public static void Test6(int32[] x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test6 .method public static void Test7<(class [mscorlib]System.Collections.Generic.IList`1<!!U[]>) T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test7 .method public static void Test8<T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test8 .method public instance void Test9(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test9 .property int32 Test2() { .get int32 Module1::get_Test2() } // end of property Module1::Test2 .property int32 Test3() { .get int32 Module1::get_Test3() .set void Module1::set_Test3(int32) } // end of property Module1::Test3 } // end of class Module1]]> Using reference = IlasmUtilities.CreateTempAssembly(customIL.Value, prependDefaultHeader:=False) Dim ILRef = MetadataReference.CreateFromImage(ReadFromFile(reference.Path)) Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="DetectingExtensionAttributeOnImport"> <file name="a.vb"> Module M1 Sub Main() End Sub End Module </file> </compilation>, {ILRef}) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1") Assert.NotSame(compilation1.Assembly, module1.ContainingAssembly) Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) Assert.True(module1.ContainingModule.MightContainExtensionMethods) Assert.True(module1.MightContainExtensionMethods) For Each method As MethodSymbol In module1.GetMembers().OfType(Of MethodSymbol)() Select Case method.Name Case "Test1", "Test8" Assert.True(method.IsExtensionMethod) Case Else Assert.False(method.IsExtensionMethod) End Select Next Assert.Equal(13, module1.GetMembers().Length) End Using End Sub <Fact> Public Sub DetectingExtensionAttributeOnImport3() Dim customIL = <![CDATA[ .assembly extern mscorlib { } .assembly extern System.Core { } .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .module '<<GeneratedFileName>>.dll' // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi Module2 extends [mscorlib]System.Object { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .class auto ansi nested public Module1 extends [mscorlib]System.Object { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Module1::.ctor .method private specialname rtspecialname static void .cctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::.cctor .method public static void Test1(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test1 .method public specialname static int32 get_Test2() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test2 .method public specialname static int32 get_Test3() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test3 .method public specialname static void set_Test3(int32 'value') cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::set_Test3 .method public static void Test4() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test4 .method public static void Test5([opt] int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] = int32(0x00000000) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test5 .method public static void Test6(int32[] x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test6 .method public static void Test7<(class [mscorlib]System.Collections.Generic.IList`1<!!U[]>) T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test7 .method public static void Test8<T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test8 .method public instance void Test9(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test9 .property int32 Test2() { .get int32 Module2/Module1::get_Test2() } // end of property Module1::Test2 .property int32 Test3() { .get int32 Module2/Module1::get_Test3() .set void Module2/Module1::set_Test3(int32) } // end of property Module1::Test3 } // end of class Module1 } // end of class Module2 ]]> Using reference = IlasmUtilities.CreateTempAssembly(customIL.Value, prependDefaultHeader:=False) Dim ILRef = MetadataReference.CreateFromImage(ReadFromFile(reference.Path)) Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="DetectingExtensionAttributeOnImport"> <file name="a.vb"> Module M1 Sub Main() End Sub End Module </file> </compilation>, {ILRef}) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module2+Module1") Assert.NotSame(compilation1.Assembly, module1.ContainingAssembly) Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) Assert.True(module1.ContainingModule.MightContainExtensionMethods) Assert.True(module1.ContainingType.MightContainExtensionMethods) Assert.False(module1.MightContainExtensionMethods) For Each method As MethodSymbol In module1.GetMembers().OfType(Of MethodSymbol)() Assert.False(method.IsExtensionMethod) Next Assert.Equal(13, module1.GetMembers().Length) End Using End Sub <Fact> Public Sub DetectingExtensionAttributeOnImport4() Dim customIL = <![CDATA[ .assembly extern mscorlib { } .assembly extern System.Core { } .assembly '<<GeneratedFileName>>' { } .module '<<GeneratedFileName>>.dll' // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi Module1 extends [mscorlib]System.Object { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Module1::.ctor .method private specialname rtspecialname static void .cctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::.cctor .method public static void Test1(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test1 .method public specialname static int32 get_Test2() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test2 .method public specialname static int32 get_Test3() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test3 .method public specialname static void set_Test3(int32 'value') cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::set_Test3 .method public static void Test4() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test4 .method public static void Test5([opt] int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] = int32(0x00000000) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test5 .method public static void Test6(int32[] x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test6 .method public static void Test7<(class [mscorlib]System.Collections.Generic.IList`1<!!U[]>) T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test7 .method public static void Test8<T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test8 .method public instance void Test9(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test9 .property int32 Test2() { .get int32 Module1::get_Test2() } // end of property Module1::Test2 .property int32 Test3() { .get int32 Module1::get_Test3() .set void Module1::set_Test3(int32) } // end of property Module1::Test3 } // end of class Module1]]> Using reference = IlasmUtilities.CreateTempAssembly(customIL.Value, prependDefaultHeader:=False) Dim ILRef = MetadataReference.CreateFromImage(ReadFromFile(reference.Path)) Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="DetectingExtensionAttributeOnImport"> <file name="a.vb"> Module M1 Sub Main() End Sub End Module </file> </compilation>, {ILRef}) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1") Assert.NotSame(compilation1.Assembly, module1.ContainingAssembly) Assert.False(module1.ContainingAssembly.MightContainExtensionMethods) Assert.False(module1.ContainingModule.MightContainExtensionMethods) Assert.False(module1.MightContainExtensionMethods) For Each method As MethodSymbol In module1.GetMembers().OfType(Of MethodSymbol)() Assert.False(method.IsExtensionMethod) Next Assert.Equal(13, module1.GetMembers().Length) End Using End Sub <Fact> Public Sub DetectingExtensionAttributeOnImport5() Dim customIL = <![CDATA[ .assembly extern mscorlib { } .assembly extern System.Core { } .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .module '<<GeneratedFileName>>.dll' // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi Module1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Module1::.ctor .method private specialname rtspecialname static void .cctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::.cctor .method public static void Test1(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test1 .method public specialname static int32 get_Test2() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test2 .method public specialname static int32 get_Test3() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test3 .method public specialname static void set_Test3(int32 'value') cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::set_Test3 .method public static void Test4() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test4 .method public static void Test5([opt] int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] = int32(0x00000000) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test5 .method public static void Test6(int32[] x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test6 .method public static void Test7<(class [mscorlib]System.Collections.Generic.IList`1<!!U[]>) T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test7 .method public static void Test8<T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test8 .method public instance void Test9(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test9 .property int32 Test2() { .get int32 Module1::get_Test2() } // end of property Module1::Test2 .property int32 Test3() { .get int32 Module1::get_Test3() .set void Module1::set_Test3(int32) } // end of property Module1::Test3 } // end of class Module1]]> Using reference = IlasmUtilities.CreateTempAssembly(customIL.Value, prependDefaultHeader:=False) Dim ILRef = MetadataReference.CreateFromImage(ReadFromFile(reference.Path)) Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="DetectingExtensionAttributeOnImport"> <file name="a.vb"> Module M1 Sub Main() End Sub End Module </file> </compilation>, {ILRef}) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1") Assert.NotSame(compilation1.Assembly, module1.ContainingAssembly) Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) Assert.True(module1.ContainingModule.MightContainExtensionMethods) Assert.False(module1.MightContainExtensionMethods) For Each method As MethodSymbol In module1.GetMembers().OfType(Of MethodSymbol)() Assert.False(method.IsExtensionMethod) Next Assert.Equal(13, module1.GetMembers().Length) End Using End Sub <Fact> Public Sub DetectingExtensionAttributeOnImport6() Dim customIL = <![CDATA[ .assembly extern mscorlib { } .assembly extern System.Core { } .module '<<GeneratedFileName>>.dll' // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi Module1 extends [mscorlib]System.Object { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Module1::.ctor .method private specialname rtspecialname static void .cctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::.cctor .method public static void Test1(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test1 .method public specialname static int32 get_Test2() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test2 .method public specialname static int32 get_Test3() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test3 .method public specialname static void set_Test3(int32 'value') cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::set_Test3 .method public static void Test4() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test4 .method public static void Test5([opt] int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] = int32(0x00000000) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test5 .method public static void Test6(int32[] x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test6 .method public static void Test7<(class [mscorlib]System.Collections.Generic.IList`1<!!U[]>) T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test7 .method public static void Test8<T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test8 .method public instance void Test9(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test9 .property int32 Test2() { .get int32 Module1::get_Test2() } // end of property Module1::Test2 .property int32 Test3() { .get int32 Module1::get_Test3() .set void Module1::set_Test3(int32) } // end of property Module1::Test3 } // end of class Module1 // ============================================================= .custom ([mscorlib]System.Runtime.CompilerServices.AssemblyAttributesGoHere) instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ]]> Using reference = IlasmUtilities.CreateTempAssembly(customIL.Value, prependDefaultHeader:=False) Dim ILRef = ModuleMetadata.CreateFromImage(File.ReadAllBytes(reference.Path)).GetReference() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="DetectingExtensionAttributeOnImport"> <file name="a.vb"> Module M1 Sub Main() End Sub End Module </file> </compilation>, {ILRef}) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1") Assert.Same(compilation1.Assembly, module1.ContainingAssembly) Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) Assert.NotSame(compilation1.Assembly.Modules(0), module1.ContainingModule) Assert.False(module1.ContainingModule.MightContainExtensionMethods) Assert.False(module1.MightContainExtensionMethods) For Each method As MethodSymbol In module1.GetMembers().OfType(Of MethodSymbol)() Assert.False(method.IsExtensionMethod) Next Assert.Equal(13, module1.GetMembers().Length) End Using End Sub <Fact> Public Sub MightContainExtensionMethods_InSource() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="MightContainExtensionMethods_InSource"> <file name="a.vb"> Module Module1 Module Module2 End Module End Module Class Class1 End Class </file> </compilation>) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1") Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) Assert.True(module1.ContainingModule.MightContainExtensionMethods) Assert.False(module1.MightContainExtensionMethods) Dim module2 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1+Module2") Assert.False(module2.MightContainExtensionMethods) Assert.Equal(TypeKind.Module, module2.TypeKind) Dim class1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Class1") Assert.False(class1.MightContainExtensionMethods) End Sub <Fact> Public Sub DeclaringExtensionMethods1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DeclaringExtensionMethod1"> <file name="a.vb"> Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 Sub Test1(x As Integer) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test2 ReadOnly Property Test2 As Integer Get Return Nothing End Get End Property Property Test3 As Integer &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Get Get Return Nothing End Get &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Set Set End Set End Property &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test4 Sub Test4() End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test5 Sub Test5(Optional x As Integer = 0) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test6 Sub Test6(ParamArray x As Integer()) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test7 Sub Test7(Of T As U, U)(x As T) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test8 Sub Test8(Of T, U)(x As T) End Sub End Module </file> </compilation>, {Net40.SystemCore}) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1") For Each method As MethodSymbol In module1.GetMembers().OfType(Of MethodSymbol)() Select Case method.Name Case "Test1", "Test8" Assert.True(method.IsExtensionMethod) Case Else Assert.False(method.IsExtensionMethod) End Select Next CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'Test2' because the attribute is not valid on this declaration type. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Get ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Set ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36552: Extension methods must declare at least one parameter. The first parameter specifies which type to extend. Sub Test4() ~~~~~ BC36553: 'Optional' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend. Sub Test5(Optional x As Integer = 0) ~ BC36554: 'ParamArray' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend. Sub Test6(ParamArray x As Integer()) ~ BC36561: Extension method 'Test7' has type constraints that can never be satisfied. Sub Test7(Of T As U, U)(x As T) ~~~~~ </expected>) End Sub <Fact> Public Sub DeclaringExtensionMethods2() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="DeclaringExtensionMethod2"> <file name="a.vb"> Class Module2 &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test1 Sub Test1(x As Integer) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test2 ReadOnly Property Test2 As Integer Get Return Nothing End Get End Property Property Test3 As Integer &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Get Get Return Nothing End Get &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Set Set End Set End Property &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test4 Sub Test4() End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test5 Sub Test5(Optional x As Integer = 0) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test6 Sub Test6(ParamArray x As Integer()) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test7 Sub Test7(Of T As U, U)(x As T) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test8 Sub Test8(Of T, U)(x As T) End Sub End Class </file> </compilation>, {Net40.SystemCore}) Dim module2 As NamedTypeSymbol = compilation2.GetTypeByMetadataName("Module2") For Each method As MethodSymbol In module2.GetMembers().OfType(Of MethodSymbol)() Assert.False(method.IsExtensionMethod) Next CompilationUtils.AssertTheseDiagnostics(compilation2, <expected> BC36551: Extension methods can be defined only in modules. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'Test2' because the attribute is not valid on this declaration type. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Get ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Set ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36551: Extension methods can be defined only in modules. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36551: Extension methods can be defined only in modules. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36551: Extension methods can be defined only in modules. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test6 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36551: Extension methods can be defined only in modules. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test7 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36551: Extension methods can be defined only in modules. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test8 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub DeclaringExtensionMethods3() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DeclaringExtensionMethod3"> <file name="a.vb"> &lt;System.Runtime.CompilerServices.Extension()&gt; 'C Class C End Class &lt;System.Runtime.CompilerServices.Extension()&gt; 'S Structure S End Structure &lt;System.Runtime.CompilerServices.Extension()&gt; 'I Interface I End Interface &lt;System.Runtime.CompilerServices.Extension()&gt; 'E Enum E x End Enum &lt;System.Runtime.CompilerServices.Extension()&gt; 'M Module M End Module &lt;System.Runtime.CompilerServices.Extension()&gt; 'D Delegate Sub D() </file> </compilation>, {Net40.SystemCore}) For Each type As NamedTypeSymbol In compilation2.SourceModule.GlobalNamespace.GetTypeMembers() Assert.False(type.MightContainExtensionMethods) Next CompilationUtils.AssertTheseDiagnostics(compilation2, <expected> BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. Class C ~ BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'S' because the attribute is not valid on this declaration type. &lt;System.Runtime.CompilerServices.Extension()&gt; 'S ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'I' because the attribute is not valid on this declaration type. &lt;System.Runtime.CompilerServices.Extension()&gt; 'I ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'E' because the attribute is not valid on this declaration type. &lt;System.Runtime.CompilerServices.Extension()&gt; 'E ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'D' because the attribute is not valid on this declaration type. &lt;System.Runtime.CompilerServices.Extension()&gt; 'D ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub DeclaringExtensionMethods4() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DeclaringExtensionMethod4"> <file name="a.vb"> Module Module2 &lt;System.Runtime.CompilerServices.Extension()&gt; 'Module1 Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 Sub Test1(x As Integer) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test2 ReadOnly Property Test2 As Integer Get Return Nothing End Get End Property Property Test3 As Integer &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Get Get Return Nothing End Get &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Set Set End Set End Property &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test4 Sub Test4() End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test5 Sub Test5(Optional x As Integer = 0) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test6 Sub Test6(ParamArray x As Integer()) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test7 Sub Test7(Of T As U, U)(x As T) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test8 Sub Test8(Of T, U)(x As T) End Sub End Module End Module </file> </compilation>, {Net40.SystemCore}) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module2+Module1") Assert.False(module1.MightContainExtensionMethods) For Each method As MethodSymbol In module1.GetMembers().OfType(Of MethodSymbol)() Assert.False(method.IsExtensionMethod) Next CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30617: 'Module' statements can occur only at file or namespace level. &lt;System.Runtime.CompilerServices.Extension()&gt; 'Module1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'Test2' because the attribute is not valid on this declaration type. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Get ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Set ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36552: Extension methods must declare at least one parameter. The first parameter specifies which type to extend. Sub Test4() ~~~~~ BC36553: 'Optional' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend. Sub Test5(Optional x As Integer = 0) ~ BC36554: 'ParamArray' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend. Sub Test6(ParamArray x As Integer()) ~ BC36561: Extension method 'Test7' has type constraints that can never be satisfied. Sub Test7(Of T As U, U)(x As T) ~~~~~ </expected>) End Sub <Fact> Public Sub DetectingAbsenceOfExtensionMethods1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DeclaringExtensionMethod1"> <file name="a.vb"> Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 Sub Test1(x As Integer) End Sub End Module </file> </compilation>) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1") Assert.True(module1.MightContainExtensionMethods) Assert.True(module1.ContainingModule.MightContainExtensionMethods) Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) DirectCast(module1, SourceNamedTypeSymbol).GenerateDeclarationErrors(Nothing) Assert.False(module1.MightContainExtensionMethods) Assert.True(module1.ContainingModule.MightContainExtensionMethods) Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) Dim containsExtensions As Boolean DirectCast(module1.ContainingModule, SourceModuleSymbol).GetAllDeclarationErrors(BindingDiagnosticBag.Discarded, Nothing, containsExtensions) Assert.False(module1.MightContainExtensionMethods) Assert.False(module1.ContainingModule.MightContainExtensionMethods) Assert.False(module1.ContainingAssembly.MightContainExtensionMethods) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, <expected> BC30002: Type 'System.Runtime.CompilerServices.Extension' is not defined. &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub DetectingAbsenceOfExtensionMethods2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DeclaringExtensionMethod1"> <file name="a.vb"> Module Module1 Module Module2 &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 Sub Test1(x As Integer) End Sub End Module End Module </file> </compilation>, {Net40.SystemCore}) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1") Assert.False(module1.MightContainExtensionMethods) Assert.True(module1.ContainingModule.MightContainExtensionMethods) Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) DirectCast(module1, SourceNamedTypeSymbol).GenerateDeclarationErrors(Nothing) Assert.False(module1.MightContainExtensionMethods) Assert.True(module1.ContainingModule.MightContainExtensionMethods) Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) Dim containsExtensions As Boolean DirectCast(module1.ContainingModule, SourceModuleSymbol).GetAllDeclarationErrors(BindingDiagnosticBag.Discarded, Nothing, containsExtensions) Assert.False(module1.MightContainExtensionMethods) Assert.False(module1.ContainingModule.MightContainExtensionMethods) Assert.False(module1.ContainingAssembly.MightContainExtensionMethods) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30617: 'Module' statements can occur only at file or namespace level. Module Module2 ~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub EmitExtensionAttribute1() Dim compilationDef = <compilation name="EmitExtensionAttribute1"> <file name="a.vb"> Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; Sub Test1(x As Integer) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={Net40.SystemCore}, symbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(1, m.ContainingAssembly. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Dim module1 = m.ContainingAssembly.GetTypeByMetadataName("Module1") Assert.Equal(1, module1. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Assert.Equal(1, module1.GetMember("Test1"). GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) End Sub) End Sub <Fact> Public Sub EmitExtensionAttribute2() Dim compilationDef = <compilation name="EmitExtensionAttribute2"> <file name="a.vb"> &lt;System.Runtime.CompilerServices.Extension()&gt; Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; Sub Test1(x As Integer) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={Net40.SystemCore}, symbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(1, m.ContainingAssembly. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Dim module1 = m.ContainingAssembly.GetTypeByMetadataName("Module1") Assert.Equal(1, module1. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Assert.Equal(1, module1.GetMember("Test1"). GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) End Sub) End Sub <Fact> Public Sub EmitExtensionAttribute3() Dim compilationDef = <compilation name="EmitExtensionAttribute3"> <file name="a.vb"> &lt;Assembly:System.Runtime.CompilerServices.Extension()&gt; &lt;System.Runtime.CompilerServices.Extension()&gt; Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; Sub Test1(x As Integer) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={Net40.SystemCore}, symbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(1, m.ContainingAssembly. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Dim module1 = m.ContainingAssembly.GetTypeByMetadataName("Module1") Assert.Equal(1, module1. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Assert.Equal(1, module1.GetMember("Test1"). GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) End Sub) End Sub <Fact> Public Sub EmitExtensionAttribute4() Dim compilationDef = <compilation name="EmitExtensionAttribute4"> <file name="a.vb"> &lt;Assembly:System.Runtime.CompilerServices.Extension()&gt; &lt;System.Runtime.CompilerServices.Extension()&gt; Module Module1 Sub Test1(x As Integer) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={Net40.SystemCore}, symbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(1, m.ContainingAssembly. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Dim module1 = m.ContainingAssembly.GetTypeByMetadataName("Module1") Assert.Equal(1, module1. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Assert.Equal(0, module1.GetMember("Test1"). GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) End Sub) End Sub <Fact> Public Sub EmitExtensionAttribute5() Dim compilationDef = <compilation name="EmitExtensionAttribute5"> <file name="a.vb"> &lt;System.Runtime.CompilerServices.Extension()&gt; Module Module1 Sub Test1(x As Integer) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={Net40.SystemCore}, symbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(0, m.ContainingAssembly. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Dim module1 = m.ContainingAssembly.GetTypeByMetadataName("Module1") Assert.Equal(1, module1. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Assert.Equal(0, module1.GetMember("Test1"). GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) End Sub) End Sub <Fact> Public Sub EmitExtensionAttribute6() Dim compilationDef = <compilation name="EmitExtensionAttribute6"> <file name="a.vb"> Module Module1 Sub Test1(x As Integer) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={Net40.SystemCore}, symbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(0, m.ContainingAssembly. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Dim module1 = m.ContainingAssembly.GetTypeByMetadataName("Module1") Assert.Equal(0, module1. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Assert.Equal(0, module1.GetMember("Test1"). GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) End Sub) End Sub <Fact> Public Sub EmitExtensionAttribute7() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="EmitExtensionAttribute7_1"> <file name="a.vb"> Namespace System.Runtime.CompilerServices Class ExtensionAttribute End Class End Namespace </file> </compilation>) CompilationUtils.AssertNoErrors(compilation2) Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="EmitExtensionAttribute7_2"> <file name="a.vb"> Namespace System.Runtime.CompilerServices Class ExtensionAttribute End Class End Namespace </file> </compilation>) CompilationUtils.AssertNoErrors(compilation3) Dim compilation1Def = <compilation name="EmitExtensionAttribute7_3"> <file name="a.vb"> Module Module1 Sub Main() Call 345.Test1() End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 Sub Test1(x As Integer) System.Console.WriteLine(x) End Sub End Module </file> </compilation> Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilation1Def, {Net40.SystemCore, New VisualBasicCompilationReference(compilation2), New VisualBasicCompilationReference(compilation3)}, TestOptions.ReleaseExe) CompileAndVerify(compilation1, expectedOutput:="345") Dim compilation3_1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="EmitExtensionAttribute7_3_1"> <file name="a.vb"> Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Public Class extensionattribute : Inherits Attribute End Class End Namespace </file> </compilation>) Dim compilation1_1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilation1Def, {Net40.SystemCore, New VisualBasicCompilationReference(compilation3_1)}, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1_1, <expected> <![CDATA[ BC30560: 'ExtensionAttribute' is ambiguous in the namespace 'System.Runtime.CompilerServices'. <System.Runtime.CompilerServices.Extension()> 'Test1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </expected>) CompilationUtils.AssertTheseDiagnostics(compilation1_1, <expected> <![CDATA[ BC30456: 'Test1' is not a member of 'Integer'. Call 345.Test1() ~~~~~~~~~ BC30560: 'ExtensionAttribute' is ambiguous in the namespace 'System.Runtime.CompilerServices'. <System.Runtime.CompilerServices.Extension()> 'Test1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </expected>) Dim compilation3_2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="EmitExtensionAttribute7_3_2"> <file name="a.vb"> Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Friend Class extensionattribute : Inherits Attribute End Class End Namespace </file> </compilation>) Dim compilation1_2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilation1Def, {Net40.SystemCore, New VisualBasicCompilationReference(compilation3_2)}, TestOptions.ReleaseExe) CompileAndVerify(compilation1_2, expectedOutput:="345") Dim compilation1_3_Def = <compilation name="EmitExtensionAttribute7_3"> <file name="a.vb"> Module Module1 Sub Main() Call 345.Test1() End Sub &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; 'Test1 Sub Test1(x As Integer) System.Console.WriteLine(x) End Sub End Module </file> </compilation> Dim compilation1_3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilation1_3_Def, {Net40.SystemCore, New VisualBasicCompilationReference(compilation3_1)}, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1_3, <expected> BC30560: 'ExtensionAttribute' is ambiguous in the namespace 'System.Runtime.CompilerServices'. &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; 'Test1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) CompilationUtils.AssertTheseDiagnostics(compilation1_3, <expected> BC30456: 'Test1' is not a member of 'Integer'. Call 345.Test1() ~~~~~~~~~ BC30560: 'ExtensionAttribute' is ambiguous in the namespace 'System.Runtime.CompilerServices'. &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; 'Test1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Dim compilation1_4_Def = <compilation name="EmitExtensionAttribute7_3"> <file name="a.vb"> Module Module1 Sub Main() Call 345.Test1() End Sub &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; 'Test1 Sub Test1(x As Integer) System.Console.WriteLine(x) End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Public Class extensionattribute : Inherits Attribute End Class End Namespace </file> </compilation> Dim compilation1_4 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilation1_4_Def, {Net40.SystemCore, New VisualBasicCompilationReference(compilation3_1)}, TestOptions.ReleaseExe) CompileAndVerify(compilation1_4, expectedOutput:="345") Dim compilation3_3 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="EmitExtensionAttribute7_3_3"> <file name="a.vb"> Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Public Class extensionattribute : Inherits Attribute Friend Sub New() End Sub End Class End Namespace </file> </compilation>) Dim compilation1_5 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilation1Def, {New VisualBasicCompilationReference(compilation3_3)}) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1_5, <expected> BC30517: Overload resolution failed because no 'New' is accessible. &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) CompilationUtils.AssertTheseDiagnostics(compilation1_5, <expected> BC30456: 'Test1' is not a member of 'Integer'. Call 345.Test1() ~~~~~~~~~ BC30517: Overload resolution failed because no 'New' is accessible. &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Dim compilation4 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="EmitExtensionAttribute7_4"> <file name="a.vb"> &lt;System.Runtime.CompilerServices.Extension()&gt; Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 Sub Test1(x As Integer) End Sub End Module </file> </compilation>, {Net40.SystemCore, New VisualBasicCompilationReference(compilation2), New VisualBasicCompilationReference(compilation3)}) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation4, <expected> BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor' is not defined. Module Module1 ~~~~~~~ </expected>) CompilationUtils.AssertTheseDiagnostics(compilation4, <expected> BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor' is not defined. Module Module1 ~~~~~~~ </expected>) Dim compilation5 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="EmitExtensionAttribute7_5"> <file name="a.vb"> &lt;Assembly:System.Runtime.CompilerServices.Extension()&gt; &lt;System.Runtime.CompilerServices.Extension()&gt; Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 Sub Test1(x As Integer) End Sub End Module </file> </compilation>, {Net40.SystemCore, New VisualBasicCompilationReference(compilation2), New VisualBasicCompilationReference(compilation3)}) CompilationUtils.AssertNoErrors(compilation5) End Sub <Fact> Public Sub EmitExtensionAttribute8() ' manually get attributes before emit Dim compilationDef = <compilation name="EmitExtensionAttribute1"> <file name="a.vb"> Imports System.Security Imports System.Security.Permissions Imports System.Security.Principal &lt;assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration:=true)&gt; Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; Sub Test1(x As Integer) End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, {Net40.SystemCore}) Dim assembly = compilation.SourceModule.ContainingAssembly Dim securityAttributes = assembly.GetAttributes() Debug.Assert(securityAttributes.Length = 1) CompileAndVerify(compilation, symbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(1, m.ContainingAssembly. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Dim module1 = m.ContainingAssembly.GetTypeByMetadataName("Module1") Assert.Equal(1, module1. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Assert.Equal(1, module1.GetMember("Test1"). GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) End Sub) End Sub <Fact> Public Sub BC36558ERR_ExtensionAttributeInvalid1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExtensionAttributeInvalid"> <file name="a.vb"> Namespace System.Runtime.Compilerservices &lt;AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method, AllowMultiple:=False, Inherited:=True)&gt; _ Class ExtensionAttribute Inherits Attribute End Class End Namespace Module ExtMethods &lt;System.Runtime.Compilerservices.Extension()&gt; Function IntegerExtension(ByVal a As Integer) As Integer Return 100 End Function End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC36558: The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods. &lt;System.Runtime.Compilerservices.Extension()&gt; Function IntegerExtension(ByVal a As Integer) As Integer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC36558ERR_ExtensionAttributeInvalid2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExtensionAttributeInvalid"> <file name="a.vb"> Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method, AllowMultiple:=False, Inherited:=True)&gt; _ Class ExtensionAttribute Inherits Attribute End Class End Namespace Module ExtMethods &lt;System.Runtime.Compilerservices.Extension()&gt; Function IntegerExtension(ByVal a As Integer) As Integer Return 100 End Function End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC36558: The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods. &lt;System.Runtime.Compilerservices.Extension()&gt; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC36558ERR_ExtensionAttributeInvalid3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExtensionAttributeInvalid"> <file name="a.vb"> Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method, AllowMultiple:=False, Inherited:=True)&gt; _ Class ExtensionAttribute Inherits Attribute End Class End Namespace &lt;System.Runtime.Compilerservices.Extension()&gt; Module ExtMethods &lt;System.Runtime.Compilerservices.Extension()&gt; Function IntegerExtension(ByVal a As Integer) As Integer Return 100 End Function End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC36558: The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods. &lt;System.Runtime.Compilerservices.Extension()&gt; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36558: The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods. &lt;System.Runtime.Compilerservices.Extension()&gt; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub FlowAnalysis1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="FlowAnalysis1"> <file name="a.vb"> Option Strict Off Imports System.Runtime.CompilerServices Module Module1 Sub Main() Dim x As Integer x.F1() End Sub Sub Main2() Dim x As Integer x.F2() End Sub Sub Main3() Dim x As C1 '3 x.F3() End Sub Sub Main4() Dim x As C1 '4 x.F4() End Sub Sub Main5() Dim x As C2 '5 x.F4() End Sub Sub Main31() Dim x As C1 '31 Dim d As System.Action = AddressOf x.F3 End Sub Sub Main41() Dim x As C1 '41 Dim d As System.Action = AddressOf x.F4 End Sub Sub Main51() Dim x As C2 '51 Dim d As System.Action = AddressOf x.F4 End Sub &lt;Extension()&gt; Sub F1(this As Integer) End Sub &lt;Extension()&gt; Sub F2(ByRef this As Integer) End Sub &lt;Extension()&gt; Sub F3(this As C1) End Sub &lt;Extension()&gt; Sub F4(ByRef this As C1) End Sub End Module Class C1 End Class Class C2 Inherits C1 End Class Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. x.F3() ~ BC42030: Variable 'x' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. x.F4() ~ BC42030: Variable 'x' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. x.F4() ~ BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. Dim d As System.Action = AddressOf x.F3 ~ BC42030: Variable 'x' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Dim d As System.Action = AddressOf x.F4 ~ BC42030: Variable 'x' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Dim d As System.Action = AddressOf x.F4 ~ </expected>) End Sub <Fact()> <WorkItem(528983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528983")> Public Sub ExtensionMethodsDeclaredInTypesWithConflictingNamesAreNotVisible() 'namespace Extensions '{ ' public static class C ' { ' public static void Goo(this int x) { } ' } ' public static class D ' { ' public static void Goo(this int x) { } ' } '} 'namespace extensions '{ ' public static class C ' { ' public static void Goo(this int x) { } ' } '} Dim customIL = <![CDATA[ .assembly extern mscorlib { } .assembly extern System.Core { } .module '<<GeneratedFileName>>.dll' .class public abstract auto ansi sealed beforefieldinit Extensions.C { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig static void Goo(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } .class public abstract auto ansi sealed beforefieldinit Extensions.D { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig static void Goo(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } .class public abstract auto ansi sealed beforefieldinit extensions.C { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig static void Goo(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } ]]> Using reference = IlasmUtilities.CreateTempAssembly(customIL.Value, prependDefaultHeader:=False) Dim ILRef = ModuleMetadata.CreateFromImage(File.ReadAllBytes(reference.Path)).GetReference() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="ExtensionMethodsDeclaredInTypesWithConflictingNamesAreNotVisible"> <file name="a.vb"> Imports Extensions Module Program Sub Main Dim x As Integer = 1 x.Goo End Sub End Module </file> </compilation>, {ILRef}) compilation1.VerifyDiagnostics( Diagnostic(ERRID.ERR_NameNotMember2, "x.Goo").WithArguments("Goo", "Integer"), Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports Extensions")) End Using End Sub <Fact()> Public Sub AttributeErrors_1() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DeclaringExtensionMethod3"> <file name="a.vb"><![CDATA[ <System.Runtime.CompilerServices.Extension()> ' 1 <System.Runtime.CompilerServices.Extension()> ' 2 Class C End Class ]]></file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation2, <expected><![CDATA[ BC30663: Attribute 'ExtensionAttribute' cannot be applied multiple times. <System.Runtime.CompilerServices.Extension()> ' 2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. Class C ~ ]]></expected>) End Sub <Fact()> Public Sub AttributeErrors_2() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DeclaringExtensionMethod3"> <file name="a.vb"><![CDATA[ <System.Runtime.CompilerServices.ExtensionAttribute()> ' 1 <System.Runtime.CompilerServices.ExtensionAttribute()> ' 2 Class C End Class Namespace System.Runtime.CompilerServices Structure ExtensionAttribute End Structure End Namespace ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation2, <expected><![CDATA[ BC31503: 'ExtensionAttribute' cannot be used as an attribute because it is not a class. <System.Runtime.CompilerServices.ExtensionAttribute()> ' 1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31503: 'ExtensionAttribute' cannot be used as an attribute because it is not a class. <System.Runtime.CompilerServices.ExtensionAttribute()> ' 2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact()> Public Sub AttributeErrors_3() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DeclaringExtensionMethod3"> <file name="a.vb"><![CDATA[ <System.Runtime.CompilerServices.ExtensionAttribute()> ' 1 <System.Runtime.CompilerServices.ExtensionAttribute()> ' 2 Class C End Class Namespace System.Runtime.CompilerServices Class ExtensionAttribute End Class End Namespace ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation2, <expected><![CDATA[ BC31504: 'ExtensionAttribute' cannot be used as an attribute because it does not inherit from 'System.Attribute'. <System.Runtime.CompilerServices.ExtensionAttribute()> ' 1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31504: 'ExtensionAttribute' cannot be used as an attribute because it does not inherit from 'System.Attribute'. <System.Runtime.CompilerServices.ExtensionAttribute()> ' 2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact()> Public Sub AttributeErrors_4() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DeclaringExtensionMethod3"> <file name="a.vb"><![CDATA[ <System.Runtime.CompilerServices.ExtensionAttribute()> ' 1 Class C End Class Namespace System.Runtime.CompilerServices <System.AttributeUsageAttribute(System.AttributeTargets.Assembly, Inherited := False)> Class ExtensionAttribute Inherits System.Attribute End Class End Namespace ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation2, <expected><![CDATA[ BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'C' because the attribute is not valid on this declaration type. <System.Runtime.CompilerServices.ExtensionAttribute()> ' 1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact(), WorkItem(545799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545799")> Public Sub SameExtensionMethodSymbol() Dim comp = CreateCompilationWithMscorlib40AndReferences( <compilation name="SameExtensionMethodSymbol"> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Public Class C Public Sub InstanceMethod(Of T)(o As T) End Sub End Class Public Module Extensions <System.Runtime.CompilerServices.Extension()> Public Sub ExtensionMethod(Of T)(this As C, o As T) End Sub End Module Module M Sub Main() Dim obj = New C() obj.InstanceMethod("q") obj.ExtensionMethod("c") End Sub End Module ]]></file> </compilation>, references:={Net40.SystemCore}) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of InvocationExpressionSyntax)() ' Invocation Dim node = nodes.First() Dim node2 = node.Expression Assert.Equal("obj.InstanceMethod", node2.ToString()) Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, node2.Kind) Dim sym = model.GetSymbolInfo(node).Symbol Assert.NotNull(sym) Assert.Equal("InstanceMethod", sym.Name) Dim sym2 = model.GetSymbolInfo(node2).Symbol Assert.Equal(sym2, sym) node = nodes.Last() node2 = node.Expression Assert.Equal("obj.ExtensionMethod", node2.ToString()) Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, node2.Kind) sym = model.GetSymbolInfo(node).Symbol Assert.NotNull(sym) Assert.Equal("ExtensionMethod", sym.Name) sym2 = model.GetSymbolInfo(node2).Symbol Assert.Equal(sym2, sym) End Sub <ConditionalFact(GetType(NoUsedAssembliesValidation))> ' https://github.com/dotnet/roslyn/issues/40680: The test hook is blocked by this issue. <WorkItem(40680, "https://github.com/dotnet/roslyn/issues/40680")> Public Sub ScriptExtensionMethods() Dim source = <![CDATA[ Imports System.Runtime.CompilerServices <Extension> Shared Function F(o As Object) As Object Return Nothing End Function Dim o As New Object() o.F()]]> Dim comp = CreateCompilationWithMscorlib45( {VisualBasicSyntaxTree.ParseText(source.Value, TestOptions.Script)}) comp.VerifyDiagnostics() Assert.True(comp.SourceAssembly.MightContainExtensionMethods) End Sub <Fact> Public Sub InteractiveExtensionMethods() Dim references = {Net40.mscorlib, Net40.SystemCore} Dim source0 = " Imports System.Runtime.CompilerServices <Extension> Shared Function F(o As Object) As Object Return 0 End Function Dim o As New Object() ? o.F()" Dim source1 = " Imports System.Runtime.CompilerServices <Extension> Shared Function G(o As Object) As Object Return 1 End Function Dim o As New Object() ? o.G().F()" Dim s0 = VisualBasicCompilation.CreateScriptCompilation( "s0.dll", syntaxTree:=Parse(source0, TestOptions.Script), references:=references) s0.VerifyDiagnostics() Assert.True(s0.SourceAssembly.MightContainExtensionMethods) Dim s1 = VisualBasicCompilation.CreateScriptCompilation( "s1.dll", syntaxTree:=Parse(source1, TestOptions.Script), previousScriptCompilation:=s0, references:=references) s1.VerifyDiagnostics() Assert.True(s1.SourceAssembly.MightContainExtensionMethods) End Sub <Fact> Public Sub ConsumeRefExtensionMethods() Dim options = New CSharpParseOptions(CodeAnalysis.CSharp.LanguageVersion.Latest) Dim csharp = CreateCSharpCompilation(" public static class Extensions { public static void PrintValue(ref this int p) { System.Console.Write(p); } }", referencedAssemblies:={Net40.mscorlib, Net40.SystemCore}, parseOptions:=options).EmitToImageReference() Dim vb = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Module Program Sub Main() Dim value = 5 value.PrintValue() End Sub End Module ]]> </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:={csharp}) CompileAndVerify(vb, expectedOutput:="5") End Sub <Fact> Public Sub ConsumeInExtensionMethods() Dim options = New CSharpParseOptions(CodeAnalysis.CSharp.LanguageVersion.Latest) Dim csharp = CreateCSharpCompilation(" public static class Extensions { public static void PrintValue(in this int p) { System.Console.Write(p); } }", referencedAssemblies:={Net40.mscorlib, Net40.SystemCore}, parseOptions:=options).EmitToImageReference() Dim vb = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Module Program Sub Main() Dim value = 5 value.PrintValue() End Sub End Module ]]> </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:={csharp}) CompileAndVerify(vb, expectedOutput:="5") 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.IO Imports Microsoft.CodeAnalysis.CSharp Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods Public Class ExtensionMethodTests : Inherits BasicTestBase <Fact> Public Sub DetectingExtensionAttributeOnImport1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="DetectingExtensionAttributeOnImport"> <file name="a.vb"> Module Module1 Sub Main() End Sub End Module </file> </compilation>, {Net40.SystemCore}) Dim enumerable As NamedTypeSymbol = compilation1.GetTypeByMetadataName("System.Linq.Enumerable") Assert.True(enumerable.ContainingAssembly.MightContainExtensionMethods) Assert.True(enumerable.ContainingModule.MightContainExtensionMethods) Assert.True(enumerable.MightContainExtensionMethods) For Each [select] As MethodSymbol In enumerable.GetMembers("Select") Assert.True([select].IsExtensionMethod) Next End Sub <Fact> Public Sub DetectingExtensionAttributeOnImport2() Dim customIL = <![CDATA[ .assembly extern mscorlib { } .assembly extern System.Core { } .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .module '<<GeneratedFileName>>.dll' // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi Module1 extends [mscorlib]System.Object { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Module1::.ctor .method private specialname rtspecialname static void .cctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::.cctor .method public static void Test1(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test1 .method public specialname static int32 get_Test2() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test2 .method public specialname static int32 get_Test3() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test3 .method public specialname static void set_Test3(int32 'value') cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::set_Test3 .method public static void Test4() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test4 .method public static void Test5([opt] int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] = int32(0x00000000) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test5 .method public static void Test6(int32[] x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test6 .method public static void Test7<(class [mscorlib]System.Collections.Generic.IList`1<!!U[]>) T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test7 .method public static void Test8<T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test8 .method public instance void Test9(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test9 .property int32 Test2() { .get int32 Module1::get_Test2() } // end of property Module1::Test2 .property int32 Test3() { .get int32 Module1::get_Test3() .set void Module1::set_Test3(int32) } // end of property Module1::Test3 } // end of class Module1]]> Using reference = IlasmUtilities.CreateTempAssembly(customIL.Value, prependDefaultHeader:=False) Dim ILRef = MetadataReference.CreateFromImage(ReadFromFile(reference.Path)) Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="DetectingExtensionAttributeOnImport"> <file name="a.vb"> Module M1 Sub Main() End Sub End Module </file> </compilation>, {ILRef}) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1") Assert.NotSame(compilation1.Assembly, module1.ContainingAssembly) Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) Assert.True(module1.ContainingModule.MightContainExtensionMethods) Assert.True(module1.MightContainExtensionMethods) For Each method As MethodSymbol In module1.GetMembers().OfType(Of MethodSymbol)() Select Case method.Name Case "Test1", "Test8" Assert.True(method.IsExtensionMethod) Case Else Assert.False(method.IsExtensionMethod) End Select Next Assert.Equal(13, module1.GetMembers().Length) End Using End Sub <Fact> Public Sub DetectingExtensionAttributeOnImport3() Dim customIL = <![CDATA[ .assembly extern mscorlib { } .assembly extern System.Core { } .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .module '<<GeneratedFileName>>.dll' // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi Module2 extends [mscorlib]System.Object { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .class auto ansi nested public Module1 extends [mscorlib]System.Object { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Module1::.ctor .method private specialname rtspecialname static void .cctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::.cctor .method public static void Test1(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test1 .method public specialname static int32 get_Test2() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test2 .method public specialname static int32 get_Test3() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test3 .method public specialname static void set_Test3(int32 'value') cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::set_Test3 .method public static void Test4() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test4 .method public static void Test5([opt] int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] = int32(0x00000000) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test5 .method public static void Test6(int32[] x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test6 .method public static void Test7<(class [mscorlib]System.Collections.Generic.IList`1<!!U[]>) T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test7 .method public static void Test8<T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test8 .method public instance void Test9(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test9 .property int32 Test2() { .get int32 Module2/Module1::get_Test2() } // end of property Module1::Test2 .property int32 Test3() { .get int32 Module2/Module1::get_Test3() .set void Module2/Module1::set_Test3(int32) } // end of property Module1::Test3 } // end of class Module1 } // end of class Module2 ]]> Using reference = IlasmUtilities.CreateTempAssembly(customIL.Value, prependDefaultHeader:=False) Dim ILRef = MetadataReference.CreateFromImage(ReadFromFile(reference.Path)) Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="DetectingExtensionAttributeOnImport"> <file name="a.vb"> Module M1 Sub Main() End Sub End Module </file> </compilation>, {ILRef}) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module2+Module1") Assert.NotSame(compilation1.Assembly, module1.ContainingAssembly) Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) Assert.True(module1.ContainingModule.MightContainExtensionMethods) Assert.True(module1.ContainingType.MightContainExtensionMethods) Assert.False(module1.MightContainExtensionMethods) For Each method As MethodSymbol In module1.GetMembers().OfType(Of MethodSymbol)() Assert.False(method.IsExtensionMethod) Next Assert.Equal(13, module1.GetMembers().Length) End Using End Sub <Fact> Public Sub DetectingExtensionAttributeOnImport4() Dim customIL = <![CDATA[ .assembly extern mscorlib { } .assembly extern System.Core { } .assembly '<<GeneratedFileName>>' { } .module '<<GeneratedFileName>>.dll' // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi Module1 extends [mscorlib]System.Object { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Module1::.ctor .method private specialname rtspecialname static void .cctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::.cctor .method public static void Test1(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test1 .method public specialname static int32 get_Test2() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test2 .method public specialname static int32 get_Test3() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test3 .method public specialname static void set_Test3(int32 'value') cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::set_Test3 .method public static void Test4() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test4 .method public static void Test5([opt] int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] = int32(0x00000000) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test5 .method public static void Test6(int32[] x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test6 .method public static void Test7<(class [mscorlib]System.Collections.Generic.IList`1<!!U[]>) T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test7 .method public static void Test8<T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test8 .method public instance void Test9(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test9 .property int32 Test2() { .get int32 Module1::get_Test2() } // end of property Module1::Test2 .property int32 Test3() { .get int32 Module1::get_Test3() .set void Module1::set_Test3(int32) } // end of property Module1::Test3 } // end of class Module1]]> Using reference = IlasmUtilities.CreateTempAssembly(customIL.Value, prependDefaultHeader:=False) Dim ILRef = MetadataReference.CreateFromImage(ReadFromFile(reference.Path)) Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="DetectingExtensionAttributeOnImport"> <file name="a.vb"> Module M1 Sub Main() End Sub End Module </file> </compilation>, {ILRef}) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1") Assert.NotSame(compilation1.Assembly, module1.ContainingAssembly) Assert.False(module1.ContainingAssembly.MightContainExtensionMethods) Assert.False(module1.ContainingModule.MightContainExtensionMethods) Assert.False(module1.MightContainExtensionMethods) For Each method As MethodSymbol In module1.GetMembers().OfType(Of MethodSymbol)() Assert.False(method.IsExtensionMethod) Next Assert.Equal(13, module1.GetMembers().Length) End Using End Sub <Fact> Public Sub DetectingExtensionAttributeOnImport5() Dim customIL = <![CDATA[ .assembly extern mscorlib { } .assembly extern System.Core { } .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .module '<<GeneratedFileName>>.dll' // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi Module1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Module1::.ctor .method private specialname rtspecialname static void .cctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::.cctor .method public static void Test1(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test1 .method public specialname static int32 get_Test2() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test2 .method public specialname static int32 get_Test3() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test3 .method public specialname static void set_Test3(int32 'value') cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::set_Test3 .method public static void Test4() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test4 .method public static void Test5([opt] int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] = int32(0x00000000) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test5 .method public static void Test6(int32[] x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test6 .method public static void Test7<(class [mscorlib]System.Collections.Generic.IList`1<!!U[]>) T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test7 .method public static void Test8<T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test8 .method public instance void Test9(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test9 .property int32 Test2() { .get int32 Module1::get_Test2() } // end of property Module1::Test2 .property int32 Test3() { .get int32 Module1::get_Test3() .set void Module1::set_Test3(int32) } // end of property Module1::Test3 } // end of class Module1]]> Using reference = IlasmUtilities.CreateTempAssembly(customIL.Value, prependDefaultHeader:=False) Dim ILRef = MetadataReference.CreateFromImage(ReadFromFile(reference.Path)) Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="DetectingExtensionAttributeOnImport"> <file name="a.vb"> Module M1 Sub Main() End Sub End Module </file> </compilation>, {ILRef}) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1") Assert.NotSame(compilation1.Assembly, module1.ContainingAssembly) Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) Assert.True(module1.ContainingModule.MightContainExtensionMethods) Assert.False(module1.MightContainExtensionMethods) For Each method As MethodSymbol In module1.GetMembers().OfType(Of MethodSymbol)() Assert.False(method.IsExtensionMethod) Next Assert.Equal(13, module1.GetMembers().Length) End Using End Sub <Fact> Public Sub DetectingExtensionAttributeOnImport6() Dim customIL = <![CDATA[ .assembly extern mscorlib { } .assembly extern System.Core { } .module '<<GeneratedFileName>>.dll' // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi Module1 extends [mscorlib]System.Object { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public specialname rtspecialname instance void .ctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Module1::.ctor .method private specialname rtspecialname static void .cctor() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::.cctor .method public static void Test1(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test1 .method public specialname static int32 get_Test2() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test2 .method public specialname static int32 get_Test3() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Module1::get_Test3 .method public specialname static void set_Test3(int32 'value') cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::set_Test3 .method public static void Test4() cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test4 .method public static void Test5([opt] int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] = int32(0x00000000) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test5 .method public static void Test6(int32[] x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test6 .method public static void Test7<(class [mscorlib]System.Collections.Generic.IList`1<!!U[]>) T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test7 .method public static void Test8<T,U>(!!T x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test8 .method public instance void Test9(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Module1::Test9 .property int32 Test2() { .get int32 Module1::get_Test2() } // end of property Module1::Test2 .property int32 Test3() { .get int32 Module1::get_Test3() .set void Module1::set_Test3(int32) } // end of property Module1::Test3 } // end of class Module1 // ============================================================= .custom ([mscorlib]System.Runtime.CompilerServices.AssemblyAttributesGoHere) instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ]]> Using reference = IlasmUtilities.CreateTempAssembly(customIL.Value, prependDefaultHeader:=False) Dim ILRef = ModuleMetadata.CreateFromImage(File.ReadAllBytes(reference.Path)).GetReference() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="DetectingExtensionAttributeOnImport"> <file name="a.vb"> Module M1 Sub Main() End Sub End Module </file> </compilation>, {ILRef}) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1") Assert.Same(compilation1.Assembly, module1.ContainingAssembly) Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) Assert.NotSame(compilation1.Assembly.Modules(0), module1.ContainingModule) Assert.False(module1.ContainingModule.MightContainExtensionMethods) Assert.False(module1.MightContainExtensionMethods) For Each method As MethodSymbol In module1.GetMembers().OfType(Of MethodSymbol)() Assert.False(method.IsExtensionMethod) Next Assert.Equal(13, module1.GetMembers().Length) End Using End Sub <Fact> Public Sub MightContainExtensionMethods_InSource() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="MightContainExtensionMethods_InSource"> <file name="a.vb"> Module Module1 Module Module2 End Module End Module Class Class1 End Class </file> </compilation>) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1") Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) Assert.True(module1.ContainingModule.MightContainExtensionMethods) Assert.False(module1.MightContainExtensionMethods) Dim module2 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1+Module2") Assert.False(module2.MightContainExtensionMethods) Assert.Equal(TypeKind.Module, module2.TypeKind) Dim class1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Class1") Assert.False(class1.MightContainExtensionMethods) End Sub <Fact> Public Sub DeclaringExtensionMethods1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DeclaringExtensionMethod1"> <file name="a.vb"> Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 Sub Test1(x As Integer) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test2 ReadOnly Property Test2 As Integer Get Return Nothing End Get End Property Property Test3 As Integer &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Get Get Return Nothing End Get &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Set Set End Set End Property &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test4 Sub Test4() End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test5 Sub Test5(Optional x As Integer = 0) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test6 Sub Test6(ParamArray x As Integer()) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test7 Sub Test7(Of T As U, U)(x As T) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test8 Sub Test8(Of T, U)(x As T) End Sub End Module </file> </compilation>, {Net40.SystemCore}) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1") For Each method As MethodSymbol In module1.GetMembers().OfType(Of MethodSymbol)() Select Case method.Name Case "Test1", "Test8" Assert.True(method.IsExtensionMethod) Case Else Assert.False(method.IsExtensionMethod) End Select Next CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'Test2' because the attribute is not valid on this declaration type. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Get ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Set ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36552: Extension methods must declare at least one parameter. The first parameter specifies which type to extend. Sub Test4() ~~~~~ BC36553: 'Optional' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend. Sub Test5(Optional x As Integer = 0) ~ BC36554: 'ParamArray' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend. Sub Test6(ParamArray x As Integer()) ~ BC36561: Extension method 'Test7' has type constraints that can never be satisfied. Sub Test7(Of T As U, U)(x As T) ~~~~~ </expected>) End Sub <Fact> Public Sub DeclaringExtensionMethods2() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="DeclaringExtensionMethod2"> <file name="a.vb"> Class Module2 &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test1 Sub Test1(x As Integer) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test2 ReadOnly Property Test2 As Integer Get Return Nothing End Get End Property Property Test3 As Integer &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Get Get Return Nothing End Get &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Set Set End Set End Property &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test4 Sub Test4() End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test5 Sub Test5(Optional x As Integer = 0) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test6 Sub Test6(ParamArray x As Integer()) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test7 Sub Test7(Of T As U, U)(x As T) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test8 Sub Test8(Of T, U)(x As T) End Sub End Class </file> </compilation>, {Net40.SystemCore}) Dim module2 As NamedTypeSymbol = compilation2.GetTypeByMetadataName("Module2") For Each method As MethodSymbol In module2.GetMembers().OfType(Of MethodSymbol)() Assert.False(method.IsExtensionMethod) Next CompilationUtils.AssertTheseDiagnostics(compilation2, <expected> BC36551: Extension methods can be defined only in modules. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'Test2' because the attribute is not valid on this declaration type. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Get ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Set ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36551: Extension methods can be defined only in modules. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36551: Extension methods can be defined only in modules. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36551: Extension methods can be defined only in modules. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test6 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36551: Extension methods can be defined only in modules. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test7 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36551: Extension methods can be defined only in modules. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test8 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub DeclaringExtensionMethods3() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DeclaringExtensionMethod3"> <file name="a.vb"> &lt;System.Runtime.CompilerServices.Extension()&gt; 'C Class C End Class &lt;System.Runtime.CompilerServices.Extension()&gt; 'S Structure S End Structure &lt;System.Runtime.CompilerServices.Extension()&gt; 'I Interface I End Interface &lt;System.Runtime.CompilerServices.Extension()&gt; 'E Enum E x End Enum &lt;System.Runtime.CompilerServices.Extension()&gt; 'M Module M End Module &lt;System.Runtime.CompilerServices.Extension()&gt; 'D Delegate Sub D() </file> </compilation>, {Net40.SystemCore}) For Each type As NamedTypeSymbol In compilation2.SourceModule.GlobalNamespace.GetTypeMembers() Assert.False(type.MightContainExtensionMethods) Next CompilationUtils.AssertTheseDiagnostics(compilation2, <expected> BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. Class C ~ BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'S' because the attribute is not valid on this declaration type. &lt;System.Runtime.CompilerServices.Extension()&gt; 'S ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'I' because the attribute is not valid on this declaration type. &lt;System.Runtime.CompilerServices.Extension()&gt; 'I ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'E' because the attribute is not valid on this declaration type. &lt;System.Runtime.CompilerServices.Extension()&gt; 'E ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'D' because the attribute is not valid on this declaration type. &lt;System.Runtime.CompilerServices.Extension()&gt; 'D ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub DeclaringExtensionMethods4() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DeclaringExtensionMethod4"> <file name="a.vb"> Module Module2 &lt;System.Runtime.CompilerServices.Extension()&gt; 'Module1 Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 Sub Test1(x As Integer) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test2 ReadOnly Property Test2 As Integer Get Return Nothing End Get End Property Property Test3 As Integer &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Get Get Return Nothing End Get &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Set Set End Set End Property &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test4 Sub Test4() End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test5 Sub Test5(Optional x As Integer = 0) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test6 Sub Test6(ParamArray x As Integer()) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test7 Sub Test7(Of T As U, U)(x As T) End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test8 Sub Test8(Of T, U)(x As T) End Sub End Module End Module </file> </compilation>, {Net40.SystemCore}) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module2+Module1") Assert.False(module1.MightContainExtensionMethods) For Each method As MethodSymbol In module1.GetMembers().OfType(Of MethodSymbol)() Assert.False(method.IsExtensionMethod) Next CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30617: 'Module' statements can occur only at file or namespace level. &lt;System.Runtime.CompilerServices.Extension()&gt; 'Module1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'Test2' because the attribute is not valid on this declaration type. &lt;System.Runtime.CompilerServices.Extension()&gt; ' Test2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Get ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. &lt;System.Runtime.CompilerServices.Extension()&gt; ' On Set ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36552: Extension methods must declare at least one parameter. The first parameter specifies which type to extend. Sub Test4() ~~~~~ BC36553: 'Optional' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend. Sub Test5(Optional x As Integer = 0) ~ BC36554: 'ParamArray' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend. Sub Test6(ParamArray x As Integer()) ~ BC36561: Extension method 'Test7' has type constraints that can never be satisfied. Sub Test7(Of T As U, U)(x As T) ~~~~~ </expected>) End Sub <Fact> Public Sub DetectingAbsenceOfExtensionMethods1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="DeclaringExtensionMethod1"> <file name="a.vb"> Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 Sub Test1(x As Integer) End Sub End Module </file> </compilation>) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1") Assert.True(module1.MightContainExtensionMethods) Assert.True(module1.ContainingModule.MightContainExtensionMethods) Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) DirectCast(module1, SourceNamedTypeSymbol).GenerateDeclarationErrors(Nothing) Assert.False(module1.MightContainExtensionMethods) Assert.True(module1.ContainingModule.MightContainExtensionMethods) Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) Dim containsExtensions As Boolean DirectCast(module1.ContainingModule, SourceModuleSymbol).GetAllDeclarationErrors(BindingDiagnosticBag.Discarded, Nothing, containsExtensions) Assert.False(module1.MightContainExtensionMethods) Assert.False(module1.ContainingModule.MightContainExtensionMethods) Assert.False(module1.ContainingAssembly.MightContainExtensionMethods) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, <expected> BC30002: Type 'System.Runtime.CompilerServices.Extension' is not defined. &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub DetectingAbsenceOfExtensionMethods2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DeclaringExtensionMethod1"> <file name="a.vb"> Module Module1 Module Module2 &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 Sub Test1(x As Integer) End Sub End Module End Module </file> </compilation>, {Net40.SystemCore}) Dim module1 As NamedTypeSymbol = compilation1.GetTypeByMetadataName("Module1") Assert.False(module1.MightContainExtensionMethods) Assert.True(module1.ContainingModule.MightContainExtensionMethods) Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) DirectCast(module1, SourceNamedTypeSymbol).GenerateDeclarationErrors(Nothing) Assert.False(module1.MightContainExtensionMethods) Assert.True(module1.ContainingModule.MightContainExtensionMethods) Assert.True(module1.ContainingAssembly.MightContainExtensionMethods) Dim containsExtensions As Boolean DirectCast(module1.ContainingModule, SourceModuleSymbol).GetAllDeclarationErrors(BindingDiagnosticBag.Discarded, Nothing, containsExtensions) Assert.False(module1.MightContainExtensionMethods) Assert.False(module1.ContainingModule.MightContainExtensionMethods) Assert.False(module1.ContainingAssembly.MightContainExtensionMethods) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC30617: 'Module' statements can occur only at file or namespace level. Module Module2 ~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub EmitExtensionAttribute1() Dim compilationDef = <compilation name="EmitExtensionAttribute1"> <file name="a.vb"> Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; Sub Test1(x As Integer) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={Net40.SystemCore}, symbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(1, m.ContainingAssembly. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Dim module1 = m.ContainingAssembly.GetTypeByMetadataName("Module1") Assert.Equal(1, module1. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Assert.Equal(1, module1.GetMember("Test1"). GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) End Sub) End Sub <Fact> Public Sub EmitExtensionAttribute2() Dim compilationDef = <compilation name="EmitExtensionAttribute2"> <file name="a.vb"> &lt;System.Runtime.CompilerServices.Extension()&gt; Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; Sub Test1(x As Integer) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={Net40.SystemCore}, symbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(1, m.ContainingAssembly. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Dim module1 = m.ContainingAssembly.GetTypeByMetadataName("Module1") Assert.Equal(1, module1. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Assert.Equal(1, module1.GetMember("Test1"). GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) End Sub) End Sub <Fact> Public Sub EmitExtensionAttribute3() Dim compilationDef = <compilation name="EmitExtensionAttribute3"> <file name="a.vb"> &lt;Assembly:System.Runtime.CompilerServices.Extension()&gt; &lt;System.Runtime.CompilerServices.Extension()&gt; Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; Sub Test1(x As Integer) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={Net40.SystemCore}, symbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(1, m.ContainingAssembly. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Dim module1 = m.ContainingAssembly.GetTypeByMetadataName("Module1") Assert.Equal(1, module1. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Assert.Equal(1, module1.GetMember("Test1"). GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) End Sub) End Sub <Fact> Public Sub EmitExtensionAttribute4() Dim compilationDef = <compilation name="EmitExtensionAttribute4"> <file name="a.vb"> &lt;Assembly:System.Runtime.CompilerServices.Extension()&gt; &lt;System.Runtime.CompilerServices.Extension()&gt; Module Module1 Sub Test1(x As Integer) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={Net40.SystemCore}, symbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(1, m.ContainingAssembly. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Dim module1 = m.ContainingAssembly.GetTypeByMetadataName("Module1") Assert.Equal(1, module1. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Assert.Equal(0, module1.GetMember("Test1"). GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) End Sub) End Sub <Fact> Public Sub EmitExtensionAttribute5() Dim compilationDef = <compilation name="EmitExtensionAttribute5"> <file name="a.vb"> &lt;System.Runtime.CompilerServices.Extension()&gt; Module Module1 Sub Test1(x As Integer) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={Net40.SystemCore}, symbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(0, m.ContainingAssembly. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Dim module1 = m.ContainingAssembly.GetTypeByMetadataName("Module1") Assert.Equal(1, module1. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Assert.Equal(0, module1.GetMember("Test1"). GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) End Sub) End Sub <Fact> Public Sub EmitExtensionAttribute6() Dim compilationDef = <compilation name="EmitExtensionAttribute6"> <file name="a.vb"> Module Module1 Sub Test1(x As Integer) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={Net40.SystemCore}, symbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(0, m.ContainingAssembly. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Dim module1 = m.ContainingAssembly.GetTypeByMetadataName("Module1") Assert.Equal(0, module1. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Assert.Equal(0, module1.GetMember("Test1"). GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) End Sub) End Sub <Fact> Public Sub EmitExtensionAttribute7() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="EmitExtensionAttribute7_1"> <file name="a.vb"> Namespace System.Runtime.CompilerServices Class ExtensionAttribute End Class End Namespace </file> </compilation>) CompilationUtils.AssertNoErrors(compilation2) Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="EmitExtensionAttribute7_2"> <file name="a.vb"> Namespace System.Runtime.CompilerServices Class ExtensionAttribute End Class End Namespace </file> </compilation>) CompilationUtils.AssertNoErrors(compilation3) Dim compilation1Def = <compilation name="EmitExtensionAttribute7_3"> <file name="a.vb"> Module Module1 Sub Main() Call 345.Test1() End Sub &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 Sub Test1(x As Integer) System.Console.WriteLine(x) End Sub End Module </file> </compilation> Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilation1Def, {Net40.SystemCore, New VisualBasicCompilationReference(compilation2), New VisualBasicCompilationReference(compilation3)}, TestOptions.ReleaseExe) CompileAndVerify(compilation1, expectedOutput:="345") Dim compilation3_1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="EmitExtensionAttribute7_3_1"> <file name="a.vb"> Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Public Class extensionattribute : Inherits Attribute End Class End Namespace </file> </compilation>) Dim compilation1_1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilation1Def, {Net40.SystemCore, New VisualBasicCompilationReference(compilation3_1)}, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1_1, <expected> <![CDATA[ BC30560: 'ExtensionAttribute' is ambiguous in the namespace 'System.Runtime.CompilerServices'. <System.Runtime.CompilerServices.Extension()> 'Test1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </expected>) CompilationUtils.AssertTheseDiagnostics(compilation1_1, <expected> <![CDATA[ BC30456: 'Test1' is not a member of 'Integer'. Call 345.Test1() ~~~~~~~~~ BC30560: 'ExtensionAttribute' is ambiguous in the namespace 'System.Runtime.CompilerServices'. <System.Runtime.CompilerServices.Extension()> 'Test1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </expected>) Dim compilation3_2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="EmitExtensionAttribute7_3_2"> <file name="a.vb"> Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Friend Class extensionattribute : Inherits Attribute End Class End Namespace </file> </compilation>) Dim compilation1_2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilation1Def, {Net40.SystemCore, New VisualBasicCompilationReference(compilation3_2)}, TestOptions.ReleaseExe) CompileAndVerify(compilation1_2, expectedOutput:="345") Dim compilation1_3_Def = <compilation name="EmitExtensionAttribute7_3"> <file name="a.vb"> Module Module1 Sub Main() Call 345.Test1() End Sub &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; 'Test1 Sub Test1(x As Integer) System.Console.WriteLine(x) End Sub End Module </file> </compilation> Dim compilation1_3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilation1_3_Def, {Net40.SystemCore, New VisualBasicCompilationReference(compilation3_1)}, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1_3, <expected> BC30560: 'ExtensionAttribute' is ambiguous in the namespace 'System.Runtime.CompilerServices'. &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; 'Test1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) CompilationUtils.AssertTheseDiagnostics(compilation1_3, <expected> BC30456: 'Test1' is not a member of 'Integer'. Call 345.Test1() ~~~~~~~~~ BC30560: 'ExtensionAttribute' is ambiguous in the namespace 'System.Runtime.CompilerServices'. &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; 'Test1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Dim compilation1_4_Def = <compilation name="EmitExtensionAttribute7_3"> <file name="a.vb"> Module Module1 Sub Main() Call 345.Test1() End Sub &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; 'Test1 Sub Test1(x As Integer) System.Console.WriteLine(x) End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Public Class extensionattribute : Inherits Attribute End Class End Namespace </file> </compilation> Dim compilation1_4 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilation1_4_Def, {Net40.SystemCore, New VisualBasicCompilationReference(compilation3_1)}, TestOptions.ReleaseExe) CompileAndVerify(compilation1_4, expectedOutput:="345") Dim compilation3_3 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="EmitExtensionAttribute7_3_3"> <file name="a.vb"> Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Public Class extensionattribute : Inherits Attribute Friend Sub New() End Sub End Class End Namespace </file> </compilation>) Dim compilation1_5 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilation1Def, {New VisualBasicCompilationReference(compilation3_3)}) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1_5, <expected> BC30517: Overload resolution failed because no 'New' is accessible. &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) CompilationUtils.AssertTheseDiagnostics(compilation1_5, <expected> BC30456: 'Test1' is not a member of 'Integer'. Call 345.Test1() ~~~~~~~~~ BC30517: Overload resolution failed because no 'New' is accessible. &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Dim compilation4 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="EmitExtensionAttribute7_4"> <file name="a.vb"> &lt;System.Runtime.CompilerServices.Extension()&gt; Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 Sub Test1(x As Integer) End Sub End Module </file> </compilation>, {Net40.SystemCore, New VisualBasicCompilationReference(compilation2), New VisualBasicCompilationReference(compilation3)}) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation4, <expected> BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor' is not defined. Module Module1 ~~~~~~~ </expected>) CompilationUtils.AssertTheseDiagnostics(compilation4, <expected> BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor' is not defined. Module Module1 ~~~~~~~ </expected>) Dim compilation5 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="EmitExtensionAttribute7_5"> <file name="a.vb"> &lt;Assembly:System.Runtime.CompilerServices.Extension()&gt; &lt;System.Runtime.CompilerServices.Extension()&gt; Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; 'Test1 Sub Test1(x As Integer) End Sub End Module </file> </compilation>, {Net40.SystemCore, New VisualBasicCompilationReference(compilation2), New VisualBasicCompilationReference(compilation3)}) CompilationUtils.AssertNoErrors(compilation5) End Sub <Fact> Public Sub EmitExtensionAttribute8() ' manually get attributes before emit Dim compilationDef = <compilation name="EmitExtensionAttribute1"> <file name="a.vb"> Imports System.Security Imports System.Security.Permissions Imports System.Security.Principal &lt;assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration:=true)&gt; Module Module1 &lt;System.Runtime.CompilerServices.Extension()&gt; Sub Test1(x As Integer) End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, {Net40.SystemCore}) Dim assembly = compilation.SourceModule.ContainingAssembly Dim securityAttributes = assembly.GetAttributes() Debug.Assert(securityAttributes.Length = 1) CompileAndVerify(compilation, symbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(1, m.ContainingAssembly. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Dim module1 = m.ContainingAssembly.GetTypeByMetadataName("Module1") Assert.Equal(1, module1. GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) Assert.Equal(1, module1.GetMember("Test1"). GetAttributes("System.Runtime.CompilerServices", "ExtensionAttribute").Count) End Sub) End Sub <Fact> Public Sub BC36558ERR_ExtensionAttributeInvalid1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExtensionAttributeInvalid"> <file name="a.vb"> Namespace System.Runtime.Compilerservices &lt;AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method, AllowMultiple:=False, Inherited:=True)&gt; _ Class ExtensionAttribute Inherits Attribute End Class End Namespace Module ExtMethods &lt;System.Runtime.Compilerservices.Extension()&gt; Function IntegerExtension(ByVal a As Integer) As Integer Return 100 End Function End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC36558: The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods. &lt;System.Runtime.Compilerservices.Extension()&gt; Function IntegerExtension(ByVal a As Integer) As Integer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC36558ERR_ExtensionAttributeInvalid2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExtensionAttributeInvalid"> <file name="a.vb"> Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method, AllowMultiple:=False, Inherited:=True)&gt; _ Class ExtensionAttribute Inherits Attribute End Class End Namespace Module ExtMethods &lt;System.Runtime.Compilerservices.Extension()&gt; Function IntegerExtension(ByVal a As Integer) As Integer Return 100 End Function End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC36558: The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods. &lt;System.Runtime.Compilerservices.Extension()&gt; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub BC36558ERR_ExtensionAttributeInvalid3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ExtensionAttributeInvalid"> <file name="a.vb"> Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method, AllowMultiple:=False, Inherited:=True)&gt; _ Class ExtensionAttribute Inherits Attribute End Class End Namespace &lt;System.Runtime.Compilerservices.Extension()&gt; Module ExtMethods &lt;System.Runtime.Compilerservices.Extension()&gt; Function IntegerExtension(ByVal a As Integer) As Integer Return 100 End Function End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC36558: The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods. &lt;System.Runtime.Compilerservices.Extension()&gt; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36558: The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods. &lt;System.Runtime.Compilerservices.Extension()&gt; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub FlowAnalysis1() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="FlowAnalysis1"> <file name="a.vb"> Option Strict Off Imports System.Runtime.CompilerServices Module Module1 Sub Main() Dim x As Integer x.F1() End Sub Sub Main2() Dim x As Integer x.F2() End Sub Sub Main3() Dim x As C1 '3 x.F3() End Sub Sub Main4() Dim x As C1 '4 x.F4() End Sub Sub Main5() Dim x As C2 '5 x.F4() End Sub Sub Main31() Dim x As C1 '31 Dim d As System.Action = AddressOf x.F3 End Sub Sub Main41() Dim x As C1 '41 Dim d As System.Action = AddressOf x.F4 End Sub Sub Main51() Dim x As C2 '51 Dim d As System.Action = AddressOf x.F4 End Sub &lt;Extension()&gt; Sub F1(this As Integer) End Sub &lt;Extension()&gt; Sub F2(ByRef this As Integer) End Sub &lt;Extension()&gt; Sub F3(this As C1) End Sub &lt;Extension()&gt; Sub F4(ByRef this As C1) End Sub End Module Class C1 End Class Class C2 Inherits C1 End Class Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <expected> BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. x.F3() ~ BC42030: Variable 'x' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. x.F4() ~ BC42030: Variable 'x' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. x.F4() ~ BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. Dim d As System.Action = AddressOf x.F3 ~ BC42030: Variable 'x' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Dim d As System.Action = AddressOf x.F4 ~ BC42030: Variable 'x' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Dim d As System.Action = AddressOf x.F4 ~ </expected>) End Sub <Fact()> <WorkItem(528983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528983")> Public Sub ExtensionMethodsDeclaredInTypesWithConflictingNamesAreNotVisible() 'namespace Extensions '{ ' public static class C ' { ' public static void Goo(this int x) { } ' } ' public static class D ' { ' public static void Goo(this int x) { } ' } '} 'namespace extensions '{ ' public static class C ' { ' public static void Goo(this int x) { } ' } '} Dim customIL = <![CDATA[ .assembly extern mscorlib { } .assembly extern System.Core { } .module '<<GeneratedFileName>>.dll' .class public abstract auto ansi sealed beforefieldinit Extensions.C { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig static void Goo(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } .class public abstract auto ansi sealed beforefieldinit Extensions.D { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig static void Goo(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } .class public abstract auto ansi sealed beforefieldinit extensions.C { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig static void Goo(int32 x) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } ]]> Using reference = IlasmUtilities.CreateTempAssembly(customIL.Value, prependDefaultHeader:=False) Dim ILRef = ModuleMetadata.CreateFromImage(File.ReadAllBytes(reference.Path)).GetReference() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="ExtensionMethodsDeclaredInTypesWithConflictingNamesAreNotVisible"> <file name="a.vb"> Imports Extensions Module Program Sub Main Dim x As Integer = 1 x.Goo End Sub End Module </file> </compilation>, {ILRef}) compilation1.VerifyDiagnostics( Diagnostic(ERRID.ERR_NameNotMember2, "x.Goo").WithArguments("Goo", "Integer"), Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports Extensions")) End Using End Sub <Fact()> Public Sub AttributeErrors_1() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DeclaringExtensionMethod3"> <file name="a.vb"><![CDATA[ <System.Runtime.CompilerServices.Extension()> ' 1 <System.Runtime.CompilerServices.Extension()> ' 2 Class C End Class ]]></file> </compilation>, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(compilation2, <expected><![CDATA[ BC30663: Attribute 'ExtensionAttribute' cannot be applied multiple times. <System.Runtime.CompilerServices.Extension()> ' 2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36550: 'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations. Class C ~ ]]></expected>) End Sub <Fact()> Public Sub AttributeErrors_2() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DeclaringExtensionMethod3"> <file name="a.vb"><![CDATA[ <System.Runtime.CompilerServices.ExtensionAttribute()> ' 1 <System.Runtime.CompilerServices.ExtensionAttribute()> ' 2 Class C End Class Namespace System.Runtime.CompilerServices Structure ExtensionAttribute End Structure End Namespace ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation2, <expected><![CDATA[ BC31503: 'ExtensionAttribute' cannot be used as an attribute because it is not a class. <System.Runtime.CompilerServices.ExtensionAttribute()> ' 1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31503: 'ExtensionAttribute' cannot be used as an attribute because it is not a class. <System.Runtime.CompilerServices.ExtensionAttribute()> ' 2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact()> Public Sub AttributeErrors_3() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DeclaringExtensionMethod3"> <file name="a.vb"><![CDATA[ <System.Runtime.CompilerServices.ExtensionAttribute()> ' 1 <System.Runtime.CompilerServices.ExtensionAttribute()> ' 2 Class C End Class Namespace System.Runtime.CompilerServices Class ExtensionAttribute End Class End Namespace ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation2, <expected><![CDATA[ BC31504: 'ExtensionAttribute' cannot be used as an attribute because it does not inherit from 'System.Attribute'. <System.Runtime.CompilerServices.ExtensionAttribute()> ' 1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31504: 'ExtensionAttribute' cannot be used as an attribute because it does not inherit from 'System.Attribute'. <System.Runtime.CompilerServices.ExtensionAttribute()> ' 2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact()> Public Sub AttributeErrors_4() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="DeclaringExtensionMethod3"> <file name="a.vb"><![CDATA[ <System.Runtime.CompilerServices.ExtensionAttribute()> ' 1 Class C End Class Namespace System.Runtime.CompilerServices <System.AttributeUsageAttribute(System.AttributeTargets.Assembly, Inherited := False)> Class ExtensionAttribute Inherits System.Attribute End Class End Namespace ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation2, <expected><![CDATA[ BC30662: Attribute 'ExtensionAttribute' cannot be applied to 'C' because the attribute is not valid on this declaration type. <System.Runtime.CompilerServices.ExtensionAttribute()> ' 1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact(), WorkItem(545799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545799")> Public Sub SameExtensionMethodSymbol() Dim comp = CreateCompilationWithMscorlib40AndReferences( <compilation name="SameExtensionMethodSymbol"> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Public Class C Public Sub InstanceMethod(Of T)(o As T) End Sub End Class Public Module Extensions <System.Runtime.CompilerServices.Extension()> Public Sub ExtensionMethod(Of T)(this As C, o As T) End Sub End Module Module M Sub Main() Dim obj = New C() obj.InstanceMethod("q") obj.ExtensionMethod("c") End Sub End Module ]]></file> </compilation>, references:={Net40.SystemCore}) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of InvocationExpressionSyntax)() ' Invocation Dim node = nodes.First() Dim node2 = node.Expression Assert.Equal("obj.InstanceMethod", node2.ToString()) Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, node2.Kind) Dim sym = model.GetSymbolInfo(node).Symbol Assert.NotNull(sym) Assert.Equal("InstanceMethod", sym.Name) Dim sym2 = model.GetSymbolInfo(node2).Symbol Assert.Equal(sym2, sym) node = nodes.Last() node2 = node.Expression Assert.Equal("obj.ExtensionMethod", node2.ToString()) Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, node2.Kind) sym = model.GetSymbolInfo(node).Symbol Assert.NotNull(sym) Assert.Equal("ExtensionMethod", sym.Name) sym2 = model.GetSymbolInfo(node2).Symbol Assert.Equal(sym2, sym) End Sub <ConditionalFact(GetType(NoUsedAssembliesValidation))> ' https://github.com/dotnet/roslyn/issues/40680: The test hook is blocked by this issue. <WorkItem(40680, "https://github.com/dotnet/roslyn/issues/40680")> Public Sub ScriptExtensionMethods() Dim source = <![CDATA[ Imports System.Runtime.CompilerServices <Extension> Shared Function F(o As Object) As Object Return Nothing End Function Dim o As New Object() o.F()]]> Dim comp = CreateCompilationWithMscorlib45( {VisualBasicSyntaxTree.ParseText(source.Value, TestOptions.Script)}) comp.VerifyDiagnostics() Assert.True(comp.SourceAssembly.MightContainExtensionMethods) End Sub <Fact> Public Sub InteractiveExtensionMethods() Dim references = {Net40.mscorlib, Net40.SystemCore} Dim source0 = " Imports System.Runtime.CompilerServices <Extension> Shared Function F(o As Object) As Object Return 0 End Function Dim o As New Object() ? o.F()" Dim source1 = " Imports System.Runtime.CompilerServices <Extension> Shared Function G(o As Object) As Object Return 1 End Function Dim o As New Object() ? o.G().F()" Dim s0 = VisualBasicCompilation.CreateScriptCompilation( "s0.dll", syntaxTree:=Parse(source0, TestOptions.Script), references:=references) s0.VerifyDiagnostics() Assert.True(s0.SourceAssembly.MightContainExtensionMethods) Dim s1 = VisualBasicCompilation.CreateScriptCompilation( "s1.dll", syntaxTree:=Parse(source1, TestOptions.Script), previousScriptCompilation:=s0, references:=references) s1.VerifyDiagnostics() Assert.True(s1.SourceAssembly.MightContainExtensionMethods) End Sub <Fact> Public Sub ConsumeRefExtensionMethods() Dim options = New CSharpParseOptions(CodeAnalysis.CSharp.LanguageVersion.Latest) Dim csharp = CreateCSharpCompilation(" public static class Extensions { public static void PrintValue(ref this int p) { System.Console.Write(p); } }", referencedAssemblies:={Net40.mscorlib, Net40.SystemCore}, parseOptions:=options).EmitToImageReference() Dim vb = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Module Program Sub Main() Dim value = 5 value.PrintValue() End Sub End Module ]]> </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:={csharp}) CompileAndVerify(vb, expectedOutput:="5") End Sub <Fact> Public Sub ConsumeInExtensionMethods() Dim options = New CSharpParseOptions(CodeAnalysis.CSharp.LanguageVersion.Latest) Dim csharp = CreateCSharpCompilation(" public static class Extensions { public static void PrintValue(in this int p) { System.Console.Write(p); } }", referencedAssemblies:={Net40.mscorlib, Net40.SystemCore}, parseOptions:=options).EmitToImageReference() Dim vb = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AssemblyName"> <file name="a.vb"> <![CDATA[ Module Program Sub Main() Dim value = 5 value.PrintValue() End Sub End Module ]]> </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:={csharp}) CompileAndVerify(vb, expectedOutput:="5") End Sub End Class End Namespace
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/RegexCharClass.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 // LICENSING NOTE: The license for this file is from the originating // source and not the general https://github.com/dotnet/roslyn license. // See https://github.com/dotnet/corefx/blob/68b76c30eafb3647c11e3f766a2645b130ca1448/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCharClass.cs using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions { using static FeaturesResources; /// <summary> /// Minimal copy of https://github.com/dotnet/corefx/blob/main/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCharClass.cs /// Used to accurately determine if something is a WordChar according to the .NET regex engine. /// </summary> internal static class RegexCharClass { private const int FLAGS = 0; private const int SETLENGTH = 1; private const int CATEGORYLENGTH = 2; private const int SETSTART = 3; private const short SpaceConst = 100; private const short NotSpaceConst = -100; private const char ZeroWidthJoiner = '\u200D'; private const char ZeroWidthNonJoiner = '\u200C'; private const string WordClass = "\u0000\u0000\u000A\u0000\u0002\u0004\u0005\u0003\u0001\u0006\u0009\u0013\u0000"; public static readonly Dictionary<string, (string shortDescription, string longDescription)> EscapeCategories = new() { // Others { "Cc", (Regex_other_control, "") }, { "Cf", (Regex_other_format, "") }, { "Cn", (Regex_other_not_assigned, "") }, { "Co", (Regex_other_private_use, "") }, { "Cs", (Regex_other_surrogate, "") }, { "C", (Regex_all_control_characters_short, Regex_all_control_characters_long) }, // Letters { "Ll", (Regex_letter_lowercase, "") }, { "Lm", (Regex_letter_modifier, "") }, { "Lo", (Regex_letter_other, "") }, { "Lt", (Regex_letter_titlecase, "") }, { "Lu", (Regex_letter_uppercase, "") }, { "L", (Regex_all_letter_characters_short, Regex_all_letter_characters_long) }, // Marks { "Mc", (Regex_mark_spacing_combining, "") }, { "Me", (Regex_mark_enclosing, "") }, { "Mn", (Regex_mark_nonspacing, "") }, { "M", (Regex_all_diacritic_marks_short, Regex_all_diacritic_marks_long) }, // Numbers { "Nd", (Regex_number_decimal_digit, "") }, { "Nl", (Regex_number_letter, "") }, { "No", (Regex_number_other, "") }, { "N", (Regex_all_numbers_short, Regex_all_numbers_long) }, // Punctuation { "Pc", (Regex_punctuation_connector, "") }, { "Pd", (Regex_punctuation_dash, "") }, { "Pe", (Regex_punctuation_close, "") }, { "Po", (Regex_punctuation_other, "") }, { "Ps", (Regex_punctuation_open, "") }, { "Pf", (Regex_punctuation_final_quote, "") }, { "Pi", (Regex_punctuation_initial_quote, "") }, { "P", (Regex_all_punctuation_characters_short, Regex_all_punctuation_characters_long) }, // Symbols { "Sc", (Regex_symbol_currency, "") }, { "Sk", (Regex_symbol_modifier, "") }, { "Sm", (Regex_symbol_math, "") }, { "So", (Regex_symbol_other, "") }, { "S", (Regex_all_symbols_short, Regex_all_symbols_long) }, // Separators { "Zl", (Regex_separator_line, "") }, { "Zp", (Regex_separator_paragraph, "") }, { "Zs", (Regex_separator_space, "") }, { "Z", (Regex_all_separator_characters_short, Regex_all_separator_characters_long) }, { "IsAlphabeticPresentationForms", ("", "") }, { "IsArabic", ("", "") }, { "IsArabicPresentationForms-A", ("", "") }, { "IsArabicPresentationForms-B", ("", "") }, { "IsArmenian", ("", "") }, { "IsArrows", ("", "") }, { "IsBasicLatin", ("", "") }, { "IsBengali", ("", "") }, { "IsBlockElements", ("", "") }, { "IsBopomofo", ("", "") }, { "IsBopomofoExtended", ("", "") }, { "IsBoxDrawing", ("", "") }, { "IsBraillePatterns", ("", "") }, { "IsBuhid", ("", "") }, { "IsCJKCompatibility", ("", "") }, { "IsCJKCompatibilityForms", ("", "") }, { "IsCJKCompatibilityIdeographs", ("", "") }, { "IsCJKRadicalsSupplement", ("", "") }, { "IsCJKSymbolsandPunctuation", ("", "") }, { "IsCJKUnifiedIdeographs", ("", "") }, { "IsCJKUnifiedIdeographsExtensionA", ("", "") }, { "IsCherokee", ("", "") }, { "IsCombiningDiacriticalMarks", ("", "") }, { "IsCombiningDiacriticalMarksforSymbols", ("", "") }, { "IsCombiningHalfMarks", ("", "") }, { "IsCombiningMarksforSymbols", ("", "") }, { "IsControlPictures", ("", "") }, { "IsCurrencySymbols", ("", "") }, { "IsCyrillic", ("", "") }, { "IsCyrillicSupplement", ("", "") }, { "IsDevanagari", ("", "") }, { "IsDingbats", ("", "") }, { "IsEnclosedAlphanumerics", ("", "") }, { "IsEnclosedCJKLettersandMonths", ("", "") }, { "IsEthiopic", ("", "") }, { "IsGeneralPunctuation", ("", "") }, { "IsGeometricShapes", ("", "") }, { "IsGeorgian", ("", "") }, { "IsGreek", ("", "") }, { "IsGreekExtended", ("", "") }, { "IsGreekandCoptic", ("", "") }, { "IsGujarati", ("", "") }, { "IsGurmukhi", ("", "") }, { "IsHalfwidthandFullwidthForms", ("", "") }, { "IsHangulCompatibilityJamo", ("", "") }, { "IsHangulJamo", ("", "") }, { "IsHangulSyllables", ("", "") }, { "IsHanunoo", ("", "") }, { "IsHebrew", ("", "") }, { "IsHighPrivateUseSurrogates", ("", "") }, { "IsHighSurrogates", ("", "") }, { "IsHiragana", ("", "") }, { "IsIPAExtensions", ("", "") }, { "IsIdeographicDescriptionCharacters", ("", "") }, { "IsKanbun", ("", "") }, { "IsKangxiRadicals", ("", "") }, { "IsKannada", ("", "") }, { "IsKatakana", ("", "") }, { "IsKatakanaPhoneticExtensions", ("", "") }, { "IsKhmer", ("", "") }, { "IsKhmerSymbols", ("", "") }, { "IsLao", ("", "") }, { "IsLatin-1Supplement", ("", "") }, { "IsLatinExtended-A", ("", "") }, { "IsLatinExtended-B", ("", "") }, { "IsLatinExtendedAdditional", ("", "") }, { "IsLetterlikeSymbols", ("", "") }, { "IsLimbu", ("", "") }, { "IsLowSurrogates", ("", "") }, { "IsMalayalam", ("", "") }, { "IsMathematicalOperators", ("", "") }, { "IsMiscellaneousMathematicalSymbols-A", ("", "") }, { "IsMiscellaneousMathematicalSymbols-B", ("", "") }, { "IsMiscellaneousSymbols", ("", "") }, { "IsMiscellaneousSymbolsandArrows", ("", "") }, { "IsMiscellaneousTechnical", ("", "") }, { "IsMongolian", ("", "") }, { "IsMyanmar", ("", "") }, { "IsNumberForms", ("", "") }, { "IsOgham", ("", "") }, { "IsOpticalCharacterRecognition", ("", "") }, { "IsOriya", ("", "") }, { "IsPhoneticExtensions", ("", "") }, { "IsPrivateUse", ("", "") }, { "IsPrivateUseArea", ("", "") }, { "IsRunic", ("", "") }, { "IsSinhala", ("", "") }, { "IsSmallFormVariants", ("", "") }, { "IsSpacingModifierLetters", ("", "") }, { "IsSpecials", ("", "") }, { "IsSuperscriptsandSubscripts", ("", "") }, { "IsSupplementalArrows-A", ("", "") }, { "IsSupplementalArrows-B", ("", "") }, { "IsSupplementalMathematicalOperators", ("", "") }, { "IsSyriac", ("", "") }, { "IsTagalog", ("", "") }, { "IsTagbanwa", ("", "") }, { "IsTaiLe", ("", "") }, { "IsTamil", ("", "") }, { "IsTelugu", ("", "") }, { "IsThaana", ("", "") }, { "IsThai", ("", "") }, { "IsTibetan", ("", "") }, { "IsUnifiedCanadianAboriginalSyllabics", ("", "") }, { "IsVariationSelectors", ("", "") }, { "IsYiRadicals", ("", "") }, { "IsYiSyllables", ("", "") }, { "IsYijingHexagramSymbols", ("", "") }, { "_xmlC", ("", "") }, { "_xmlD", ("", "") }, { "_xmlI", ("", "") }, { "_xmlW", ("", "") }, }; public static bool IsEscapeCategory(string value) => EscapeCategories.ContainsKey(value); public static bool IsWordChar(VirtualChar r) { // unicode characters that do not fit in 16bits are not supported by // .net regex system. if (r.Value > char.MaxValue) return false; var ch = (char)r.Value; // According to UTS#18 Unicode Regular Expressions (http://www.unicode.org/reports/tr18/) // RL 1.4 Simple Word Boundaries The class of <word_character> includes all Alphabetic // values from the Unicode character database, from UnicodeData.txt [UData], plus the U+200C // ZERO WIDTH NON-JOINER and U+200D ZERO WIDTH JOINER. return CharInClass(ch, WordClass) || ch == ZeroWidthJoiner || ch == ZeroWidthNonJoiner; } internal static bool CharInClass(char ch, string set) => CharInClassRecursive(ch, set, 0); internal static bool CharInClassRecursive(char ch, string set, int start) { int mySetLength = set[start + SETLENGTH]; int myCategoryLength = set[start + CATEGORYLENGTH]; var myEndPosition = start + SETSTART + mySetLength + myCategoryLength; var subtracted = false; if (set.Length > myEndPosition) { subtracted = CharInClassRecursive(ch, set, myEndPosition); } var b = CharInClassInternal(ch, set, start, mySetLength, myCategoryLength); // Note that we apply the negation *before* performing the subtraction. This is because // the negation only applies to the first char class, not the entire subtraction. if (set[start + FLAGS] == 1) b = !b; return b && !subtracted; } /// <summary> /// Determines a character's membership in a character class (via the /// string representation of the class). /// </summary> private static bool CharInClassInternal(char ch, string set, int start, int mySetLength, int myCategoryLength) { int min; int max; int mid; min = start + SETSTART; max = min + mySetLength; while (min != max) { mid = (min + max) / 2; if (ch < set[mid]) max = mid; else min = mid + 1; } // The starting position of the set within the character class determines // whether what an odd or even ending position means. If the start is odd, // an *even* ending position means the character was in the set. With recursive // subtractions in the mix, the starting position = start+SETSTART. Since we know that // SETSTART is odd, we can simplify it out of the equation. But if it changes we need to // reverse this check. Debug.Assert((SETSTART & 0x1) == 1, "If SETSTART is not odd, the calculation below this will be reversed"); if ((min & 0x1) == (start & 0x1)) { return true; } else { if (myCategoryLength == 0) return false; return CharInCategory(ch, set, start, mySetLength, myCategoryLength); } } private static bool CharInCategory(char ch, string set, int start, int mySetLength, int myCategoryLength) { var chcategory = CharUnicodeInfo.GetUnicodeCategory(ch); var i = start + SETSTART + mySetLength; var end = i + myCategoryLength; while (i < end) { int curcat = unchecked((short)set[i]); if (curcat == 0) { // zero is our marker for a group of categories - treated as a unit if (CharInCategoryGroup(chcategory, set, ref i)) return true; } else if (curcat > 0) { // greater than zero is a positive case if (curcat == SpaceConst) { if (char.IsWhiteSpace(ch)) { return true; } else { i++; continue; } } --curcat; if (chcategory == (UnicodeCategory)curcat) return true; } else { // less than zero is a negative case if (curcat == NotSpaceConst) { if (!char.IsWhiteSpace(ch)) { return true; } else { i++; continue; } } //curcat = -curcat; //--curcat; curcat = -1 - curcat; if (chcategory != (UnicodeCategory)curcat) return true; } i++; } return false; } /// <summary> /// This is used for categories which are composed of other categories - L, N, Z, W... /// These groups need special treatment when they are negated /// </summary> private static bool CharInCategoryGroup(UnicodeCategory chcategory, string category, ref int i) { i++; int curcat = unchecked((short)category[i]); if (curcat > 0) { // positive case - the character must be in ANY of the categories in the group var answer = false; while (curcat != 0) { if (!answer) { --curcat; if (chcategory == (UnicodeCategory)curcat) answer = true; } i++; curcat = (short)category[i]; } return answer; } else { // negative case - the character must be in NONE of the categories in the group var answer = true; while (curcat != 0) { if (answer) { //curcat = -curcat; //--curcat; curcat = -1 - curcat; if (chcategory == (UnicodeCategory)curcat) answer = false; } i++; curcat = unchecked((short)category[i]); } return answer; } } } }
// Licensed to the .NET Foundation under one or more 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 // LICENSING NOTE: The license for this file is from the originating // source and not the general https://github.com/dotnet/roslyn license. // See https://github.com/dotnet/corefx/blob/68b76c30eafb3647c11e3f766a2645b130ca1448/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCharClass.cs using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions { using static FeaturesResources; /// <summary> /// Minimal copy of https://github.com/dotnet/corefx/blob/main/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCharClass.cs /// Used to accurately determine if something is a WordChar according to the .NET regex engine. /// </summary> internal static class RegexCharClass { private const int FLAGS = 0; private const int SETLENGTH = 1; private const int CATEGORYLENGTH = 2; private const int SETSTART = 3; private const short SpaceConst = 100; private const short NotSpaceConst = -100; private const char ZeroWidthJoiner = '\u200D'; private const char ZeroWidthNonJoiner = '\u200C'; private const string WordClass = "\u0000\u0000\u000A\u0000\u0002\u0004\u0005\u0003\u0001\u0006\u0009\u0013\u0000"; public static readonly Dictionary<string, (string shortDescription, string longDescription)> EscapeCategories = new() { // Others { "Cc", (Regex_other_control, "") }, { "Cf", (Regex_other_format, "") }, { "Cn", (Regex_other_not_assigned, "") }, { "Co", (Regex_other_private_use, "") }, { "Cs", (Regex_other_surrogate, "") }, { "C", (Regex_all_control_characters_short, Regex_all_control_characters_long) }, // Letters { "Ll", (Regex_letter_lowercase, "") }, { "Lm", (Regex_letter_modifier, "") }, { "Lo", (Regex_letter_other, "") }, { "Lt", (Regex_letter_titlecase, "") }, { "Lu", (Regex_letter_uppercase, "") }, { "L", (Regex_all_letter_characters_short, Regex_all_letter_characters_long) }, // Marks { "Mc", (Regex_mark_spacing_combining, "") }, { "Me", (Regex_mark_enclosing, "") }, { "Mn", (Regex_mark_nonspacing, "") }, { "M", (Regex_all_diacritic_marks_short, Regex_all_diacritic_marks_long) }, // Numbers { "Nd", (Regex_number_decimal_digit, "") }, { "Nl", (Regex_number_letter, "") }, { "No", (Regex_number_other, "") }, { "N", (Regex_all_numbers_short, Regex_all_numbers_long) }, // Punctuation { "Pc", (Regex_punctuation_connector, "") }, { "Pd", (Regex_punctuation_dash, "") }, { "Pe", (Regex_punctuation_close, "") }, { "Po", (Regex_punctuation_other, "") }, { "Ps", (Regex_punctuation_open, "") }, { "Pf", (Regex_punctuation_final_quote, "") }, { "Pi", (Regex_punctuation_initial_quote, "") }, { "P", (Regex_all_punctuation_characters_short, Regex_all_punctuation_characters_long) }, // Symbols { "Sc", (Regex_symbol_currency, "") }, { "Sk", (Regex_symbol_modifier, "") }, { "Sm", (Regex_symbol_math, "") }, { "So", (Regex_symbol_other, "") }, { "S", (Regex_all_symbols_short, Regex_all_symbols_long) }, // Separators { "Zl", (Regex_separator_line, "") }, { "Zp", (Regex_separator_paragraph, "") }, { "Zs", (Regex_separator_space, "") }, { "Z", (Regex_all_separator_characters_short, Regex_all_separator_characters_long) }, { "IsAlphabeticPresentationForms", ("", "") }, { "IsArabic", ("", "") }, { "IsArabicPresentationForms-A", ("", "") }, { "IsArabicPresentationForms-B", ("", "") }, { "IsArmenian", ("", "") }, { "IsArrows", ("", "") }, { "IsBasicLatin", ("", "") }, { "IsBengali", ("", "") }, { "IsBlockElements", ("", "") }, { "IsBopomofo", ("", "") }, { "IsBopomofoExtended", ("", "") }, { "IsBoxDrawing", ("", "") }, { "IsBraillePatterns", ("", "") }, { "IsBuhid", ("", "") }, { "IsCJKCompatibility", ("", "") }, { "IsCJKCompatibilityForms", ("", "") }, { "IsCJKCompatibilityIdeographs", ("", "") }, { "IsCJKRadicalsSupplement", ("", "") }, { "IsCJKSymbolsandPunctuation", ("", "") }, { "IsCJKUnifiedIdeographs", ("", "") }, { "IsCJKUnifiedIdeographsExtensionA", ("", "") }, { "IsCherokee", ("", "") }, { "IsCombiningDiacriticalMarks", ("", "") }, { "IsCombiningDiacriticalMarksforSymbols", ("", "") }, { "IsCombiningHalfMarks", ("", "") }, { "IsCombiningMarksforSymbols", ("", "") }, { "IsControlPictures", ("", "") }, { "IsCurrencySymbols", ("", "") }, { "IsCyrillic", ("", "") }, { "IsCyrillicSupplement", ("", "") }, { "IsDevanagari", ("", "") }, { "IsDingbats", ("", "") }, { "IsEnclosedAlphanumerics", ("", "") }, { "IsEnclosedCJKLettersandMonths", ("", "") }, { "IsEthiopic", ("", "") }, { "IsGeneralPunctuation", ("", "") }, { "IsGeometricShapes", ("", "") }, { "IsGeorgian", ("", "") }, { "IsGreek", ("", "") }, { "IsGreekExtended", ("", "") }, { "IsGreekandCoptic", ("", "") }, { "IsGujarati", ("", "") }, { "IsGurmukhi", ("", "") }, { "IsHalfwidthandFullwidthForms", ("", "") }, { "IsHangulCompatibilityJamo", ("", "") }, { "IsHangulJamo", ("", "") }, { "IsHangulSyllables", ("", "") }, { "IsHanunoo", ("", "") }, { "IsHebrew", ("", "") }, { "IsHighPrivateUseSurrogates", ("", "") }, { "IsHighSurrogates", ("", "") }, { "IsHiragana", ("", "") }, { "IsIPAExtensions", ("", "") }, { "IsIdeographicDescriptionCharacters", ("", "") }, { "IsKanbun", ("", "") }, { "IsKangxiRadicals", ("", "") }, { "IsKannada", ("", "") }, { "IsKatakana", ("", "") }, { "IsKatakanaPhoneticExtensions", ("", "") }, { "IsKhmer", ("", "") }, { "IsKhmerSymbols", ("", "") }, { "IsLao", ("", "") }, { "IsLatin-1Supplement", ("", "") }, { "IsLatinExtended-A", ("", "") }, { "IsLatinExtended-B", ("", "") }, { "IsLatinExtendedAdditional", ("", "") }, { "IsLetterlikeSymbols", ("", "") }, { "IsLimbu", ("", "") }, { "IsLowSurrogates", ("", "") }, { "IsMalayalam", ("", "") }, { "IsMathematicalOperators", ("", "") }, { "IsMiscellaneousMathematicalSymbols-A", ("", "") }, { "IsMiscellaneousMathematicalSymbols-B", ("", "") }, { "IsMiscellaneousSymbols", ("", "") }, { "IsMiscellaneousSymbolsandArrows", ("", "") }, { "IsMiscellaneousTechnical", ("", "") }, { "IsMongolian", ("", "") }, { "IsMyanmar", ("", "") }, { "IsNumberForms", ("", "") }, { "IsOgham", ("", "") }, { "IsOpticalCharacterRecognition", ("", "") }, { "IsOriya", ("", "") }, { "IsPhoneticExtensions", ("", "") }, { "IsPrivateUse", ("", "") }, { "IsPrivateUseArea", ("", "") }, { "IsRunic", ("", "") }, { "IsSinhala", ("", "") }, { "IsSmallFormVariants", ("", "") }, { "IsSpacingModifierLetters", ("", "") }, { "IsSpecials", ("", "") }, { "IsSuperscriptsandSubscripts", ("", "") }, { "IsSupplementalArrows-A", ("", "") }, { "IsSupplementalArrows-B", ("", "") }, { "IsSupplementalMathematicalOperators", ("", "") }, { "IsSyriac", ("", "") }, { "IsTagalog", ("", "") }, { "IsTagbanwa", ("", "") }, { "IsTaiLe", ("", "") }, { "IsTamil", ("", "") }, { "IsTelugu", ("", "") }, { "IsThaana", ("", "") }, { "IsThai", ("", "") }, { "IsTibetan", ("", "") }, { "IsUnifiedCanadianAboriginalSyllabics", ("", "") }, { "IsVariationSelectors", ("", "") }, { "IsYiRadicals", ("", "") }, { "IsYiSyllables", ("", "") }, { "IsYijingHexagramSymbols", ("", "") }, { "_xmlC", ("", "") }, { "_xmlD", ("", "") }, { "_xmlI", ("", "") }, { "_xmlW", ("", "") }, }; public static bool IsEscapeCategory(string value) => EscapeCategories.ContainsKey(value); public static bool IsWordChar(VirtualChar r) { // unicode characters that do not fit in 16bits are not supported by // .net regex system. if (r.Value > char.MaxValue) return false; var ch = (char)r.Value; // According to UTS#18 Unicode Regular Expressions (http://www.unicode.org/reports/tr18/) // RL 1.4 Simple Word Boundaries The class of <word_character> includes all Alphabetic // values from the Unicode character database, from UnicodeData.txt [UData], plus the U+200C // ZERO WIDTH NON-JOINER and U+200D ZERO WIDTH JOINER. return CharInClass(ch, WordClass) || ch == ZeroWidthJoiner || ch == ZeroWidthNonJoiner; } internal static bool CharInClass(char ch, string set) => CharInClassRecursive(ch, set, 0); internal static bool CharInClassRecursive(char ch, string set, int start) { int mySetLength = set[start + SETLENGTH]; int myCategoryLength = set[start + CATEGORYLENGTH]; var myEndPosition = start + SETSTART + mySetLength + myCategoryLength; var subtracted = false; if (set.Length > myEndPosition) { subtracted = CharInClassRecursive(ch, set, myEndPosition); } var b = CharInClassInternal(ch, set, start, mySetLength, myCategoryLength); // Note that we apply the negation *before* performing the subtraction. This is because // the negation only applies to the first char class, not the entire subtraction. if (set[start + FLAGS] == 1) b = !b; return b && !subtracted; } /// <summary> /// Determines a character's membership in a character class (via the /// string representation of the class). /// </summary> private static bool CharInClassInternal(char ch, string set, int start, int mySetLength, int myCategoryLength) { int min; int max; int mid; min = start + SETSTART; max = min + mySetLength; while (min != max) { mid = (min + max) / 2; if (ch < set[mid]) max = mid; else min = mid + 1; } // The starting position of the set within the character class determines // whether what an odd or even ending position means. If the start is odd, // an *even* ending position means the character was in the set. With recursive // subtractions in the mix, the starting position = start+SETSTART. Since we know that // SETSTART is odd, we can simplify it out of the equation. But if it changes we need to // reverse this check. Debug.Assert((SETSTART & 0x1) == 1, "If SETSTART is not odd, the calculation below this will be reversed"); if ((min & 0x1) == (start & 0x1)) { return true; } else { if (myCategoryLength == 0) return false; return CharInCategory(ch, set, start, mySetLength, myCategoryLength); } } private static bool CharInCategory(char ch, string set, int start, int mySetLength, int myCategoryLength) { var chcategory = CharUnicodeInfo.GetUnicodeCategory(ch); var i = start + SETSTART + mySetLength; var end = i + myCategoryLength; while (i < end) { int curcat = unchecked((short)set[i]); if (curcat == 0) { // zero is our marker for a group of categories - treated as a unit if (CharInCategoryGroup(chcategory, set, ref i)) return true; } else if (curcat > 0) { // greater than zero is a positive case if (curcat == SpaceConst) { if (char.IsWhiteSpace(ch)) { return true; } else { i++; continue; } } --curcat; if (chcategory == (UnicodeCategory)curcat) return true; } else { // less than zero is a negative case if (curcat == NotSpaceConst) { if (!char.IsWhiteSpace(ch)) { return true; } else { i++; continue; } } //curcat = -curcat; //--curcat; curcat = -1 - curcat; if (chcategory != (UnicodeCategory)curcat) return true; } i++; } return false; } /// <summary> /// This is used for categories which are composed of other categories - L, N, Z, W... /// These groups need special treatment when they are negated /// </summary> private static bool CharInCategoryGroup(UnicodeCategory chcategory, string category, ref int i) { i++; int curcat = unchecked((short)category[i]); if (curcat > 0) { // positive case - the character must be in ANY of the categories in the group var answer = false; while (curcat != 0) { if (!answer) { --curcat; if (chcategory == (UnicodeCategory)curcat) answer = true; } i++; curcat = (short)category[i]; } return answer; } else { // negative case - the character must be in NONE of the categories in the group var answer = true; while (curcat != 0) { if (answer) { //curcat = -curcat; //--curcat; curcat = -1 - curcat; if (chcategory == (UnicodeCategory)curcat) answer = false; } i++; curcat = unchecked((short)category[i]); } return answer; } } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Workspaces/CSharp/Portable/CodeGeneration/ParameterGenerator.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 Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.PooledObjects; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class ParameterGenerator { public static ParameterListSyntax GenerateParameterList( ImmutableArray<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { return GenerateParameterList((IEnumerable<IParameterSymbol>)parameterDefinitions, isExplicit, options); } public static ParameterListSyntax GenerateParameterList( IEnumerable<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { var parameters = GetParameters(parameterDefinitions, isExplicit, options); return SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters)); } public static BracketedParameterListSyntax GenerateBracketedParameterList( ImmutableArray<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { return GenerateBracketedParameterList((IList<IParameterSymbol>)parameterDefinitions, isExplicit, options); } public static BracketedParameterListSyntax GenerateBracketedParameterList( IEnumerable<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { // Bracketed parameter lists come from indexers. Those don't have type parameters, so we // could never have a typeParameterMapping. var parameters = GetParameters(parameterDefinitions, isExplicit, options); return SyntaxFactory.BracketedParameterList( parameters: SyntaxFactory.SeparatedList(parameters)); } internal static ImmutableArray<ParameterSyntax> GetParameters( IEnumerable<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { var result = ArrayBuilder<ParameterSyntax>.GetInstance(); var seenOptional = false; var isFirstParam = true; foreach (var p in parameterDefinitions) { var parameter = GetParameter(p, options, isExplicit, isFirstParam, seenOptional); result.Add(parameter); seenOptional = seenOptional || parameter.Default != null; isFirstParam = false; } return result.ToImmutableAndFree(); } internal static ParameterSyntax GetParameter(IParameterSymbol p, CodeGenerationOptions options, bool isExplicit, bool isFirstParam, bool seenOptional) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ParameterSyntax>(p, options); if (reusableSyntax != null) { return reusableSyntax; } return SyntaxFactory.Parameter(p.Name.ToIdentifierToken()) .WithAttributeLists(GenerateAttributes(p, isExplicit, options)) .WithModifiers(GenerateModifiers(p, isFirstParam)) .WithType(p.Type.GenerateTypeSyntax()) .WithDefault(GenerateEqualsValueClause(p, isExplicit, seenOptional)); } private static SyntaxTokenList GenerateModifiers( IParameterSymbol parameter, bool isFirstParam) { var list = CSharpSyntaxGeneratorInternal.GetParameterModifiers(parameter.RefKind); if (isFirstParam && parameter.ContainingSymbol is IMethodSymbol methodSymbol && methodSymbol.IsExtensionMethod) { list = list.Add(SyntaxFactory.Token(SyntaxKind.ThisKeyword)); } if (parameter.IsParams) { list = list.Add(SyntaxFactory.Token(SyntaxKind.ParamsKeyword)); } return list; } private static EqualsValueClauseSyntax GenerateEqualsValueClause( IParameterSymbol parameter, bool isExplicit, bool seenOptional) { if (!parameter.IsParams && !isExplicit && !parameter.IsRefOrOut()) { if (parameter.HasExplicitDefaultValue || seenOptional) { var defaultValue = parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null; if (defaultValue is DateTime) { return null; } return SyntaxFactory.EqualsValueClause( GenerateEqualsValueClauseWorker(parameter, defaultValue)); } } return null; } private static ExpressionSyntax GenerateEqualsValueClauseWorker( IParameterSymbol parameter, object value) { return ExpressionGenerator.GenerateExpression(parameter.Type, value, canUseFieldReference: true); } private static SyntaxList<AttributeListSyntax> GenerateAttributes( IParameterSymbol parameter, bool isExplicit, CodeGenerationOptions options) { if (isExplicit) { return default; } var attributes = parameter.GetAttributes(); if (attributes.Length == 0) { return default; } return AttributeGenerator.GenerateAttributeLists(attributes, options); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.PooledObjects; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class ParameterGenerator { public static ParameterListSyntax GenerateParameterList( ImmutableArray<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { return GenerateParameterList((IEnumerable<IParameterSymbol>)parameterDefinitions, isExplicit, options); } public static ParameterListSyntax GenerateParameterList( IEnumerable<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { var parameters = GetParameters(parameterDefinitions, isExplicit, options); return SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters)); } public static BracketedParameterListSyntax GenerateBracketedParameterList( ImmutableArray<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { return GenerateBracketedParameterList((IList<IParameterSymbol>)parameterDefinitions, isExplicit, options); } public static BracketedParameterListSyntax GenerateBracketedParameterList( IEnumerable<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { // Bracketed parameter lists come from indexers. Those don't have type parameters, so we // could never have a typeParameterMapping. var parameters = GetParameters(parameterDefinitions, isExplicit, options); return SyntaxFactory.BracketedParameterList( parameters: SyntaxFactory.SeparatedList(parameters)); } internal static ImmutableArray<ParameterSyntax> GetParameters( IEnumerable<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { var result = ArrayBuilder<ParameterSyntax>.GetInstance(); var seenOptional = false; var isFirstParam = true; foreach (var p in parameterDefinitions) { var parameter = GetParameter(p, options, isExplicit, isFirstParam, seenOptional); result.Add(parameter); seenOptional = seenOptional || parameter.Default != null; isFirstParam = false; } return result.ToImmutableAndFree(); } internal static ParameterSyntax GetParameter(IParameterSymbol p, CodeGenerationOptions options, bool isExplicit, bool isFirstParam, bool seenOptional) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ParameterSyntax>(p, options); if (reusableSyntax != null) { return reusableSyntax; } return SyntaxFactory.Parameter(p.Name.ToIdentifierToken()) .WithAttributeLists(GenerateAttributes(p, isExplicit, options)) .WithModifiers(GenerateModifiers(p, isFirstParam)) .WithType(p.Type.GenerateTypeSyntax()) .WithDefault(GenerateEqualsValueClause(p, isExplicit, seenOptional)); } private static SyntaxTokenList GenerateModifiers( IParameterSymbol parameter, bool isFirstParam) { var list = CSharpSyntaxGeneratorInternal.GetParameterModifiers(parameter.RefKind); if (isFirstParam && parameter.ContainingSymbol is IMethodSymbol methodSymbol && methodSymbol.IsExtensionMethod) { list = list.Add(SyntaxFactory.Token(SyntaxKind.ThisKeyword)); } if (parameter.IsParams) { list = list.Add(SyntaxFactory.Token(SyntaxKind.ParamsKeyword)); } return list; } private static EqualsValueClauseSyntax GenerateEqualsValueClause( IParameterSymbol parameter, bool isExplicit, bool seenOptional) { if (!parameter.IsParams && !isExplicit && !parameter.IsRefOrOut()) { if (parameter.HasExplicitDefaultValue || seenOptional) { var defaultValue = parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null; if (defaultValue is DateTime) { return null; } return SyntaxFactory.EqualsValueClause( GenerateEqualsValueClauseWorker(parameter, defaultValue)); } } return null; } private static ExpressionSyntax GenerateEqualsValueClauseWorker( IParameterSymbol parameter, object value) { return ExpressionGenerator.GenerateExpression(parameter.Type, value, canUseFieldReference: true); } private static SyntaxList<AttributeListSyntax> GenerateAttributes( IParameterSymbol parameter, bool isExplicit, CodeGenerationOptions options) { if (isExplicit) { return default; } var attributes = parameter.GetAttributes(); if (attributes.Length == 0) { return default; } return AttributeGenerator.GenerateAttributeLists(attributes, options); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/CSharp/Portable/Symbols/Source/SourceFixedFieldSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal class SourceFixedFieldSymbol : SourceMemberFieldSymbolFromDeclarator { private const int FixedSizeNotInitialized = -1; // In a fixed-size field declaration, stores the fixed size of the buffer private int _fixedSize = FixedSizeNotInitialized; internal SourceFixedFieldSymbol( SourceMemberContainerTypeSymbol containingType, VariableDeclaratorSyntax declarator, DeclarationModifiers modifiers, bool modifierErrors, BindingDiagnosticBag diagnostics) : base(containingType, declarator, modifiers, modifierErrors, diagnostics) { // Checked in parser: a fixed field declaration requires a length in square brackets Debug.Assert(this.IsFixedSizeBuffer); } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = this.DeclaringCompilation; var systemType = compilation.GetWellKnownType(WellKnownType.System_Type); var intType = compilation.GetSpecialType(SpecialType.System_Int32); var item1 = new TypedConstant(systemType, TypedConstantKind.Type, ((PointerTypeSymbol)this.Type).PointedAtType); var item2 = new TypedConstant(intType, TypedConstantKind.Primitive, this.FixedSize); AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_FixedBufferAttribute__ctor, ImmutableArray.Create<TypedConstant>(item1, item2))); } public sealed override int FixedSize { get { if (_fixedSize == FixedSizeNotInitialized) { BindingDiagnosticBag diagnostics = BindingDiagnosticBag.GetInstance(); int size = 0; VariableDeclaratorSyntax declarator = VariableDeclaratorNode; if (declarator.ArgumentList == null) { // Diagnostic reported by parser. } else { SeparatedSyntaxList<ArgumentSyntax> arguments = declarator.ArgumentList.Arguments; if (arguments.Count == 0 || arguments[0].Expression.Kind() == SyntaxKind.OmittedArraySizeExpression) { Debug.Assert(declarator.ArgumentList.ContainsDiagnostics, "The parser should have caught this."); } else { if (arguments.Count > 1) { diagnostics.Add(ErrorCode.ERR_FixedBufferTooManyDimensions, declarator.ArgumentList.Location); } ExpressionSyntax sizeExpression = arguments[0].Expression; BinderFactory binderFactory = this.DeclaringCompilation.GetBinderFactory(SyntaxTree); Binder binder = binderFactory.GetBinder(sizeExpression); binder = new ExecutableCodeBinder(sizeExpression, binder.ContainingMemberOrLambda, binder).GetBinder(sizeExpression); TypeSymbol intType = binder.GetSpecialType(SpecialType.System_Int32, diagnostics, sizeExpression); BoundExpression boundSizeExpression = binder.GenerateConversionForAssignment( intType, binder.BindValue(sizeExpression, diagnostics, Binder.BindValueKind.RValue), diagnostics); // GetAndValidateConstantValue doesn't generate a very intuitive-reading diagnostic // for this situation, but this is what the Dev10 compiler produces. ConstantValue sizeConstant = ConstantValueUtils.GetAndValidateConstantValue(boundSizeExpression, this, intType, sizeExpression.Location, diagnostics); Debug.Assert(sizeConstant != null); Debug.Assert(sizeConstant.IsIntegral || diagnostics.HasAnyErrors() || sizeExpression.HasErrors); if (sizeConstant.IsIntegral) { int int32Value = sizeConstant.Int32Value; if (int32Value > 0) { size = int32Value; TypeSymbol elementType = ((PointerTypeSymbol)this.Type).PointedAtType; int elementSize = elementType.FixedBufferElementSizeInBytes(); long totalSize = elementSize * 1L * int32Value; if (totalSize > int.MaxValue) { // Fixed size buffer of length '{0}' and type '{1}' is too big diagnostics.Add(ErrorCode.ERR_FixedOverflow, sizeExpression.Location, int32Value, elementType); } } else { diagnostics.Add(ErrorCode.ERR_InvalidFixedArraySize, sizeExpression.Location); } } } } // Winner writes diagnostics. if (Interlocked.CompareExchange(ref _fixedSize, size, FixedSizeNotInitialized) == FixedSizeNotInitialized) { this.AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.FixedSize); } diagnostics.Free(); } Debug.Assert(_fixedSize != FixedSizeNotInitialized); return _fixedSize; } } internal override NamedTypeSymbol FixedImplementationType(PEModuleBuilder emitModule) { return emitModule.SetFixedImplementationType(this); } } internal sealed class FixedFieldImplementationType : SynthesizedContainer { internal const string FixedElementFieldName = "FixedElementField"; private readonly SourceMemberFieldSymbol _field; private readonly MethodSymbol _constructor; private readonly FieldSymbol _internalField; public FixedFieldImplementationType(SourceMemberFieldSymbol field) : base(GeneratedNames.MakeFixedFieldImplementationName(field.Name), typeParameters: ImmutableArray<TypeParameterSymbol>.Empty, typeMap: TypeMap.Empty) { _field = field; _constructor = new SynthesizedInstanceConstructor(this); _internalField = new SynthesizedFieldSymbol(this, ((PointerTypeSymbol)field.Type).PointedAtType, FixedElementFieldName, isPublic: true); } public override Symbol ContainingSymbol { get { return _field.ContainingType; } } public override TypeKind TypeKind { get { return TypeKind.Struct; } } internal override MethodSymbol Constructor { get { return _constructor; } } internal override TypeLayout Layout { get { int nElements = _field.FixedSize; var elementType = ((PointerTypeSymbol)_field.Type).PointedAtType; int elementSize = elementType.FixedBufferElementSizeInBytes(); const int alignment = 0; int totalSize = nElements * elementSize; const LayoutKind layoutKind = LayoutKind.Sequential; return new TypeLayout(layoutKind, totalSize, alignment); } } internal override CharSet MarshallingCharSet { get { // We manually propagate the CharSet field of StructLayout attribute for fabricated structs implementing fixed buffers. // See void AttrBind::EmitStructLayoutAttributeCharSet(AttributeNode *attr) in native codebase. return _field.ContainingType.MarshallingCharSet; } } internal override FieldSymbol FixedElementField { get { return _internalField; } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = ContainingSymbol.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_UnsafeValueTypeAttribute__ctor)); } public override IEnumerable<string> MemberNames { get { return SpecializedCollections.SingletonEnumerable(FixedElementFieldName); } } public override ImmutableArray<Symbol> GetMembers() { return ImmutableArray.Create<Symbol>(_constructor, _internalField); } public override ImmutableArray<Symbol> GetMembers(string name) { return (name == _constructor.Name) ? ImmutableArray.Create<Symbol>(_constructor) : (name == FixedElementFieldName) ? ImmutableArray.Create<Symbol>(_internalField) : ImmutableArray<Symbol>.Empty; } public override Accessibility DeclaredAccessibility { get { return Accessibility.Public; } } internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => ContainingAssembly.GetSpecialType(SpecialType.System_ValueType); public sealed override bool AreLocalsZeroed => throw ExceptionUtilities.Unreachable; internal override bool IsRecord => false; internal override bool IsRecordStruct => false; internal override bool HasPossibleWellKnownCloneMethod() => false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal class SourceFixedFieldSymbol : SourceMemberFieldSymbolFromDeclarator { private const int FixedSizeNotInitialized = -1; // In a fixed-size field declaration, stores the fixed size of the buffer private int _fixedSize = FixedSizeNotInitialized; internal SourceFixedFieldSymbol( SourceMemberContainerTypeSymbol containingType, VariableDeclaratorSyntax declarator, DeclarationModifiers modifiers, bool modifierErrors, BindingDiagnosticBag diagnostics) : base(containingType, declarator, modifiers, modifierErrors, diagnostics) { // Checked in parser: a fixed field declaration requires a length in square brackets Debug.Assert(this.IsFixedSizeBuffer); } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = this.DeclaringCompilation; var systemType = compilation.GetWellKnownType(WellKnownType.System_Type); var intType = compilation.GetSpecialType(SpecialType.System_Int32); var item1 = new TypedConstant(systemType, TypedConstantKind.Type, ((PointerTypeSymbol)this.Type).PointedAtType); var item2 = new TypedConstant(intType, TypedConstantKind.Primitive, this.FixedSize); AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_FixedBufferAttribute__ctor, ImmutableArray.Create<TypedConstant>(item1, item2))); } public sealed override int FixedSize { get { if (_fixedSize == FixedSizeNotInitialized) { BindingDiagnosticBag diagnostics = BindingDiagnosticBag.GetInstance(); int size = 0; VariableDeclaratorSyntax declarator = VariableDeclaratorNode; if (declarator.ArgumentList == null) { // Diagnostic reported by parser. } else { SeparatedSyntaxList<ArgumentSyntax> arguments = declarator.ArgumentList.Arguments; if (arguments.Count == 0 || arguments[0].Expression.Kind() == SyntaxKind.OmittedArraySizeExpression) { Debug.Assert(declarator.ArgumentList.ContainsDiagnostics, "The parser should have caught this."); } else { if (arguments.Count > 1) { diagnostics.Add(ErrorCode.ERR_FixedBufferTooManyDimensions, declarator.ArgumentList.Location); } ExpressionSyntax sizeExpression = arguments[0].Expression; BinderFactory binderFactory = this.DeclaringCompilation.GetBinderFactory(SyntaxTree); Binder binder = binderFactory.GetBinder(sizeExpression); binder = new ExecutableCodeBinder(sizeExpression, binder.ContainingMemberOrLambda, binder).GetBinder(sizeExpression); TypeSymbol intType = binder.GetSpecialType(SpecialType.System_Int32, diagnostics, sizeExpression); BoundExpression boundSizeExpression = binder.GenerateConversionForAssignment( intType, binder.BindValue(sizeExpression, diagnostics, Binder.BindValueKind.RValue), diagnostics); // GetAndValidateConstantValue doesn't generate a very intuitive-reading diagnostic // for this situation, but this is what the Dev10 compiler produces. ConstantValue sizeConstant = ConstantValueUtils.GetAndValidateConstantValue(boundSizeExpression, this, intType, sizeExpression.Location, diagnostics); Debug.Assert(sizeConstant != null); Debug.Assert(sizeConstant.IsIntegral || diagnostics.HasAnyErrors() || sizeExpression.HasErrors); if (sizeConstant.IsIntegral) { int int32Value = sizeConstant.Int32Value; if (int32Value > 0) { size = int32Value; TypeSymbol elementType = ((PointerTypeSymbol)this.Type).PointedAtType; int elementSize = elementType.FixedBufferElementSizeInBytes(); long totalSize = elementSize * 1L * int32Value; if (totalSize > int.MaxValue) { // Fixed size buffer of length '{0}' and type '{1}' is too big diagnostics.Add(ErrorCode.ERR_FixedOverflow, sizeExpression.Location, int32Value, elementType); } } else { diagnostics.Add(ErrorCode.ERR_InvalidFixedArraySize, sizeExpression.Location); } } } } // Winner writes diagnostics. if (Interlocked.CompareExchange(ref _fixedSize, size, FixedSizeNotInitialized) == FixedSizeNotInitialized) { this.AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.FixedSize); } diagnostics.Free(); } Debug.Assert(_fixedSize != FixedSizeNotInitialized); return _fixedSize; } } internal override NamedTypeSymbol FixedImplementationType(PEModuleBuilder emitModule) { return emitModule.SetFixedImplementationType(this); } } internal sealed class FixedFieldImplementationType : SynthesizedContainer { internal const string FixedElementFieldName = "FixedElementField"; private readonly SourceMemberFieldSymbol _field; private readonly MethodSymbol _constructor; private readonly FieldSymbol _internalField; public FixedFieldImplementationType(SourceMemberFieldSymbol field) : base(GeneratedNames.MakeFixedFieldImplementationName(field.Name), typeParameters: ImmutableArray<TypeParameterSymbol>.Empty, typeMap: TypeMap.Empty) { _field = field; _constructor = new SynthesizedInstanceConstructor(this); _internalField = new SynthesizedFieldSymbol(this, ((PointerTypeSymbol)field.Type).PointedAtType, FixedElementFieldName, isPublic: true); } public override Symbol ContainingSymbol { get { return _field.ContainingType; } } public override TypeKind TypeKind { get { return TypeKind.Struct; } } internal override MethodSymbol Constructor { get { return _constructor; } } internal override TypeLayout Layout { get { int nElements = _field.FixedSize; var elementType = ((PointerTypeSymbol)_field.Type).PointedAtType; int elementSize = elementType.FixedBufferElementSizeInBytes(); const int alignment = 0; int totalSize = nElements * elementSize; const LayoutKind layoutKind = LayoutKind.Sequential; return new TypeLayout(layoutKind, totalSize, alignment); } } internal override CharSet MarshallingCharSet { get { // We manually propagate the CharSet field of StructLayout attribute for fabricated structs implementing fixed buffers. // See void AttrBind::EmitStructLayoutAttributeCharSet(AttributeNode *attr) in native codebase. return _field.ContainingType.MarshallingCharSet; } } internal override FieldSymbol FixedElementField { get { return _internalField; } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = ContainingSymbol.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_UnsafeValueTypeAttribute__ctor)); } public override IEnumerable<string> MemberNames { get { return SpecializedCollections.SingletonEnumerable(FixedElementFieldName); } } public override ImmutableArray<Symbol> GetMembers() { return ImmutableArray.Create<Symbol>(_constructor, _internalField); } public override ImmutableArray<Symbol> GetMembers(string name) { return (name == _constructor.Name) ? ImmutableArray.Create<Symbol>(_constructor) : (name == FixedElementFieldName) ? ImmutableArray.Create<Symbol>(_internalField) : ImmutableArray<Symbol>.Empty; } public override Accessibility DeclaredAccessibility { get { return Accessibility.Public; } } internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => ContainingAssembly.GetSpecialType(SpecialType.System_ValueType); public sealed override bool AreLocalsZeroed => throw ExceptionUtilities.Unreachable; internal override bool IsRecord => false; internal override bool IsRecordStruct => false; internal override bool HasPossibleWellKnownCloneMethod() => false; } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Workspaces/Remote/ServiceHub/Services/EncapsulateField/RemoteEncapsulateFieldService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.EncapsulateField; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteEncapsulateFieldService : BrokeredServiceBase, IRemoteEncapsulateFieldService { internal sealed class Factory : FactoryBase<IRemoteEncapsulateFieldService> { protected override IRemoteEncapsulateFieldService CreateService(in ServiceConstructionArguments arguments) => new RemoteEncapsulateFieldService(arguments); } public RemoteEncapsulateFieldService(in ServiceConstructionArguments arguments) : base(arguments) { } public ValueTask<ImmutableArray<(DocumentId, ImmutableArray<TextChange>)>> EncapsulateFieldsAsync( PinnedSolutionInfo solutionInfo, DocumentId documentId, ImmutableArray<string> fieldSymbolKeys, bool updateReferences, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = solution.GetRequiredDocument(documentId); using var _ = ArrayBuilder<IFieldSymbol>.GetInstance(out var fields); var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); foreach (var key in fieldSymbolKeys) { var resolved = SymbolKey.ResolveString(key, compilation, cancellationToken: cancellationToken).GetAnySymbol() as IFieldSymbol; if (resolved == null) return ImmutableArray<(DocumentId, ImmutableArray<TextChange>)>.Empty; fields.Add(resolved); } var service = document.GetLanguageService<AbstractEncapsulateFieldService>(); var newSolution = await service.EncapsulateFieldsAsync( document, fields.ToImmutable(), updateReferences, cancellationToken).ConfigureAwait(false); return await RemoteUtilities.GetDocumentTextChangesAsync( solution, newSolution, cancellationToken).ConfigureAwait(false); }, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.EncapsulateField; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteEncapsulateFieldService : BrokeredServiceBase, IRemoteEncapsulateFieldService { internal sealed class Factory : FactoryBase<IRemoteEncapsulateFieldService> { protected override IRemoteEncapsulateFieldService CreateService(in ServiceConstructionArguments arguments) => new RemoteEncapsulateFieldService(arguments); } public RemoteEncapsulateFieldService(in ServiceConstructionArguments arguments) : base(arguments) { } public ValueTask<ImmutableArray<(DocumentId, ImmutableArray<TextChange>)>> EncapsulateFieldsAsync( PinnedSolutionInfo solutionInfo, DocumentId documentId, ImmutableArray<string> fieldSymbolKeys, bool updateReferences, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = solution.GetRequiredDocument(documentId); using var _ = ArrayBuilder<IFieldSymbol>.GetInstance(out var fields); var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); foreach (var key in fieldSymbolKeys) { var resolved = SymbolKey.ResolveString(key, compilation, cancellationToken: cancellationToken).GetAnySymbol() as IFieldSymbol; if (resolved == null) return ImmutableArray<(DocumentId, ImmutableArray<TextChange>)>.Empty; fields.Add(resolved); } var service = document.GetLanguageService<AbstractEncapsulateFieldService>(); var newSolution = await service.EncapsulateFieldsAsync( document, fields.ToImmutable(), updateReferences, cancellationToken).ConfigureAwait(false); return await RemoteUtilities.GetDocumentTextChangesAsync( solution, newSolution, cancellationToken).ConfigureAwait(false); }, cancellationToken); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/PreprocessorDirectives/IfDirectiveKeywordRecommender.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.PreprocessorDirectives ''' <summary> ''' Recommends the "#If" preprocessor directive ''' </summary> Friend Class IfDirectiveKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("#If", VBFeaturesResources.Conditionally_compiles_selected_blocks_of_code_depending_on_the_value_of_an_expression)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Return If(context.IsPreprocessorStartContext AndAlso Not context.SyntaxTree.IsEnumMemberNameContext(context), s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.PreprocessorDirectives ''' <summary> ''' Recommends the "#If" preprocessor directive ''' </summary> Friend Class IfDirectiveKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("#If", VBFeaturesResources.Conditionally_compiles_selected_blocks_of_code_depending_on_the_value_of_an_expression)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Return If(context.IsPreprocessorStartContext AndAlso Not context.SyntaxTree.IsEnumMemberNameContext(context), s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) End Function End Class End Namespace
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/Core/Portable/InternalUtilities/SpanUtilities.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 { internal static class SpanUtilities { public static bool All<TElement, TParam>(this ReadOnlySpan<TElement> span, TParam param, Func<TElement, TParam, bool> predicate) { foreach (var e in span) { if (!predicate(e, param)) { return false; } } return true; } public static bool All<TElement>(this ReadOnlySpan<TElement> span, Func<TElement, bool> predicate) { foreach (var e in span) { if (!predicate(e)) { return false; } } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { internal static class SpanUtilities { public static bool All<TElement, TParam>(this ReadOnlySpan<TElement> span, TParam param, Func<TElement, TParam, bool> predicate) { foreach (var e in span) { if (!predicate(e, param)) { return false; } } return true; } public static bool All<TElement>(this ReadOnlySpan<TElement> span, Func<TElement, bool> predicate) { foreach (var e in span) { if (!predicate(e)) { return false; } } return true; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/EditorFeatures/CSharpTest2/Recommendations/VoidKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class VoidKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass() { await VerifyKeywordAsync( @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStackAlloc() { await VerifyAbsenceAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFixedStatement() { await VerifyKeywordAsync( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotInCastType(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"var str = (($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotInCastType2(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"var str = (($$)items) as string;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInTypeOf(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync(@"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync(@"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync(@"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync(@"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync(@"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync(@"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync(@"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMultipleRootAttributes() { await VerifyKeywordAsync(@"[goo][goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPartial() { await VerifyKeywordAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternal() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPublic() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPrivate() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate_Script() { await VerifyKeywordAsync(SourceCodeKind.Script, @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterProtected() { await VerifyAbsenceAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() => await VerifyKeywordAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticInClass() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticPublic() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"static public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"static public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegate() { await VerifyKeywordAsync( @"delegate $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterAnonymousDelegate(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"var q = delegate $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterEvent() { await VerifyAbsenceAsync( @"class C { event $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVoid() { await VerifyAbsenceAsync( @"class C { void $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNew() { await VerifyAbsenceAsync( @"new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedNew() { await VerifyKeywordAsync( @"class C { new $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInUnsafeBlock(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"unsafe { $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeMethod() { await VerifyKeywordAsync( @"class C { unsafe void Goo() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeClass() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameter() { await VerifyAbsenceAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeParameter1() { await VerifyKeywordAsync( @"class C { unsafe void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeParameter2() { await VerifyKeywordAsync( @"unsafe class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCast() { await VerifyAbsenceAsync( @"class C { void Goo() { hr = GetRealProcAddress(""CompareAssemblyIdentity"", ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCast2() { await VerifyAbsenceAsync( @"class C { void Goo() { hr = GetRealProcAddress(""CompareAssemblyIdentity"", ($$**)pfnCompareAssemblyIdentity);"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeCast() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { hr = GetRealProcAddress(""CompareAssemblyIdentity"", ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeCast2() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { hr = GetRealProcAddress(""CompareAssemblyIdentity"", ($$**)pfnCompareAssemblyIdentity);"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeConversionOperator() { await VerifyKeywordAsync( @"class C { unsafe implicit operator int(C c) { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeOperator() { await VerifyKeywordAsync( @"class C { unsafe int operator ++(C c) { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeConstructor() { await VerifyKeywordAsync( @"class C { unsafe C() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeDestructor() { await VerifyKeywordAsync( @"class C { unsafe ~C() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeProperty() { await VerifyKeywordAsync( @"class C { unsafe int Goo { get { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeIndexer() { await VerifyKeywordAsync( @"class C { unsafe int this[int i] { get { $$"); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotInDefault(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"default($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInSizeOf(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [WorkItem(544347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544347")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeDefaultExpression() { await VerifyKeywordAsync( @"unsafe class C { static void Method1(void* p1 = default($$"); } [WorkItem(544347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544347")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDefaultExpression() { await VerifyAbsenceAsync( @"class C { static void Method1(void* p1 = default($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction() { await VerifyKeywordAsync(@" class C { void M() { $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [WorkItem(14525, "https://github.com/dotnet/roslyn/issues/14525")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction2() { await VerifyKeywordAsync(@" class C { void M() { async $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction3() { await VerifyAbsenceAsync(@" class C { void M() { async async $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction4() { await VerifyAbsenceAsync(@" class C { void M() { var async $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction5() { await VerifyAbsenceAsync(@" using System; class C { void M(Action<int> a) { M(async $$ () => } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction6() { await VerifyKeywordAsync(@" class C { void M() { unsafe async $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction7() { await VerifyKeywordAsync(@" using System; class C { void M(Action<int> a) { M(async () => { async $$ }) } }"); } [Fact] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointer01() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointer02() { await VerifyKeywordAsync(@" class C<T> { C<delegate*<$$"); } [Fact] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointer03() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointer04() { await VerifyKeywordAsync(@" class C { delegate*<int, v$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(43295, "https://github.com/dotnet/roslyn/issues/43295")] public async Task TestAfterReadonlyInStruct() { await VerifyKeywordAsync(@" struct S { public readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReadonlyInRecordStruct() { await VerifyKeywordAsync(@" record struct S { public readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(43295, "https://github.com/dotnet/roslyn/issues/43295")] public async Task TestNotAfterReadonlyInClass() { await VerifyAbsenceAsync(@" class C { public readonly $$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class VoidKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass() { await VerifyKeywordAsync( @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStackAlloc() { await VerifyAbsenceAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFixedStatement() { await VerifyKeywordAsync( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotInCastType(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"var str = (($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotInCastType2(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"var str = (($$)items) as string;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInTypeOf(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync(@"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync(@"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync(@"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync(@"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync(@"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync(@"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync(@"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMultipleRootAttributes() { await VerifyKeywordAsync(@"[goo][goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPartial() { await VerifyKeywordAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternal() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPublic() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPrivate() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate_Script() { await VerifyKeywordAsync(SourceCodeKind.Script, @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterProtected() { await VerifyAbsenceAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() => await VerifyKeywordAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticInClass() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticPublic() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"static public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"static public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegate() { await VerifyKeywordAsync( @"delegate $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterAnonymousDelegate(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"var q = delegate $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterEvent() { await VerifyAbsenceAsync( @"class C { event $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVoid() { await VerifyAbsenceAsync( @"class C { void $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNew() { await VerifyAbsenceAsync( @"new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedNew() { await VerifyKeywordAsync( @"class C { new $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInUnsafeBlock(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"unsafe { $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeMethod() { await VerifyKeywordAsync( @"class C { unsafe void Goo() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeClass() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameter() { await VerifyAbsenceAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeParameter1() { await VerifyKeywordAsync( @"class C { unsafe void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeParameter2() { await VerifyKeywordAsync( @"unsafe class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCast() { await VerifyAbsenceAsync( @"class C { void Goo() { hr = GetRealProcAddress(""CompareAssemblyIdentity"", ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCast2() { await VerifyAbsenceAsync( @"class C { void Goo() { hr = GetRealProcAddress(""CompareAssemblyIdentity"", ($$**)pfnCompareAssemblyIdentity);"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeCast() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { hr = GetRealProcAddress(""CompareAssemblyIdentity"", ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeCast2() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { hr = GetRealProcAddress(""CompareAssemblyIdentity"", ($$**)pfnCompareAssemblyIdentity);"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeConversionOperator() { await VerifyKeywordAsync( @"class C { unsafe implicit operator int(C c) { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeOperator() { await VerifyKeywordAsync( @"class C { unsafe int operator ++(C c) { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeConstructor() { await VerifyKeywordAsync( @"class C { unsafe C() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeDestructor() { await VerifyKeywordAsync( @"class C { unsafe ~C() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeProperty() { await VerifyKeywordAsync( @"class C { unsafe int Goo { get { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeIndexer() { await VerifyKeywordAsync( @"class C { unsafe int this[int i] { get { $$"); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotInDefault(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"default($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInSizeOf(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [WorkItem(544347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544347")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeDefaultExpression() { await VerifyKeywordAsync( @"unsafe class C { static void Method1(void* p1 = default($$"); } [WorkItem(544347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544347")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDefaultExpression() { await VerifyAbsenceAsync( @"class C { static void Method1(void* p1 = default($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction() { await VerifyKeywordAsync(@" class C { void M() { $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [WorkItem(14525, "https://github.com/dotnet/roslyn/issues/14525")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction2() { await VerifyKeywordAsync(@" class C { void M() { async $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction3() { await VerifyAbsenceAsync(@" class C { void M() { async async $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction4() { await VerifyAbsenceAsync(@" class C { void M() { var async $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction5() { await VerifyAbsenceAsync(@" using System; class C { void M(Action<int> a) { M(async $$ () => } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction6() { await VerifyKeywordAsync(@" class C { void M() { unsafe async $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction7() { await VerifyKeywordAsync(@" using System; class C { void M(Action<int> a) { M(async () => { async $$ }) } }"); } [Fact] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointer01() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointer02() { await VerifyKeywordAsync(@" class C<T> { C<delegate*<$$"); } [Fact] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointer03() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointer04() { await VerifyKeywordAsync(@" class C { delegate*<int, v$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(43295, "https://github.com/dotnet/roslyn/issues/43295")] public async Task TestAfterReadonlyInStruct() { await VerifyKeywordAsync(@" struct S { public readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReadonlyInRecordStruct() { await VerifyKeywordAsync(@" record struct S { public readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(43295, "https://github.com/dotnet/roslyn/issues/43295")] public async Task TestNotAfterReadonlyInClass() { await VerifyAbsenceAsync(@" class C { public readonly $$"); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Features/Core/Portable/QuickInfo/CommonQuickInfoContext.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; namespace Microsoft.CodeAnalysis.QuickInfo { internal readonly struct CommonQuickInfoContext { public readonly Workspace Workspace; public readonly SemanticModel SemanticModel; public readonly int Position; public readonly CancellationToken CancellationToken; public CommonQuickInfoContext( Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken) { Workspace = workspace; SemanticModel = semanticModel; Position = position; 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; namespace Microsoft.CodeAnalysis.QuickInfo { internal readonly struct CommonQuickInfoContext { public readonly Workspace Workspace; public readonly SemanticModel SemanticModel; public readonly int Position; public readonly CancellationToken CancellationToken; public CommonQuickInfoContext( Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken) { Workspace = workspace; SemanticModel = semanticModel; Position = position; CancellationToken = cancellationToken; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/EditorFeatures/Core.Wpf/Notification/EditorNotificationServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Windows; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Notification; namespace Microsoft.CodeAnalysis.Editor.Implementation.Notification { [ExportWorkspaceServiceFactory(typeof(INotificationService), ServiceLayer.Editor)] [Shared] internal class EditorNotificationServiceFactory : IWorkspaceServiceFactory { private static readonly object s_gate = new object(); private static EditorDialogService s_singleton; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public EditorNotificationServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { lock (s_gate) { if (s_singleton == null) { s_singleton = new EditorDialogService(); } } return s_singleton; } private class EditorDialogService : INotificationService, INotificationServiceCallback { /// <summary> /// For testing purposes only. If non-null, this callback will be invoked instead of showing a dialog. /// </summary> public Action<string, string, NotificationSeverity> NotificationCallback { get; set; } public void SendNotification( string message, string title = null, NotificationSeverity severity = NotificationSeverity.Warning) { var callback = NotificationCallback; if (callback != null) { // invoke the callback callback(message, title, severity); } else { var image = SeverityToImage(severity); MessageBox.Show(message, title, MessageBoxButton.OK, image); } } public bool ConfirmMessageBox( string message, string title = null, NotificationSeverity severity = NotificationSeverity.Warning) { var callback = NotificationCallback; if (callback != null) { // invoke the callback and assume 'Yes' was clicked. Since this is a test-only scenario, assuming yes should be fine. callback(message, title, severity); return true; } else { var image = SeverityToImage(severity); return MessageBox.Show(message, title, MessageBoxButton.YesNo, image) == MessageBoxResult.Yes; } } private static MessageBoxImage SeverityToImage(NotificationSeverity severity) => severity switch { NotificationSeverity.Information => MessageBoxImage.Information, NotificationSeverity.Warning => MessageBoxImage.Warning, _ => MessageBoxImage.Error, }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Windows; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Notification; namespace Microsoft.CodeAnalysis.Editor.Implementation.Notification { [ExportWorkspaceServiceFactory(typeof(INotificationService), ServiceLayer.Editor)] [Shared] internal class EditorNotificationServiceFactory : IWorkspaceServiceFactory { private static readonly object s_gate = new object(); private static EditorDialogService s_singleton; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public EditorNotificationServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { lock (s_gate) { if (s_singleton == null) { s_singleton = new EditorDialogService(); } } return s_singleton; } private class EditorDialogService : INotificationService, INotificationServiceCallback { /// <summary> /// For testing purposes only. If non-null, this callback will be invoked instead of showing a dialog. /// </summary> public Action<string, string, NotificationSeverity> NotificationCallback { get; set; } public void SendNotification( string message, string title = null, NotificationSeverity severity = NotificationSeverity.Warning) { var callback = NotificationCallback; if (callback != null) { // invoke the callback callback(message, title, severity); } else { var image = SeverityToImage(severity); MessageBox.Show(message, title, MessageBoxButton.OK, image); } } public bool ConfirmMessageBox( string message, string title = null, NotificationSeverity severity = NotificationSeverity.Warning) { var callback = NotificationCallback; if (callback != null) { // invoke the callback and assume 'Yes' was clicked. Since this is a test-only scenario, assuming yes should be fine. callback(message, title, severity); return true; } else { var image = SeverityToImage(severity); return MessageBox.Show(message, title, MessageBoxButton.YesNo, image) == MessageBoxResult.Yes; } } private static MessageBoxImage SeverityToImage(NotificationSeverity severity) => severity switch { NotificationSeverity.Information => MessageBoxImage.Information, NotificationSeverity.Warning => MessageBoxImage.Warning, _ => MessageBoxImage.Error, }; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./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,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Workspaces/CoreTestUtilities/Formatting/FormattingTestBase.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Formatting { [UseExportProvider] public abstract class FormattingTestBase { private protected Task AssertFormatAsync( string expected, string code, string language, bool debugMode = false, OptionsCollection? changedOptionSet = null, bool testWithTransformation = true) { return AssertFormatAsync(expected, code, new[] { new TextSpan(0, code.Length) }, language, debugMode, changedOptionSet, testWithTransformation); } private protected async Task AssertFormatAsync( string expected, string code, IEnumerable<TextSpan> spans, string language, #pragma warning disable IDE0060 // Remove unused parameter - https://github.com/dotnet/roslyn/issues/44225 bool debugMode = false, #pragma warning restore IDE0060 // Remove unused parameter OptionsCollection? changedOptionSet = null, bool treeCompare = true, ParseOptions? parseOptions = null) { using (var workspace = new AdhocWorkspace()) { var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", language); if (parseOptions != null) { project = project.WithParseOptions(parseOptions); } var document = project.AddDocument("Document", SourceText.From(code)); var syntaxTree = await document.GetRequiredSyntaxTreeAsync(CancellationToken.None); var options = workspace.Options; if (changedOptionSet != null) { foreach (var entry in changedOptionSet) { options = options.WithChangedOption(entry.Key, entry.Value); } } var root = await syntaxTree.GetRootAsync(); AssertFormat(workspace, expected, root, spans, options, await document.GetTextAsync()); // format with node and transform AssertFormatWithTransformation(workspace, expected, root, spans, options, treeCompare, parseOptions); } } protected abstract SyntaxNode ParseCompilation(string text, ParseOptions? parseOptions); protected void AssertFormatWithTransformation( Workspace workspace, string expected, SyntaxNode root, IEnumerable<TextSpan> spans, OptionSet optionSet, bool treeCompare = true, ParseOptions? parseOptions = null) { var newRootNode = Formatter.Format(root, spans, workspace, optionSet, CancellationToken.None); Assert.Equal(expected, newRootNode.ToFullString()); // test doesn't use parsing option. add one if needed later var newRootNodeFromString = ParseCompilation(expected, parseOptions); if (treeCompare) { // simple check to see whether two nodes are equivalent each other. Assert.True(newRootNodeFromString.IsEquivalentTo(newRootNode)); } } protected static void AssertFormat(Workspace workspace, string expected, SyntaxNode root, IEnumerable<TextSpan> spans, OptionSet optionSet, SourceText sourceText) { var result = Formatter.GetFormattedTextChanges(root, spans, workspace, optionSet); AssertResult(expected, sourceText, result); } protected static void AssertResult(string expected, SourceText sourceText, IList<TextChange> result) { var actual = sourceText.WithChanges(result).ToString(); AssertEx.EqualOrDiff(expected, actual); } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Formatting { [UseExportProvider] public abstract class FormattingTestBase { private protected Task AssertFormatAsync( string expected, string code, string language, bool debugMode = false, OptionsCollection? changedOptionSet = null, bool testWithTransformation = true) { return AssertFormatAsync(expected, code, new[] { new TextSpan(0, code.Length) }, language, debugMode, changedOptionSet, testWithTransformation); } private protected async Task AssertFormatAsync( string expected, string code, IEnumerable<TextSpan> spans, string language, #pragma warning disable IDE0060 // Remove unused parameter - https://github.com/dotnet/roslyn/issues/44225 bool debugMode = false, #pragma warning restore IDE0060 // Remove unused parameter OptionsCollection? changedOptionSet = null, bool treeCompare = true, ParseOptions? parseOptions = null) { using (var workspace = new AdhocWorkspace()) { var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", language); if (parseOptions != null) { project = project.WithParseOptions(parseOptions); } var document = project.AddDocument("Document", SourceText.From(code)); var syntaxTree = await document.GetRequiredSyntaxTreeAsync(CancellationToken.None); var options = workspace.Options; if (changedOptionSet != null) { foreach (var entry in changedOptionSet) { options = options.WithChangedOption(entry.Key, entry.Value); } } var root = await syntaxTree.GetRootAsync(); AssertFormat(workspace, expected, root, spans, options, await document.GetTextAsync()); // format with node and transform AssertFormatWithTransformation(workspace, expected, root, spans, options, treeCompare, parseOptions); } } protected abstract SyntaxNode ParseCompilation(string text, ParseOptions? parseOptions); protected void AssertFormatWithTransformation( Workspace workspace, string expected, SyntaxNode root, IEnumerable<TextSpan> spans, OptionSet optionSet, bool treeCompare = true, ParseOptions? parseOptions = null) { var newRootNode = Formatter.Format(root, spans, workspace, optionSet, CancellationToken.None); Assert.Equal(expected, newRootNode.ToFullString()); // test doesn't use parsing option. add one if needed later var newRootNodeFromString = ParseCompilation(expected, parseOptions); if (treeCompare) { // simple check to see whether two nodes are equivalent each other. Assert.True(newRootNodeFromString.IsEquivalentTo(newRootNode)); } } protected static void AssertFormat(Workspace workspace, string expected, SyntaxNode root, IEnumerable<TextSpan> spans, OptionSet optionSet, SourceText sourceText) { var result = Formatter.GetFormattedTextChanges(root, spans, workspace, optionSet); AssertResult(expected, sourceText, result); } protected static void AssertResult(string expected, SourceText sourceText, IList<TextChange> result) { var actual = sourceText.WithChanges(result).ToString(); AssertEx.EqualOrDiff(expected, actual); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Interactive/csi/csi.coreclr.rsp
# basic references /r:System.Collections /r:System.Collections.Concurrent /r:System.Console /r:System.Diagnostics.Debug /r:System.Diagnostics.Process /r:System.Diagnostics.StackTrace /r:System.Globalization /r:System.IO /r:System.IO.FileSystem /r:System.IO.FileSystem.Primitives /r:System.Reflection /r:System.Reflection.Primitives /r:System.Runtime /r:System.Runtime.Extensions /r:System.Runtime.InteropServices /r:System.Text.Encoding /r:System.Text.Encoding.CodePages /r:System.Text.Encoding.Extensions /r:System.Text.RegularExpressions /r:System.Threading /r:System.Threading.Tasks /r:System.Threading.Tasks.Parallel /r:System.Threading.Thread # extra references /r:System.Dynamic.Runtime /r:System.Linq /r:System.Linq.Expressions /r:System.Runtime.Numerics /r:System.ValueTuple /r:Microsoft.CSharp # imports /u:System /u:System.IO /u:System.Collections.Generic /u:System.Console /u:System.Diagnostics /u:System.Dynamic /u:System.Linq /u:System.Linq.Expressions /u:System.Text /u:System.Threading.Tasks
# basic references /r:System.Collections /r:System.Collections.Concurrent /r:System.Console /r:System.Diagnostics.Debug /r:System.Diagnostics.Process /r:System.Diagnostics.StackTrace /r:System.Globalization /r:System.IO /r:System.IO.FileSystem /r:System.IO.FileSystem.Primitives /r:System.Reflection /r:System.Reflection.Primitives /r:System.Runtime /r:System.Runtime.Extensions /r:System.Runtime.InteropServices /r:System.Text.Encoding /r:System.Text.Encoding.CodePages /r:System.Text.Encoding.Extensions /r:System.Text.RegularExpressions /r:System.Threading /r:System.Threading.Tasks /r:System.Threading.Tasks.Parallel /r:System.Threading.Thread # extra references /r:System.Dynamic.Runtime /r:System.Linq /r:System.Linq.Expressions /r:System.Runtime.Numerics /r:System.ValueTuple /r:Microsoft.CSharp # imports /u:System /u:System.IO /u:System.Collections.Generic /u:System.Console /u:System.Diagnostics /u:System.Dynamic /u:System.Linq /u:System.Linq.Expressions /u:System.Text /u:System.Threading.Tasks
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Definitions/GoToDefinitionHandler.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.Concurrent; using System.Composition; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Definitions; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Handler.Definitions { [ExportLspRequestHandlerProvider(StringConstants.XamlLanguageName), Shared] [ProvidesMethod(Methods.TextDocumentDefinitionName)] internal class GoToDefinitionHandler : AbstractStatelessRequestHandler<TextDocumentPositionParams, LSP.Location[]> { private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GoToDefinitionHandler(IMetadataAsSourceFileService metadataAsSourceFileService) { _metadataAsSourceFileService = metadataAsSourceFileService; } public override string Method => Methods.TextDocumentDefinitionName; public override bool MutatesSolutionState => false; public override bool RequiresLSPSolution => true; public override TextDocumentIdentifier? GetTextDocumentIdentifier(TextDocumentPositionParams request) => request.TextDocument; public override async Task<LSP.Location[]> HandleRequestAsync(TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) { var locations = new ConcurrentBag<LSP.Location>(); var document = context.Document; if (document == null) { return locations.ToArray(); } var xamlGoToDefinitionService = document.Project.LanguageServices.GetService<IXamlGoToDefinitionService>(); if (xamlGoToDefinitionService == null) { return locations.ToArray(); } var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false); var definitions = await xamlGoToDefinitionService.GetDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); using var _ = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var definition in definitions) { var task = Task.Run(async () => { foreach (var location in await this.GetLocationsAsync(definition, context, cancellationToken).ConfigureAwait(false)) { locations.Add(location); } }, cancellationToken); tasks.Add(task); } await Task.WhenAll(tasks).ConfigureAwait(false); return locations.ToArray(); } private async Task<LSP.Location[]> GetLocationsAsync(XamlDefinition definition, RequestContext context, CancellationToken cancellationToken) { using var _ = ArrayBuilder<LSP.Location>.GetInstance(out var locations); if (definition is XamlSourceDefinition sourceDefinition) { locations.AddIfNotNull(await GetSourceDefinitionLocationAsync(sourceDefinition, context, cancellationToken).ConfigureAwait(false)); } else if (definition is XamlSymbolDefinition symbolDefinition) { locations.AddRange(await GetSymbolDefinitionLocationsAsync(symbolDefinition, context, _metadataAsSourceFileService, cancellationToken).ConfigureAwait(false)); } else { throw new InvalidOperationException($"Unexpected {nameof(XamlDefinition)} Type"); } return locations.ToArray(); } private static async Task<LSP.Location?> GetSourceDefinitionLocationAsync(XamlSourceDefinition sourceDefinition, RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(sourceDefinition.FilePath); var document = context.Solution?.GetDocuments(ProtocolConversions.GetUriFromFilePath(sourceDefinition.FilePath)).FirstOrDefault(); if (document != null) { var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var span = sourceDefinition.GetTextSpan(sourceText); if (span != null) { return await ProtocolConversions.TextSpanToLocationAsync( document, span.Value, isStale: false, cancellationToken).ConfigureAwait(false); } } else { // Cannot find the file in solution. This is probably a file lives outside of the solution like generic.xaml // which lives in the Windows SDK folder. Try getting the SourceText from the file path. using var fileStream = new FileStream(sourceDefinition.FilePath, FileMode.Open, FileAccess.Read); var sourceText = SourceText.From(fileStream); var span = sourceDefinition.GetTextSpan(sourceText); if (span != null) { return new LSP.Location { Uri = new Uri(sourceDefinition.FilePath), Range = ProtocolConversions.TextSpanToRange(span.Value, sourceText), }; } } return null; } private static async Task<LSP.Location[]> GetSymbolDefinitionLocationsAsync(XamlSymbolDefinition symbolDefinition, RequestContext context, IMetadataAsSourceFileService metadataAsSourceFileService, CancellationToken cancellationToken) { Contract.ThrowIfNull(symbolDefinition.Symbol); using var _ = ArrayBuilder<LSP.Location>.GetInstance(out var locations); var symbol = symbolDefinition.Symbol; var items = NavigableItemFactory.GetItemsFromPreferredSourceLocations(context.Solution, symbol, displayTaggedParts: null, cancellationToken); if (items.Any()) { foreach (var item in items) { var location = await ProtocolConversions.TextSpanToLocationAsync( item.Document, item.SourceSpan, item.IsStale, cancellationToken).ConfigureAwait(false); locations.AddIfNotNull(location); } } else { var metadataLocation = symbol.Locations.Where(loc => loc.IsInMetadata).FirstOrDefault(); if (metadataLocation != null && metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol)) { var project = context.Document?.GetCodeProject(); if (project != null) { var declarationFile = await metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, allowDecompilation: false, cancellationToken).ConfigureAwait(false); var linePosSpan = declarationFile.IdentifierLocation.GetLineSpan().Span; locations.Add(new LSP.Location { Uri = new Uri(declarationFile.FilePath), Range = ProtocolConversions.LinePositionToRange(linePosSpan), }); } } } return locations.ToArray(); } } }
// Licensed to the .NET Foundation under one or more 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.Concurrent; using System.Composition; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Definitions; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Handler.Definitions { [ExportLspRequestHandlerProvider(StringConstants.XamlLanguageName), Shared] [ProvidesMethod(Methods.TextDocumentDefinitionName)] internal class GoToDefinitionHandler : AbstractStatelessRequestHandler<TextDocumentPositionParams, LSP.Location[]> { private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GoToDefinitionHandler(IMetadataAsSourceFileService metadataAsSourceFileService) { _metadataAsSourceFileService = metadataAsSourceFileService; } public override string Method => Methods.TextDocumentDefinitionName; public override bool MutatesSolutionState => false; public override bool RequiresLSPSolution => true; public override TextDocumentIdentifier? GetTextDocumentIdentifier(TextDocumentPositionParams request) => request.TextDocument; public override async Task<LSP.Location[]> HandleRequestAsync(TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) { var locations = new ConcurrentBag<LSP.Location>(); var document = context.Document; if (document == null) { return locations.ToArray(); } var xamlGoToDefinitionService = document.Project.LanguageServices.GetService<IXamlGoToDefinitionService>(); if (xamlGoToDefinitionService == null) { return locations.ToArray(); } var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false); var definitions = await xamlGoToDefinitionService.GetDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); using var _ = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var definition in definitions) { var task = Task.Run(async () => { foreach (var location in await this.GetLocationsAsync(definition, context, cancellationToken).ConfigureAwait(false)) { locations.Add(location); } }, cancellationToken); tasks.Add(task); } await Task.WhenAll(tasks).ConfigureAwait(false); return locations.ToArray(); } private async Task<LSP.Location[]> GetLocationsAsync(XamlDefinition definition, RequestContext context, CancellationToken cancellationToken) { using var _ = ArrayBuilder<LSP.Location>.GetInstance(out var locations); if (definition is XamlSourceDefinition sourceDefinition) { locations.AddIfNotNull(await GetSourceDefinitionLocationAsync(sourceDefinition, context, cancellationToken).ConfigureAwait(false)); } else if (definition is XamlSymbolDefinition symbolDefinition) { locations.AddRange(await GetSymbolDefinitionLocationsAsync(symbolDefinition, context, _metadataAsSourceFileService, cancellationToken).ConfigureAwait(false)); } else { throw new InvalidOperationException($"Unexpected {nameof(XamlDefinition)} Type"); } return locations.ToArray(); } private static async Task<LSP.Location?> GetSourceDefinitionLocationAsync(XamlSourceDefinition sourceDefinition, RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(sourceDefinition.FilePath); var document = context.Solution?.GetDocuments(ProtocolConversions.GetUriFromFilePath(sourceDefinition.FilePath)).FirstOrDefault(); if (document != null) { var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var span = sourceDefinition.GetTextSpan(sourceText); if (span != null) { return await ProtocolConversions.TextSpanToLocationAsync( document, span.Value, isStale: false, cancellationToken).ConfigureAwait(false); } } else { // Cannot find the file in solution. This is probably a file lives outside of the solution like generic.xaml // which lives in the Windows SDK folder. Try getting the SourceText from the file path. using var fileStream = new FileStream(sourceDefinition.FilePath, FileMode.Open, FileAccess.Read); var sourceText = SourceText.From(fileStream); var span = sourceDefinition.GetTextSpan(sourceText); if (span != null) { return new LSP.Location { Uri = new Uri(sourceDefinition.FilePath), Range = ProtocolConversions.TextSpanToRange(span.Value, sourceText), }; } } return null; } private static async Task<LSP.Location[]> GetSymbolDefinitionLocationsAsync(XamlSymbolDefinition symbolDefinition, RequestContext context, IMetadataAsSourceFileService metadataAsSourceFileService, CancellationToken cancellationToken) { Contract.ThrowIfNull(symbolDefinition.Symbol); using var _ = ArrayBuilder<LSP.Location>.GetInstance(out var locations); var symbol = symbolDefinition.Symbol; var items = NavigableItemFactory.GetItemsFromPreferredSourceLocations(context.Solution, symbol, displayTaggedParts: null, cancellationToken); if (items.Any()) { foreach (var item in items) { var location = await ProtocolConversions.TextSpanToLocationAsync( item.Document, item.SourceSpan, item.IsStale, cancellationToken).ConfigureAwait(false); locations.AddIfNotNull(location); } } else { var metadataLocation = symbol.Locations.Where(loc => loc.IsInMetadata).FirstOrDefault(); if (metadataLocation != null && metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol)) { var project = context.Document?.GetCodeProject(); if (project != null) { var declarationFile = await metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, allowDecompilation: false, cancellationToken).ConfigureAwait(false); var linePosSpan = declarationFile.IdentifierLocation.GetLineSpan().Span; locations.Add(new LSP.Location { Uri = new Uri(declarationFile.FilePath), Range = ProtocolConversions.LinePositionToRange(linePosSpan), }); } } } return locations.ToArray(); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/Core/CodeAnalysisTest/Analyzers/AnalyzerFileReferenceAppDomainTests.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. #if NET472 // AppDomains using System; using System.Collections.Immutable; using System.Reflection; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.Desktop; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class RemoteAnalyzerFileReferenceTest : MarshalByRefObject { public override object InitializeLifetimeService() { return null; } public Exception LoadAnalyzer(string analyzerPath) { Exception analyzerLoadException = null; var analyzerRef = new AnalyzerFileReference(analyzerPath, TestAnalyzerAssemblyLoader.LoadFromFile); analyzerRef.AnalyzerLoadFailed += (s, e) => analyzerLoadException = e.Exception; var builder = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>(); analyzerRef.AddAnalyzers(builder, LanguageNames.CSharp); return analyzerLoadException; } } public class AnalyzerFileReferenceAppDomainTests : TestBase { [Fact] public void TestAnalyzerLoading_AppDomain() { var dir = Temp.CreateDirectory(); dir.CopyFile(typeof(AppDomainUtils).Assembly.Location); dir.CopyFile(typeof(RemoteAnalyzerFileReferenceTest).Assembly.Location); var analyzerFile = DesktopTestHelpers.CreateCSharpAnalyzerAssemblyWithTestAnalyzer(dir, "MyAnalyzer"); var loadDomain = AppDomainUtils.Create("AnalyzerTestDomain", basePath: dir.Path); try { // Test analyzer load success. var remoteTest = (RemoteAnalyzerFileReferenceTest)loadDomain.CreateInstanceAndUnwrap(typeof(RemoteAnalyzerFileReferenceTest).Assembly.FullName, typeof(RemoteAnalyzerFileReferenceTest).FullName); var exception = remoteTest.LoadAnalyzer(analyzerFile.Path); Assert.Null(exception); } finally { AppDomain.Unload(loadDomain); } } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/mono/mono/issues/10960")] public void TestAnalyzerLoading_Error() { var analyzerSource = @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using System.Runtime.InteropServices; [DiagnosticAnalyzer(LanguageNames.CSharp)] [StructLayout(LayoutKind.Sequential, Size = 10000000)] public class TestAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } }"; var dir = Temp.CreateDirectory(); dir.CopyFile(typeof(System.Reflection.Metadata.MetadataReader).Assembly.Location); dir.CopyFile(typeof(AppDomainUtils).Assembly.Location); dir.CopyFile(typeof(Memory<>).Assembly.Location); dir.CopyFile(typeof(System.Runtime.CompilerServices.Unsafe).Assembly.Location); var immutable = dir.CopyFile(typeof(ImmutableArray).Assembly.Location); var analyzer = dir.CopyFile(typeof(DiagnosticAnalyzer).Assembly.Location); dir.CopyFile(typeof(RemoteAnalyzerFileReferenceTest).Assembly.Location); var analyzerCompilation = CSharp.CSharpCompilation.Create( "MyAnalyzer", new SyntaxTree[] { CSharp.SyntaxFactory.ParseSyntaxTree(analyzerSource) }, new MetadataReference[] { TestMetadata.NetStandard20.mscorlib, TestMetadata.NetStandard20.netstandard, TestMetadata.NetStandard20.SystemRuntime, MetadataReference.CreateFromFile(immutable.Path), MetadataReference.CreateFromFile(analyzer.Path) }, new CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel)); var analyzerFile = dir.CreateFile("MyAnalyzer.dll").WriteAllBytes(analyzerCompilation.EmitToArray()); var loadDomain = AppDomainUtils.Create("AnalyzerTestDomain", basePath: dir.Path); try { // Test analyzer load failure. var remoteTest = (RemoteAnalyzerFileReferenceTest)loadDomain.CreateInstanceAndUnwrap(typeof(RemoteAnalyzerFileReferenceTest).Assembly.FullName, typeof(RemoteAnalyzerFileReferenceTest).FullName); var exception = remoteTest.LoadAnalyzer(analyzerFile.Path); Assert.NotNull(exception as TypeLoadException); } finally { AppDomain.Unload(loadDomain); } } private static Assembly OnResolve(object sender, ResolveEventArgs e) { Console.WriteLine($"Resolve in {AppDomain.CurrentDomain.Id} for {e.Name}"); return null; } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #if NET472 // AppDomains using System; using System.Collections.Immutable; using System.Reflection; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.Desktop; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class RemoteAnalyzerFileReferenceTest : MarshalByRefObject { public override object InitializeLifetimeService() { return null; } public Exception LoadAnalyzer(string analyzerPath) { Exception analyzerLoadException = null; var analyzerRef = new AnalyzerFileReference(analyzerPath, TestAnalyzerAssemblyLoader.LoadFromFile); analyzerRef.AnalyzerLoadFailed += (s, e) => analyzerLoadException = e.Exception; var builder = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>(); analyzerRef.AddAnalyzers(builder, LanguageNames.CSharp); return analyzerLoadException; } } public class AnalyzerFileReferenceAppDomainTests : TestBase { [Fact] public void TestAnalyzerLoading_AppDomain() { var dir = Temp.CreateDirectory(); dir.CopyFile(typeof(AppDomainUtils).Assembly.Location); dir.CopyFile(typeof(RemoteAnalyzerFileReferenceTest).Assembly.Location); var analyzerFile = DesktopTestHelpers.CreateCSharpAnalyzerAssemblyWithTestAnalyzer(dir, "MyAnalyzer"); var loadDomain = AppDomainUtils.Create("AnalyzerTestDomain", basePath: dir.Path); try { // Test analyzer load success. var remoteTest = (RemoteAnalyzerFileReferenceTest)loadDomain.CreateInstanceAndUnwrap(typeof(RemoteAnalyzerFileReferenceTest).Assembly.FullName, typeof(RemoteAnalyzerFileReferenceTest).FullName); var exception = remoteTest.LoadAnalyzer(analyzerFile.Path); Assert.Null(exception); } finally { AppDomain.Unload(loadDomain); } } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/mono/mono/issues/10960")] public void TestAnalyzerLoading_Error() { var analyzerSource = @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using System.Runtime.InteropServices; [DiagnosticAnalyzer(LanguageNames.CSharp)] [StructLayout(LayoutKind.Sequential, Size = 10000000)] public class TestAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } }"; var dir = Temp.CreateDirectory(); dir.CopyFile(typeof(System.Reflection.Metadata.MetadataReader).Assembly.Location); dir.CopyFile(typeof(AppDomainUtils).Assembly.Location); dir.CopyFile(typeof(Memory<>).Assembly.Location); dir.CopyFile(typeof(System.Runtime.CompilerServices.Unsafe).Assembly.Location); var immutable = dir.CopyFile(typeof(ImmutableArray).Assembly.Location); var analyzer = dir.CopyFile(typeof(DiagnosticAnalyzer).Assembly.Location); dir.CopyFile(typeof(RemoteAnalyzerFileReferenceTest).Assembly.Location); var analyzerCompilation = CSharp.CSharpCompilation.Create( "MyAnalyzer", new SyntaxTree[] { CSharp.SyntaxFactory.ParseSyntaxTree(analyzerSource) }, new MetadataReference[] { TestMetadata.NetStandard20.mscorlib, TestMetadata.NetStandard20.netstandard, TestMetadata.NetStandard20.SystemRuntime, MetadataReference.CreateFromFile(immutable.Path), MetadataReference.CreateFromFile(analyzer.Path) }, new CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel)); var analyzerFile = dir.CreateFile("MyAnalyzer.dll").WriteAllBytes(analyzerCompilation.EmitToArray()); var loadDomain = AppDomainUtils.Create("AnalyzerTestDomain", basePath: dir.Path); try { // Test analyzer load failure. var remoteTest = (RemoteAnalyzerFileReferenceTest)loadDomain.CreateInstanceAndUnwrap(typeof(RemoteAnalyzerFileReferenceTest).Assembly.FullName, typeof(RemoteAnalyzerFileReferenceTest).FullName); var exception = remoteTest.LoadAnalyzer(analyzerFile.Path); Assert.NotNull(exception as TypeLoadException); } finally { AppDomain.Unload(loadDomain); } } private static Assembly OnResolve(object sender, ResolveEventArgs e) { Console.WriteLine($"Resolve in {AppDomain.CurrentDomain.Id} for {e.Name}"); return null; } } } #endif
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Workspaces/Core/Portable/Options/SerializableOptionSet.WorkspaceOptionSet.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Options { internal sealed partial class SerializableOptionSet : OptionSet { /// <summary> /// An implementation of <see cref="OptionSet"/> for non-serializable options that are defined in VS layers. /// It fetches values it doesn't know about to the workspace's option service. It ensures a contract /// that values are immutable from this instance once observed. /// TODO: Remove this type once we move all the options from the VS layers into Workspaces/Features, so the entire /// option set is serializable and becomes pure data snapshot for options. /// </summary> private sealed class WorkspaceOptionSet : OptionSet { private ImmutableDictionary<OptionKey, object?> _values; internal WorkspaceOptionSet(IOptionService service) : this(service, ImmutableDictionary<OptionKey, object?>.Empty) { } public IOptionService OptionService { get; } private WorkspaceOptionSet(IOptionService service, ImmutableDictionary<OptionKey, object?> values) { OptionService = service; _values = values; } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowLocks = false)] private protected override object? GetOptionCore(OptionKey optionKey) { if (_values.TryGetValue(optionKey, out var value)) { return value; } value = OptionService.GetOption(optionKey); return ImmutableInterlocked.GetOrAdd(ref _values, optionKey, value); } public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value) { // make sure we first load this in current optionset this.GetOption(optionAndLanguage); return new WorkspaceOptionSet(OptionService, _values.SetItem(optionAndLanguage, value)); } /// <summary> /// Gets a list of all the options that were changed. /// </summary> internal IEnumerable<OptionKey> GetChangedOptions() { var optionSet = OptionService.GetOptions(); return GetChangedOptions(optionSet); } internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet? optionSet) { if (optionSet == this) { yield break; } foreach (var (key, value) in _values) { var currentValue = optionSet?.GetOption(key); if (!object.Equals(currentValue, value)) yield return key; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Options { internal sealed partial class SerializableOptionSet : OptionSet { /// <summary> /// An implementation of <see cref="OptionSet"/> for non-serializable options that are defined in VS layers. /// It fetches values it doesn't know about to the workspace's option service. It ensures a contract /// that values are immutable from this instance once observed. /// TODO: Remove this type once we move all the options from the VS layers into Workspaces/Features, so the entire /// option set is serializable and becomes pure data snapshot for options. /// </summary> private sealed class WorkspaceOptionSet : OptionSet { private ImmutableDictionary<OptionKey, object?> _values; internal WorkspaceOptionSet(IOptionService service) : this(service, ImmutableDictionary<OptionKey, object?>.Empty) { } public IOptionService OptionService { get; } private WorkspaceOptionSet(IOptionService service, ImmutableDictionary<OptionKey, object?> values) { OptionService = service; _values = values; } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowLocks = false)] private protected override object? GetOptionCore(OptionKey optionKey) { if (_values.TryGetValue(optionKey, out var value)) { return value; } value = OptionService.GetOption(optionKey); return ImmutableInterlocked.GetOrAdd(ref _values, optionKey, value); } public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value) { // make sure we first load this in current optionset this.GetOption(optionAndLanguage); return new WorkspaceOptionSet(OptionService, _values.SetItem(optionAndLanguage, value)); } /// <summary> /// Gets a list of all the options that were changed. /// </summary> internal IEnumerable<OptionKey> GetChangedOptions() { var optionSet = OptionService.GetOptions(); return GetChangedOptions(optionSet); } internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet? optionSet) { if (optionSet == this) { yield break; } foreach (var (key, value) in _values) { var currentValue = optionSet?.GetOption(key); if (!object.Equals(currentValue, value)) yield return key; } } } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./docs/compilers/Interactive Imports.md
# Imports in Scripts/Interactive ## Guiding principles Files includes by ```#load``` are each in a separate lexical scope. Declarations (including aliases) take precedence over usings (including using static) because they express intent. ## Process Steps (top to bottom) | Binding Using | Binding Code | #load ----------------------|---------------|--------------|------ Look for declarations in the current submission/file (including aliases) | Yes, excluding aliases | Yes, in submission | Yes, in file Look for declarations in preceding submissions (including aliases), in order | Yes | Yes | No Look for members in the host object (if any) | Yes | Yes | Yes Look for declarations in the global namespace | Yes | Yes | Yes Look in usings (except aliases) in the current submission/file and all preceding submissions (all at once, not looping) | No | Yes, in all submissions | Yes, in file only Look in the global imports of the current submission and all preceding submissions (all at once, not looping) | No | Yes | Yes
# Imports in Scripts/Interactive ## Guiding principles Files includes by ```#load``` are each in a separate lexical scope. Declarations (including aliases) take precedence over usings (including using static) because they express intent. ## Process Steps (top to bottom) | Binding Using | Binding Code | #load ----------------------|---------------|--------------|------ Look for declarations in the current submission/file (including aliases) | Yes, excluding aliases | Yes, in submission | Yes, in file Look for declarations in preceding submissions (including aliases), in order | Yes | Yes | No Look for members in the host object (if any) | Yes | Yes | Yes Look for declarations in the global namespace | Yes | Yes | Yes Look in usings (except aliases) in the current submission/file and all preceding submissions (all at once, not looping) | No | Yes, in all submissions | Yes, in file only Look in the global imports of the current submission and all preceding submissions (all at once, not looping) | No | Yes | Yes
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenDeconstructTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { [CompilerTrait(CompilerFeature.Tuples)] public class CodeGenDeconstructTests : CSharpTestBase { private static readonly MetadataReference[] s_valueTupleRefs = new[] { SystemRuntimeFacadeRef, ValueTupleRef }; const string commonSource = @"public class Pair<T1, T2> { T1 item1; T2 item2; public Pair(T1 item1, T2 item2) { this.item1 = item1; this.item2 = item2; } public void Deconstruct(out T1 item1, out T2 item2) { System.Console.WriteLine($""Deconstructing {ToString()}""); item1 = this.item1; item2 = this.item2; } public override string ToString() { return $""({item1.ToString()}, {item2.ToString()})""; } } public static class Pair { public static Pair<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Pair<T1, T2>(item1, item2); } } public class Integer { public int state; public override string ToString() { return state.ToString(); } public Integer(int i) { state = i; } public static implicit operator LongInteger(Integer i) { System.Console.WriteLine($""Converting {i}""); return new LongInteger(i.state); } } public class LongInteger { long state; public LongInteger(long l) { state = l; } public override string ToString() { return state.ToString(); } }"; [Fact] public void SimpleAssign() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(x, y)", lhs.ToString()); Assert.Equal("(System.Int64 x, System.String y)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int64 x, System.String y)", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); var right = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single(); Assert.Equal(@"new C()", right.ToString()); Assert.Equal("C", model.GetTypeInfo(right).Type.ToTestDisplayString()); Assert.Equal("C", model.GetTypeInfo(right).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(right).Kind); }; var comp = CompileAndVerifyWithMscorlib40(source, expectedOutput: "1 hello", references: s_valueTupleRefs, sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 43 (0x2b) .maxstack 3 .locals init (long V_0, //x string V_1, //y int V_2, string V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_2 IL_0007: ldloca.s V_3 IL_0009: callvirt ""void C.Deconstruct(out int, out string)"" IL_000e: ldloc.2 IL_000f: conv.i8 IL_0010: stloc.0 IL_0011: ldloc.3 IL_0012: stloc.1 IL_0013: ldloca.s V_0 IL_0015: call ""string long.ToString()"" IL_001a: ldstr "" "" IL_001f: ldloc.1 IL_0020: call ""string string.Concat(string, string, string)"" IL_0025: call ""void System.Console.WriteLine(string)"" IL_002a: ret }"); } [Fact] public void ObsoleteDeconstructMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); foreach (var (z1, z2) in new[] { new C() }) { } } [System.Obsolete] public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,18): warning CS0612: 'C.Deconstruct(out int, out string)' is obsolete // (x, y) = new C(); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "new C()").WithArguments("C.Deconstruct(out int, out string)").WithLocation(9, 18), // (10,34): warning CS0612: 'C.Deconstruct(out int, out string)' is obsolete // foreach (var (z1, z2) in new[] { new C() }) { } Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "new[] { new C() }").WithArguments("C.Deconstruct(out int, out string)").WithLocation(10, 34) ); } [Fact] [WorkItem(13632, "https://github.com/dotnet/roslyn/issues/13632")] public void SimpleAssignWithoutConversion() { string source = @" class C { static void Main() { int x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 42 (0x2a) .maxstack 3 .locals init (int V_0, //x string V_1, //y int V_2, string V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_2 IL_0007: ldloca.s V_3 IL_0009: callvirt ""void C.Deconstruct(out int, out string)"" IL_000e: ldloc.2 IL_000f: stloc.0 IL_0010: ldloc.3 IL_0011: stloc.1 IL_0012: ldloca.s V_0 IL_0014: call ""string int.ToString()"" IL_0019: ldstr "" "" IL_001e: ldloc.1 IL_001f: call ""string string.Concat(string, string, string)"" IL_0024: call ""void System.Console.WriteLine(string)"" IL_0029: ret }"); } [Fact] public void DeconstructMethodAmbiguous() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } public void Deconstruct(out int a) { a = 2; } }"; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var deconstruction = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression).AsNode(); Assert.Equal("(x, y) = new C()", deconstruction.ToString()); var deconstructionInfo = model.GetDeconstructionInfo(deconstruction); var firstDeconstructMethod = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C").GetMembers(WellKnownMemberNames.DeconstructMethodName) .OfType<SourceOrdinaryMethodSymbol>().Where(m => m.ParameterCount == 2).Single(); Assert.Equal(firstDeconstructMethod.GetPublicSymbol(), deconstructionInfo.Method); Assert.Equal("void C.Deconstruct(out System.Int32 a, out System.String b)", deconstructionInfo.Method.ToTestDisplayString()); Assert.Null(deconstructionInfo.Conversion); var nested = deconstructionInfo.Nested; Assert.Equal(2, nested.Length); Assert.Null(nested[0].Method); Assert.Equal(ConversionKind.ImplicitNumeric, nested[0].Conversion.Value.Kind); Assert.Empty(nested[0].Nested); Assert.Null(nested[1].Method); Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind); Assert.Empty(nested[1].Nested); var assignment = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression, occurrence: 2).AsNode(); Assert.Equal("a = 1", assignment.ToString()); var defaultInfo = model.GetDeconstructionInfo(assignment); Assert.Null(defaultInfo.Method); Assert.Empty(defaultInfo.Nested); Assert.Equal(ConversionKind.UnsetConversionKind, defaultInfo.Conversion.Value.Kind); } [Fact] [WorkItem(27520, "https://github.com/dotnet/roslyn/issues/27520")] public void GetDeconstructionInfoOnIncompleteCode() { string source = @" class C { static void M(string s) { foreach (char in s) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS1525: Invalid expression term 'char' // foreach (char in s) { } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "char").WithArguments("char").WithLocation(6, 18), // (6,23): error CS0230: Type and identifier are both required in a foreach statement // foreach (char in s) { } Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 23) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var foreachDeconstruction = (ForEachVariableStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.ForEachVariableStatement).AsNode(); Assert.Equal(@"foreach (char in s) { }", foreachDeconstruction.ToString()); var deconstructionInfo = model.GetDeconstructionInfo(foreachDeconstruction); Assert.Equal(Conversion.UnsetConversion, deconstructionInfo.Conversion); Assert.Null(deconstructionInfo.Method); Assert.Empty(deconstructionInfo.Nested); } [Fact] [WorkItem(15634, "https://github.com/dotnet/roslyn/issues/15634")] public void DeconstructMustReturnVoid() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); } public int Deconstruct(out int a, out string b) { a = 1; b = ""hello""; return 42; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS8129: No Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type. // (x, y) = new C(); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 18) ); } [Fact] public void VerifyExecutionOrder_Deconstruct() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; } static void Main() { C c = new C(); (c.getHolderForX().x, c.getHolderForY().y) = c.getDeconstructReceiver(); } public void Deconstruct(out D1 x, out D2 y) { x = new D1(); y = new D2(); Console.WriteLine(""Deconstruct""); } } class D1 { public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } "; string expected = @"getHolderforX getHolderforY getDeconstructReceiver Deconstruct Conversion1 Conversion2 setX setY "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_Deconstruct_Conditional() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; } static void Main() { C c = new C(); bool b = true; (c.getHolderForX().x, c.getHolderForY().y) = b ? c.getDeconstructReceiver() : default; } public void Deconstruct(out D1 x, out D2 y) { x = new D1(); y = new D2(); Console.WriteLine(""Deconstruct""); } } class D1 { public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } "; string expected = @"getHolderforX getHolderforY getDeconstructReceiver Deconstruct Conversion1 Conversion2 setX setY "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_TupleLiteral() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } static void Main() { C c = new C(); (c.getHolderForX().x, c.getHolderForY().y) = (new D1(), new D2()); } } class D1 { public D1() { Console.WriteLine(""Constructor1""); } public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public D2() { Console.WriteLine(""Constructor2""); } public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } "; string expected = @"getHolderforX getHolderforY Constructor1 Conversion1 Constructor2 Conversion2 setX setY "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_TupleLiteral_Conditional() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } static void Main() { C c = new C(); bool b = true; (c.getHolderForX().x, c.getHolderForY().y) = b ? (new D1(), new D2()) : default; } } class D1 { public D1() { Console.WriteLine(""Constructor1""); } public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public D2() { Console.WriteLine(""Constructor2""); } public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } "; string expected = @"getHolderforX getHolderforY Constructor1 Constructor2 Conversion1 Conversion2 setX setY "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_TupleLiteralAndDeconstruction() { string source = @" using System; class C { int w { set { Console.WriteLine($""setW""); } } int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } int z { set { Console.WriteLine($""setZ""); } } C getHolderForW() { Console.WriteLine(""getHolderforW""); return this; } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; } static void Main() { C c = new C(); (c.getHolderForW().w, (c.getHolderForY().y, c.getHolderForZ().z), c.getHolderForX().x) = (new D1(), new D2(), new D3()); } } class D1 { public D1() { Console.WriteLine(""Constructor1""); } public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public D2() { Console.WriteLine(""Constructor2""); } public void Deconstruct(out int x, out int y) { x = 2; y = 3; Console.WriteLine(""deconstruct""); } } class D3 { public D3() { Console.WriteLine(""Constructor3""); } public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; } } "; string expected = @"getHolderforW getHolderforY getHolderforZ getHolderforX Constructor1 Conversion1 Constructor2 Constructor3 Conversion3 deconstruct setW setY setZ setX "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_TupleLiteralAndDeconstruction_Conditional() { string source = @" using System; class C { int w { set { Console.WriteLine($""setW""); } } int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } int z { set { Console.WriteLine($""setZ""); } } C getHolderForW() { Console.WriteLine(""getHolderforW""); return this; } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; } static void Main() { C c = new C(); bool b = false; (c.getHolderForW().w, (c.getHolderForY().y, c.getHolderForZ().z), c.getHolderForX().x) = b ? default : (new D1(), new D2(), new D3()); } } class D1 { public D1() { Console.WriteLine(""Constructor1""); } public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public D2() { Console.WriteLine(""Constructor2""); } public void Deconstruct(out int x, out int y) { x = 2; y = 3; Console.WriteLine(""deconstruct""); } } class D3 { public D3() { Console.WriteLine(""Constructor3""); } public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; } } "; string expected = @"getHolderforW getHolderforY getHolderforZ getHolderforX Constructor1 Constructor2 Constructor3 deconstruct Conversion1 Conversion3 setW setY setZ setX "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void DifferentVariableKinds() { string source = @" class C { int[] ArrayIndexer = new int[1]; string property; string Property { set { property = value; } } string AutoProperty { get; set; } static void Main() { C c = new C(); (c.ArrayIndexer[0], c.Property, c.AutoProperty) = new C(); System.Console.WriteLine(c.ArrayIndexer[0] + "" "" + c.property + "" "" + c.AutoProperty); } public void Deconstruct(out int a, out string b, out string c) { a = 1; b = ""hello""; c = ""world""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello world"); comp.VerifyDiagnostics(); } [Fact] public void Dynamic() { string source = @" class C { dynamic Dynamic1; dynamic Dynamic2; static void Main() { C c = new C(); (c.Dynamic1, c.Dynamic2) = c; System.Console.WriteLine(c.Dynamic1 + "" "" + c.Dynamic2); } public void Deconstruct(out int a, out dynamic b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructInterfaceOnStruct() { string source = @" interface IDeconstructable { void Deconstruct(out int a, out string b); } struct C : IDeconstructable { string state; static void Main() { int x; string y; IDeconstructable c = new C() { state = ""initial"" }; System.Console.Write(c); (x, y) = c; System.Console.WriteLine("" "" + c + "" "" + x + "" "" + y); } void IDeconstructable.Deconstruct(out int a, out string b) { a = 1; b = ""hello""; state = ""modified""; } public override string ToString() { return state; } } "; var comp = CompileAndVerify(source, expectedOutput: "initial modified 1 hello", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructMethodHasParams2() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b, params int[] c) // not a Deconstruct operator { a = 1; b = ""ignored""; } public void Deconstruct(out int a, out string b) { a = 2; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "2 hello"); comp.VerifyDiagnostics(); } [Fact] public void OutParamsDisallowed() { string source = @" class C { public void Deconstruct(out int a, out string b, out params int[] c) { a = 1; b = ""ignored""; c = new[] { 2, 2 }; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,58): error CS8328: The parameter modifier 'params' cannot be used with 'out' // public void Deconstruct(out int a, out string b, out params int[] c) Diagnostic(ErrorCode.ERR_BadParameterModifiers, "params").WithArguments("params", "out").WithLocation(4, 58)); } [Fact] public void DeconstructMethodHasArglist2() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } public void Deconstruct(out int a, out string b, __arglist) // not a Deconstruct operator { a = 2; b = ""ignored""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DifferentStaticVariableKinds() { string source = @" class C { static int[] ArrayIndexer = new int[1]; static string property; static string Property { set { property = value; } } static string AutoProperty { get; set; } static void Main() { (C.ArrayIndexer[0], C.Property, C.AutoProperty) = new C(); System.Console.WriteLine(C.ArrayIndexer[0] + "" "" + C.property + "" "" + C.AutoProperty); } public void Deconstruct(out int a, out string b, out string c) { a = 1; b = ""hello""; c = ""world""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello world"); comp.VerifyDiagnostics(); } [Fact] public void DifferentVariableRefKinds() { string source = @" class C { static void Main() { long a = 1; int b; C.M(ref a, out b); System.Console.WriteLine(a + "" "" + b); } static void M(ref long a, out int b) { (a, b) = new C(); } public void Deconstruct(out int x, out byte y) { x = 2; y = (byte)3; } } "; var comp = CompileAndVerify(source, expectedOutput: "2 3"); comp.VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.RefLocalsReturns)] public void RefReturningMethod() { string source = @" class C { static int i = 0; static void Main() { (M(), M()) = new C(); System.Console.WriteLine($""Final i is {i}""); } static ref int M() { System.Console.WriteLine($""M (previous i is {i})""); return ref i; } void Deconstruct(out int x, out int y) { System.Console.WriteLine(""Deconstruct""); x = 42; y = 43; } } "; var expected = @"M (previous i is 0) M (previous i is 0) Deconstruct Final i is 43 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact, CompilerTrait(CompilerFeature.RefLocalsReturns)] public void RefReturningProperty() { string source = @" class C { static int i = 0; static void Main() { (P, P) = new C(); System.Console.WriteLine($""Final i is {i}""); } static ref int P { get { System.Console.WriteLine($""P (previous i is {i})""); return ref i; } } void Deconstruct(out int x, out int y) { System.Console.WriteLine(""Deconstruct""); x = 42; y = 43; } } "; var expected = @"P (previous i is 0) P (previous i is 0) Deconstruct Final i is 43 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.RefLocalsReturns)] public void RefReturningMethodFlow() { string source = @" struct C { static C i; static C P { get { System.Console.WriteLine(""getP""); return i; } set { System.Console.WriteLine(""setP""); i = value; } } static void Main() { (M(), M()) = P; } static ref C M() { System.Console.WriteLine($""M (previous i is {i})""); return ref i; } void Deconstruct(out int x, out int y) { System.Console.WriteLine(""Deconstruct""); x = 42; y = 43; } public static implicit operator C(int x) { System.Console.WriteLine(""conversion""); return new C(); } } "; var expected = @"M (previous i is C) M (previous i is C) getP Deconstruct conversion conversion"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void Indexers() { string source = @" class C { static SomeArray array; static void Main() { int y; (Goo()[Bar()], y) = new C(); System.Console.WriteLine($""Final array values[2] {array.values[2]}""); } static SomeArray Goo() { System.Console.WriteLine($""Goo""); array = new SomeArray(); return array; } static int Bar() { System.Console.WriteLine($""Bar""); return 2; } void Deconstruct(out int x, out int y) { System.Console.WriteLine(""Deconstruct""); x = 101; y = 102; } } class SomeArray { public int[] values; public SomeArray() { values = new [] { 42, 43, 44 }; } public int this[int index] { get { System.Console.WriteLine($""indexGet (with value {values[index]})""); return values[index]; } set { System.Console.WriteLine($""indexSet (with value {value})""); values[index] = value; } } } "; var expected = @"Goo Bar Deconstruct indexSet (with value 101) Final array values[2] 101 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void AssigningTuple() { string source = @" class C { static void Main() { long x; string y; int i = 1; (x, y) = (i, ""hello""); System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var deconstruction = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Single(); var deconstructionInfo = model.GetDeconstructionInfo(deconstruction); Assert.Null(deconstructionInfo.Method); Assert.Null(deconstructionInfo.Conversion); var nested = deconstructionInfo.Nested; Assert.Equal(2, nested.Length); Assert.Null(nested[0].Method); Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind); Assert.Empty(nested[0].Nested); Assert.Null(nested[1].Method); Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind); Assert.Empty(nested[1].Nested); var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(i, ""hello"")", tuple.ToString()); var tupleConversion = model.GetConversion(tuple); Assert.Equal(ConversionKind.ImplicitTupleLiteral, tupleConversion.Kind); Assert.Equal(ConversionKind.ImplicitNumeric, tupleConversion.UnderlyingConversions[0].Kind); } [Fact] public void AssigningTupleWithConversion() { string source = @" class C { static void Main() { long x; string y; (x, y) = M(); System.Console.WriteLine(x + "" "" + y); } static System.ValueTuple<int, string> M() { return (1, ""hello""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact] public void AssigningLongTuple() { string source = @" class C { static void Main() { long x; int y; (x, x, x, x, x, x, x, x, x, y) = (1, 1, 1, 1, 1, 1, 1, 1, 4, 2); System.Console.WriteLine(string.Concat(x, "" "", y)); } } "; var comp = CompileAndVerify(source, expectedOutput: "4 2"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0) //y IL_0000: ldc.i4.4 IL_0001: conv.i8 IL_0002: ldc.i4.2 IL_0003: stloc.0 IL_0004: box ""long"" IL_0009: ldstr "" "" IL_000e: ldloc.0 IL_000f: box ""int"" IL_0014: call ""string string.Concat(object, object, object)"" IL_0019: call ""void System.Console.WriteLine(string)"" IL_001e: ret }"); } [Fact] public void AssigningLongTupleWithNames() { string source = @" class C { static void Main() { long x; int y; (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "9 10"); comp.VerifyDiagnostics( // (9,43): warning CS8123: The tuple element name 'a' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "a: 1").WithArguments("a", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 43), // (9,49): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 49), // (9,55): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 55), // (9,61): warning CS8123: The tuple element name 'd' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "d: 4").WithArguments("d", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 61), // (9,67): warning CS8123: The tuple element name 'e' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "e: 5").WithArguments("e", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 67), // (9,73): warning CS8123: The tuple element name 'f' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "f: 6").WithArguments("f", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 73), // (9,79): warning CS8123: The tuple element name 'g' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "g: 7").WithArguments("g", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 79), // (9,85): warning CS8123: The tuple element name 'h' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "h: 8").WithArguments("h", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 85), // (9,91): warning CS8123: The tuple element name 'i' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "i: 9").WithArguments("i", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 91), // (9,97): warning CS8123: The tuple element name 'j' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "j: 10").WithArguments("j", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 97) ); } [Fact] public void AssigningLongTuple2() { string source = @" class C { static void Main() { long x; int y; (x, x, x, x, x, x, x, x, x, y) = (1, 1, 1, 1, 1, 1, 1, 1, 4, (byte)2); System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "4 2"); comp.VerifyDiagnostics(); } [Fact] public void AssigningTypelessTuple() { string source = @" class C { static void Main() { string x = ""goodbye""; string y; (x, y) = (null, ""hello""); System.Console.WriteLine($""{x}{y}""); } } "; var comp = CompileAndVerify(source, expectedOutput: "hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 19 (0x13) .maxstack 2 .locals init (string V_0) //y IL_0000: ldnull IL_0001: ldstr ""hello"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""string string.Concat(string, string)"" IL_000d: call ""void System.Console.WriteLine(string)"" IL_0012: ret } "); } [Fact] public void ValueTupleReturnIsNotEmittedIfUnused() { string source = @" class C { public static void Main() { int x, y; (x, y) = new C(); } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 15 (0xf) .maxstack 3 .locals init (int V_0, int V_1) IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_0 IL_0007: ldloca.s V_1 IL_0009: callvirt ""void C.Deconstruct(out int, out int)"" IL_000e: ret }"); } [Fact] public void ValueTupleReturnIsEmittedIfUsed() { string source = @" class C { public static void Main() { int x, y; var z = ((x, y) = new C()); z.ToString(); } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().ElementAt(2); Assert.Equal("(System.Int32 x, System.Int32 y) z", model.GetDeclaredSymbol(x).ToTestDisplayString()); }; var comp = CompileAndVerify(source, sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 37 (0x25) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0, //z int V_1, int V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_1 IL_0007: ldloca.s V_2 IL_0009: callvirt ""void C.Deconstruct(out int, out int)"" IL_000e: ldloc.1 IL_000f: ldloc.2 IL_0010: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0015: stloc.0 IL_0016: ldloca.s V_0 IL_0018: constrained. ""System.ValueTuple<int, int>"" IL_001e: callvirt ""string object.ToString()"" IL_0023: pop IL_0024: ret }"); } [Fact] public void ValueTupleReturnIsEmittedIfUsed_WithCSharp7_1() { string source = @" class C { public static void Main() { int x, y; var z = ((x, y) = new C()); z.ToString(); } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().ElementAt(2); Assert.Equal("(System.Int32 x, System.Int32 y) z", model.GetDeclaredSymbol(x).ToTestDisplayString()); }; var comp = CompileAndVerify(source, sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics(); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleNotRequiredIfReturnIsNotUsed() { string source = @" class C { public static void Main() { int x, y; (x, y) = new C(); System.Console.Write($""assignment: {x} {y}. ""); foreach (var (a, b) in new[] { new C() }) { System.Console.Write($""foreach: {a} {b}.""); } } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "assignment: 1 2. foreach: 1 2."); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var xy = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal("(x, y)", xy.ToString()); var tuple1 = model.GetTypeInfo(xy).Type; Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tuple1.ToTestDisplayString()); var ab = nodes.OfType<DeclarationExpressionSyntax>().Single(); var tuple2 = model.GetTypeInfo(ab).Type; Assert.Equal("(System.Int32 a, System.Int32 b)[missing]", tuple2.ToTestDisplayString()); Assert.Equal("(System.Int32 a, System.Int32 b)[missing]", model.GetTypeInfo(ab).ConvertedType.ToTestDisplayString()); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleNotRequiredIfReturnIsNotUsed2() { string source = @" class C { public static void Main() { int x, y; for((x, y) = new C(1); ; (x, y) = new C(2)) { } } public C(int c) { } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var tuple1 = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(x, y) = new C(1)", tuple1.Parent.ToString()); var tupleType1 = model.GetTypeInfo(tuple1).Type; Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tupleType1.ToTestDisplayString()); var tuple2 = nodes.OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(x, y) = new C(2)", tuple2.Parent.ToString()); var tupleType2 = model.GetTypeInfo(tuple1).Type; Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tupleType2.ToTestDisplayString()); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleNotRequiredIfReturnIsNotUsed3() { string source = @" class C { public static void Main() { int x, y; (x, y) = new C(); } public C() { } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } namespace System { [Obsolete] public struct ValueTuple<T1, T2> { [Obsolete] public T1 Item1; [Obsolete] public T2 Item2; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyEmitDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var tuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(x, y) = new C()", tuple.Parent.ToString()); var tupleType = model.GetTypeInfo(tuple).Type; Assert.Equal("(System.Int32 x, System.Int32 y)", tupleType.ToTestDisplayString()); var underlying = ((INamedTypeSymbol)tupleType).TupleUnderlyingType; Assert.Equal("(System.Int32, System.Int32)", underlying.ToTestDisplayString()); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleRequiredWhenRightHandSideIsTuple() { string source = @" class C { public static void Main() { int x, y; (x, y) = (1, 2); } } "; var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (7,18): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1, 2)").WithArguments("System.ValueTuple`2").WithLocation(7, 18) ); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleRequiredWhenRightHandSideIsTupleButNoReferenceEmitted() { string source = @" class C { public static void Main() { int x, y; (x, y) = (1, 2); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); Action<PEAssembly> assemblyValidator = assembly => { var reader = assembly.GetMetadataReader(); var names = reader.GetAssemblyRefNames().Select(name => reader.GetString(name)); Assert.Empty(names.Where(name => name.Contains("ValueTuple"))); }; CompileAndVerifyCommon(comp, assemblyValidator: assemblyValidator); } [Fact] public void ValueTupleReturnMissingMemberWithCSharp7() { string source = @" class C { public void M() { int x, y; var nested = ((x, y) = (1, 2)); System.Console.Write(nested.x); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyDiagnostics( // (8,37): error CS8305: Tuple element name 'x' is inferred. Please use language version 7.1 or greater to access an element by its inferred name. // System.Console.Write(nested.x); Diagnostic(ErrorCode.ERR_TupleInferredNamesNotAvailable, "x").WithArguments("x", "7.1").WithLocation(8, 37) ); } [Fact] public void ValueTupleReturnWithInferredNamesWithCSharp7_1() { string source = @" class C { public void M() { int x, y, Item1, Rest; var a = ((x, y) = (1, 2)); var b = ((x, x) = (1, 2)); var c = ((_, x) = (1, 2)); var d = ((Item1, Rest) = (1, 2)); var nested = ((x, Item1, y, (_, x, x), (x, y)) = (1, 2, 3, (4, 5, 6), (7, 8))); (int, int) f = ((x, y) = (1, 2)); } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var declarations = nodes.OfType<VariableDeclaratorSyntax>(); Assert.Equal("(System.Int32 x, System.Int32 y) a", model.GetDeclaredSymbol(declarations.ElementAt(4)).ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32) b", model.GetDeclaredSymbol(declarations.ElementAt(5)).ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32 x) c", model.GetDeclaredSymbol(declarations.ElementAt(6)).ToTestDisplayString()); var x = (ILocalSymbol)model.GetDeclaredSymbol(declarations.ElementAt(7)); Assert.Equal("(System.Int32, System.Int32) d", x.ToTestDisplayString()); Assert.True(x.Type.GetSymbol().TupleElementNames.IsDefault); Assert.Equal("(System.Int32 x, System.Int32, System.Int32 y, (System.Int32, System.Int32, System.Int32), (System.Int32 x, System.Int32 y)) nested", model.GetDeclaredSymbol(declarations.ElementAt(8)).ToTestDisplayString()); }; var comp = CompileAndVerify(source, sourceSymbolValidator: validator, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyDiagnostics(); } [Fact] public void DeconstructionDeclarationCanOnlyBeParsedAsStatement() { string source = @" class C { public static void Main() { var z = ((var x, int y) = new C()); } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,19): error CS8185: A declaration is not allowed in this context. // var z = ((var x, int y) = new C()); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x").WithLocation(6, 19) ); } [ConditionalFact(typeof(DesktopOnly))] public void Constraints_01() { string source = @" using System; class C { public void M() { (int x, var (err1, y)) = (0, new C()); // ok, no return value used (ArgIterator err2, var err3) = M2(); // ok, no return value foreach ((ArgIterator err4, var err5) in new[] { M2() }) // ok, no return value { } } public static (ArgIterator, ArgIterator) M2() { return (default(ArgIterator), default(ArgIterator)); } public void Deconstruct(out ArgIterator a, out int b) { a = default(ArgIterator); b = 2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (19,29): error CS1601: Cannot make reference to variable of type 'ArgIterator' // public void Deconstruct(out ArgIterator a, out int b) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out ArgIterator a").WithArguments("System.ArgIterator").WithLocation(19, 29), // (14,46): error CS0306: The type 'ArgIterator' may not be used as a type argument // public static (ArgIterator, ArgIterator) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("System.ArgIterator").WithLocation(14, 46), // (14,46): error CS0306: The type 'ArgIterator' may not be used as a type argument // public static (ArgIterator, ArgIterator) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("System.ArgIterator").WithLocation(14, 46), // (16,17): error CS0306: The type 'ArgIterator' may not be used as a type argument // return (default(ArgIterator), default(ArgIterator)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(ArgIterator)").WithArguments("System.ArgIterator").WithLocation(16, 17), // (16,39): error CS0306: The type 'ArgIterator' may not be used as a type argument // return (default(ArgIterator), default(ArgIterator)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(ArgIterator)").WithArguments("System.ArgIterator").WithLocation(16, 39) ); } [Fact] public void Constraints_02() { string source = @" unsafe class C { public void M() { (int x, var (err1, y)) = (0, new C()); // ok, no return value (var err2, var err3) = M2(); // ok, no return value foreach ((var err4, var err5) in new[] { M2() }) // ok, no return value { } } public static (int*, int*) M2() { return (default(int*), default(int*)); } public void Deconstruct(out int* a, out int b) { a = default(int*); b = 2; } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (13,32): error CS0306: The type 'int*' may not be used as a type argument // public static (int*, int*) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(13, 32), // (13,32): error CS0306: The type 'int*' may not be used as a type argument // public static (int*, int*) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(13, 32), // (15,17): error CS0306: The type 'int*' may not be used as a type argument // return (default(int*), default(int*)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(int*)").WithArguments("int*").WithLocation(15, 17), // (15,32): error CS0306: The type 'int*' may not be used as a type argument // return (default(int*), default(int*)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(int*)").WithArguments("int*").WithLocation(15, 32) ); } [Fact] public void Constraints_03() { string source = @" unsafe class C { public void M() { int ok; int* err1, err2; var t = ((ok, (err1, ok)) = (0, new C())); var t2 = ((err1, err2) = M2()); } public static (int*, int*) M2() { throw null; } public void Deconstruct(out int* a, out int b) { a = default(int*); b = 2; } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (12,32): error CS0306: The type 'int*' may not be used as a type argument // public static (int*, int*) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(12, 32), // (12,32): error CS0306: The type 'int*' may not be used as a type argument // public static (int*, int*) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(12, 32), // (8,24): error CS0306: The type 'int*' may not be used as a type argument // var t = ((ok, (err1, ok)) = (0, new C())); Diagnostic(ErrorCode.ERR_BadTypeArgument, "err1").WithArguments("int*").WithLocation(8, 24), // (9,20): error CS0306: The type 'int*' may not be used as a type argument // var t2 = ((err1, err2) = M2()); Diagnostic(ErrorCode.ERR_BadTypeArgument, "err1").WithArguments("int*").WithLocation(9, 20), // (9,26): error CS0306: The type 'int*' may not be used as a type argument // var t2 = ((err1, err2) = M2()); Diagnostic(ErrorCode.ERR_BadTypeArgument, "err2").WithArguments("int*").WithLocation(9, 26) ); } [Fact] public void DeconstructionWithTupleNamesCannotBeParsed() { string source = @" class C { public static void Main() { (Alice: var x, Bob: int y) = (1, 2); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,10): error CS8187: Tuple element names are not permitted on the left of a deconstruction. // (Alice: var x, Bob: int y) = (1, 2); Diagnostic(ErrorCode.ERR_TupleElementNamesInDeconstruction, "Alice:").WithLocation(6, 10), // (6,24): error CS8187: Tuple element names are not permitted on the left of a deconstruction. // (Alice: var x, Bob: int y) = (1, 2); Diagnostic(ErrorCode.ERR_TupleElementNamesInDeconstruction, "Bob:").WithLocation(6, 24) ); } [Fact] public void ValueTupleReturnIsEmittedIfUsedInLambda() { string source = @" class C { static void F(System.Action a) { } static void F<T>(System.Func<T> f) { System.Console.Write(f().ToString()); } static void Main() { int x, y; F(() => (x, y) = (1, 2)); } } "; var comp = CompileAndVerify(source, expectedOutput: "(1, 2)"); comp.VerifyDiagnostics(); } [Fact] public void AssigningIntoProperties() { string source = @" class C { static int field; static long x { set { System.Console.WriteLine($""setX {value}""); } } static string y { get; set; } static ref int z { get { return ref field; } } static void Main() { (x, y, z) = new C(); System.Console.WriteLine(y); System.Console.WriteLine($""field: {field}""); } public void Deconstruct(out int a, out string b, out int c) { a = 1; b = ""hello""; c = 2; } } "; string expected = @"setX 1 hello field: 2 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void AssigningTupleIntoProperties() { string source = @" class C { static int field; static long x { set { System.Console.WriteLine($""setX {value}""); } } static string y { get; set; } static ref int z { get { return ref field; } } static void Main() { (x, y, z) = (1, ""hello"", 2); System.Console.WriteLine(y); System.Console.WriteLine($""field: {field}""); } } "; string expected = @"setX 1 hello field: 2 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] [WorkItem(18554, "https://github.com/dotnet/roslyn/issues/18554")] public void AssigningIntoIndexers() { string source = @" using System; class C { int field; ref int this[int x, int y, int z, int opt = 1] { get { Console.WriteLine($""this.get""); return ref field; } } int this[int x, long y, int z, int opt = 1] { set { Console.WriteLine($""this.set({value})""); } } int M(int i) { Console.WriteLine($""M({i})""); return 0; } void Test() { (this[z: M(1), x: M(2), y: 10], this[z: M(3), x: M(4), y: 10L]) = this; Console.WriteLine($""field: {field}""); } static void Main() { new C().Test(); } void Deconstruct(out int a, out int b) { Console.WriteLine(nameof(Deconstruct)); a = 1; b = 2; } } "; var expectedOutput = @"M(1) M(2) this.get M(3) M(4) Deconstruct this.set(2) field: 1 "; var comp = CompileAndVerify(source, expectedOutput: expectedOutput); comp.VerifyDiagnostics(); } [Fact] [WorkItem(18554, "https://github.com/dotnet/roslyn/issues/18554")] public void AssigningTupleIntoIndexers() { string source = @" using System; class C { int field; ref int this[int x, int y, int z, int opt = 1] { get { Console.WriteLine($""this.get""); return ref field; } } int this[int x, long y, int z, int opt = 1] { set { Console.WriteLine($""this.set({value})""); } } int M(int i) { Console.WriteLine($""M({i})""); return 0; } void Test() { (this[z: M(1), x: M(2), y: 10], this[z: M(3), x: M(4), y: 10L]) = (1, 2); Console.WriteLine($""field: {field}""); } static void Main() { new C().Test(); } } "; var expectedOutput = @"M(1) M(2) this.get M(3) M(4) this.set(2) field: 1 "; var comp = CompileAndVerify(source, expectedOutput: expectedOutput); comp.VerifyDiagnostics(); } [Fact] public void AssigningIntoIndexerWithOptionalValueParameter() { var ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) .method public hidebysig specialname instance void set_Item ( int32 i, [opt] int32 'value' ) cil managed { .param [2] = int32(1) .maxstack 8 IL_0000: ldstr ""this.set({0})"" IL_0005: ldarg.2 IL_0006: box[mscorlib]System.Int32 IL_000b: call string[mscorlib] System.String::Format(string, object) IL_0010: call void [mscorlib]System.Console::WriteLine(string) IL_0015: ret } // end of method C::set_Item .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor .property instance int32 Item( int32 i ) { .set instance void C::set_Item(int32, int32) } } // end of class C "; var source = @" class Program { static void Main() { var c = new C(); (c[1], c[2]) = (1, 2); } } "; string expectedOutput = @"this.set(1) this.set(2) "; var comp = CreateCompilationWithILAndMscorlib40(source, ilSource, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void Swap() { string source = @" class C { static int x = 2; static int y = 4; static void Main() { Swap(); System.Console.WriteLine(x + "" "" + y); } static void Swap() { (x, y) = (y, x); } } "; var comp = CompileAndVerify(source, expectedOutput: "4 2"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Swap", @" { // Code size 23 (0x17) .maxstack 2 .locals init (int V_0) IL_0000: ldsfld ""int C.y"" IL_0005: ldsfld ""int C.x"" IL_000a: stloc.0 IL_000b: stsfld ""int C.x"" IL_0010: ldloc.0 IL_0011: stsfld ""int C.y"" IL_0016: ret } "); } [Fact] public void CircularFlow() { string source = @" class C { static void Main() { (object i, object ii) x = (1, 2); object y; (x.ii, y) = x; System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "(1, 1) 2"); comp.VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.RefLocalsReturns)] public void CircularFlow2() { string source = @" class C { static void Main() { (object i, object ii) x = (1,2); object y; ref var a = ref x; (a.ii, y) = x; System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "(1, 1) 2", parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); } [Fact] public void DeconstructUsingBaseDeconstructMethod() { string source = @" class Base { public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } class C : Base { static void Main() { int x, y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int c) { c = 42; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2", parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); } [Fact] public void NestedDeconstructUsingSystemTupleExtensionMethod() { string source = @" using System; class C { static void Main() { int x; string y, z; (x, (y, z)) = Tuple.Create(1, Tuple.Create(""hello"", ""world"")); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello world", parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var deconstruction = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression).AsNode(); Assert.Equal(@"(x, (y, z)) = Tuple.Create(1, Tuple.Create(""hello"", ""world""))", deconstruction.ToString()); var deconstructionInfo = model.GetDeconstructionInfo(deconstruction); Assert.Equal("void System.TupleExtensions.Deconstruct<System.Int32, System.Tuple<System.String, System.String>>(" + "this System.Tuple<System.Int32, System.Tuple<System.String, System.String>> value, " + "out System.Int32 item1, out System.Tuple<System.String, System.String> item2)", deconstructionInfo.Method.ToTestDisplayString()); Assert.Null(deconstructionInfo.Conversion); var nested = deconstructionInfo.Nested; Assert.Equal(2, nested.Length); Assert.Null(nested[0].Method); Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind); Assert.Empty(nested[0].Nested); Assert.Equal("void System.TupleExtensions.Deconstruct<System.String, System.String>(" + "this System.Tuple<System.String, System.String> value, " + "out System.String item1, out System.String item2)", nested[1].Method.ToTestDisplayString()); Assert.Null(nested[1].Conversion); var nested2 = nested[1].Nested; Assert.Equal(2, nested.Length); Assert.Null(nested2[0].Method); Assert.Equal(ConversionKind.Identity, nested2[0].Conversion.Value.Kind); Assert.Empty(nested2[0].Nested); Assert.Null(nested2[1].Method); Assert.Equal(ConversionKind.Identity, nested2[1].Conversion.Value.Kind); Assert.Empty(nested2[1].Nested); } [Fact] public void DeconstructUsingValueTupleExtensionMethod() { string source = @" class C { static void Main() { int x; string y, z; (x, y, z) = (1, 2); } } public static class Extensions { public static void Deconstruct(this (int, int) self, out int x, out string y, out string z) { throw null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,25): error CS0029: Cannot implicitly convert type 'int' to 'string' // (x, y, z) = (1, 2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "2").WithArguments("int", "string").WithLocation(8, 25), // (8,9): error CS8132: Cannot deconstruct a tuple of '2' elements into '3' variables. // (x, y, z) = (1, 2); Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, "(x, y, z) = (1, 2)").WithArguments("2", "3").WithLocation(8, 9) ); } [Fact] public void OverrideDeconstruct() { string source = @" class Base { public virtual void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } class C : Base { static void Main() { int x; string y; (x, y) = new C(); } public override void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; System.Console.WriteLine(""override""); } } "; var comp = CompileAndVerify(source, expectedOutput: "override", parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); } [Fact] public void DeconstructRefTuple() { string template = @" using System; class C { static void Main() { int VARIABLES; // int x1, x2, ... (VARIABLES) = (TUPLE).ToTuple(); // (x1, x2, ...) = (1, 2, ...).ToTuple(); System.Console.WriteLine(OUTPUT); } } "; for (int i = 2; i <= 21; i++) { var tuple = String.Join(", ", Enumerable.Range(1, i).Select(n => n.ToString())); var variables = String.Join(", ", Enumerable.Range(1, i).Select(n => $"x{n}")); var output = String.Join(@" + "" "" + ", Enumerable.Range(1, i).Select(n => $"x{n}")); var expected = String.Join(" ", Enumerable.Range(1, i).Select(n => n)); var source = template.Replace("VARIABLES", variables).Replace("TUPLE", tuple).Replace("OUTPUT", output); var comp = CompileAndVerify(source, expectedOutput: expected, parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); } } [Fact] public void DeconstructExtensionMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } } static class D { public static void Deconstruct(this C value, out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact] public void DeconstructRefExtensionMethod() { // https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-01-24.md string source = @" struct C { static void Main() { long x; string y; var c = new C(); (x, y) = c; System.Console.WriteLine(x + "" "" + y); } } static class D { public static void Deconstruct(this ref C value, out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source).VerifyDiagnostics( // (10,9): error CS1510: A ref or out value must be an assignable variable // (x, y) = c; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x, y) = c").WithLocation(10, 9) ); } [Fact] public void DeconstructInExtensionMethod() { string source = @" struct C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } } static class D { public static void Deconstruct(this in C value, out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact] public void UnderspecifiedDeconstructGenericExtensionMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); } } static class Extension { public static void Deconstruct<T>(this C value, out int a, out T b) { a = 2; b = default(T); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS0411: The type arguments for method 'Extension.Deconstruct<T>(C, out int, out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // (x, y) = new C(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new C()").WithArguments("Extension.Deconstruct<T>(C, out int, out T)").WithLocation(8, 18), // (8,18): error CS8129: No Deconstruct instance or extension method was found for type 'C', with 2 out parameters. // (x, y) = new C(); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 18) ); } [Fact] public void UnspecifiedGenericMethodIsNotCandidate() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); } } static class Extension { public static void Deconstruct<T>(this C value, out int a, out T b) { a = 2; b = default(T); } public static void Deconstruct(this C value, out int a, out string b) { a = 2; b = ""hello""; System.Console.Write(""Deconstructed""); } }"; var comp = CompileAndVerify(source, expectedOutput: "Deconstructed"); comp.VerifyDiagnostics(); } [Fact] public void DeconstructGenericExtensionMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C1<string>(); } } public class C1<T> { } static class Extension { public static void Deconstruct<T>(this C1<T> value, out int a, out T b) { a = 2; b = default(T); System.Console.WriteLine(""Deconstructed""); } } "; var comp = CompileAndVerify(source, expectedOutput: "Deconstructed"); comp.VerifyDiagnostics(); } [Fact] public void DeconstructGenericMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C1(); } } class C1 { public void Deconstruct<T>(out int a, out T b) { a = 2; b = default(T); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,18): error CS0411: The type arguments for method 'C1.Deconstruct<T>(out int, out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // (x, y) = new C1(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new C1()").WithArguments("C1.Deconstruct<T>(out int, out T)").WithLocation(9, 18), // (9,18): error CS8129: No Deconstruct instance or extension method was found for type 'C1', with 2 out parameters and a void return type. // (x, y) = new C1(); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C1()").WithArguments("C1", "2").WithLocation(9, 18) ); } [Fact] public void AmbiguousDeconstructGenericMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C1(); System.Console.Write($""{x} {y}""); } } class C1 { public void Deconstruct<T>(out int a, out T b) { a = 2; b = default(T); } public void Deconstruct(out int a, out string b) { a = 2; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "2 hello"); comp.VerifyDiagnostics(); } [Fact] public void NestedTupleAssignment() { string source = @" class C { static void Main() { long x; string y, z; (x, (y, z)) = ((int)1, (""a"", ""b"")); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(x, (y, z))", lhs.ToString()); Assert.Equal("(System.Int64 x, (System.String y, System.String z))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int64 x, (System.String y, System.String z))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: "1 a b", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void NestedTypelessTupleAssignment() { string source = @" class C { static void Main() { string x, y, z; (x, (y, z)) = (null, (null, null)); System.Console.WriteLine(""nothing"" + x + y + z); } } "; var comp = CompileAndVerify(source, expectedOutput: "nothing"); comp.VerifyDiagnostics(); } [Fact] public void NestedDeconstructAssignment() { string source = @" class C { static void Main() { int x; string y, z; (x, (y, z)) = new D1(); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } class D1 { public void Deconstruct(out int item1, out D2 item2) { item1 = 1; item2 = new D2(); } } class D2 { public void Deconstruct(out string item1, out string item2) { item1 = ""a""; item2 = ""b""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 a b"); comp.VerifyDiagnostics(); } [Fact] public void NestedMixedAssignment1() { string source = @" class C { static void Main() { int x, y, z; (x, (y, z)) = (1, new D1()); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } class D1 { public void Deconstruct(out int item1, out int item2) { item1 = 2; item2 = 3; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 3"); comp.VerifyDiagnostics(); } [Fact] public void NestedMixedAssignment2() { string source = @" class C { static void Main() { int x; string y, z; (x, (y, z)) = new D1(); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } class D1 { public void Deconstruct(out int item1, out (string, string) item2) { item1 = 1; item2 = (""a"", ""b""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 a b"); comp.VerifyDiagnostics(); } [Fact] public void VerifyNestedExecutionOrder() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } int z { set { Console.WriteLine($""setZ""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; } C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; } static void Main() { C c = new C(); (c.getHolderForX().x, (c.getHolderForY().y, c.getHolderForZ().z)) = c.getDeconstructReceiver(); } public void Deconstruct(out D1 x, out C1 t) { x = new D1(); t = new C1(); Console.WriteLine(""Deconstruct1""); } } class C1 { public void Deconstruct(out D2 y, out D3 z) { y = new D2(); z = new D3(); Console.WriteLine(""Deconstruct2""); } } class D1 { public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } class D3 { public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; } } "; string expected = @"getHolderforX getHolderforY getHolderforZ getDeconstructReceiver Deconstruct1 Deconstruct2 Conversion1 Conversion2 Conversion3 setX setY setZ "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyNestedExecutionOrder_Conditional() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } int z { set { Console.WriteLine($""setZ""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; } C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; } static void Main() { C c = new C(); bool b = false; (c.getHolderForX().x, (c.getHolderForY().y, c.getHolderForZ().z)) = b ? default : c.getDeconstructReceiver(); } public void Deconstruct(out D1 x, out C1 t) { x = new D1(); t = new C1(); Console.WriteLine(""Deconstruct1""); } } class C1 { public void Deconstruct(out D2 y, out D3 z) { y = new D2(); z = new D3(); Console.WriteLine(""Deconstruct2""); } } class D1 { public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } class D3 { public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; } } "; string expected = @"getHolderforX getHolderforY getHolderforZ getDeconstructReceiver Deconstruct1 Deconstruct2 Conversion1 Conversion2 Conversion3 setX setY setZ "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyNestedExecutionOrder2() { string source = @" using System; class C { static LongInteger x1 { set { Console.WriteLine($""setX1 {value}""); } } static LongInteger x2 { set { Console.WriteLine($""setX2 {value}""); } } static LongInteger x3 { set { Console.WriteLine($""setX3 {value}""); } } static LongInteger x4 { set { Console.WriteLine($""setX4 {value}""); } } static LongInteger x5 { set { Console.WriteLine($""setX5 {value}""); } } static LongInteger x6 { set { Console.WriteLine($""setX6 {value}""); } } static LongInteger x7 { set { Console.WriteLine($""setX7 {value}""); } } static void Main() { ((x1, (x2, x3)), ((x4, x5), (x6, x7))) = Pair.Create(Pair.Create(new Integer(1), Pair.Create(new Integer(2), new Integer(3))), Pair.Create(Pair.Create(new Integer(4), new Integer(5)), Pair.Create(new Integer(6), new Integer(7)))); } } " + commonSource; string expected = @"Deconstructing ((1, (2, 3)), ((4, 5), (6, 7))) Deconstructing (1, (2, 3)) Deconstructing (2, 3) Deconstructing ((4, 5), (6, 7)) Deconstructing (4, 5) Deconstructing (6, 7) Converting 1 Converting 2 Converting 3 Converting 4 Converting 5 Converting 6 Converting 7 setX1 1 setX2 2 setX3 3 setX4 4 setX5 5 setX6 6 setX7 7"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void MixOfAssignments() { string source = @" class C { static void Main() { long x; string y; C a, b, c; c = new C(); (x, y) = a = b = c; System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/12400")] [WorkItem(12400, "https://github.com/dotnet/roslyn/issues/12400")] public void AssignWithPostfixOperator() { string source = @" class C { int state = 1; static void Main() { long x; string y; C c = new C(); (x, y) = c++; System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = state; b = ""hello""; } public static C operator ++(C c1) { return new C() { state = 2 }; } } "; // https://github.com/dotnet/roslyn/issues/12400 // we expect "2 hello" instead, which means the evaluation order is wrong var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(13631, "https://github.com/dotnet/roslyn/issues/13631")] public void DeconstructionDeclaration() { string source = @" class C { static void Main() { var (x1, x2) = (1, ""hello""); System.Console.WriteLine(x1 + "" "" + x2); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 32 (0x20) .maxstack 3 .locals init (int V_0, //x1 string V_1) //x2 IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldstr ""hello"" IL_0007: stloc.1 IL_0008: ldloca.s V_0 IL_000a: call ""string int.ToString()"" IL_000f: ldstr "" "" IL_0014: ldloc.1 IL_0015: call ""string string.Concat(string, string, string)"" IL_001a: call ""void System.Console.WriteLine(string)"" IL_001f: ret }"); } [Fact] public void NestedVarDeconstructionDeclaration() { string source = @" class C { static void Main() { var (x1, (x2, x3)) = (1, (2, ""hello"")); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().First(); Assert.Equal(@"var (x1, (x2, x3))", lhs.ToString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhs).Symbol); var lhsNested = tree.GetRoot().DescendantNodes().OfType<ParenthesizedVariableDesignationSyntax>().ElementAt(1); Assert.Equal(@"(x2, x3)", lhsNested.ToString()); Assert.Null(model.GetTypeInfo(lhsNested).Type); Assert.Null(model.GetSymbolInfo(lhsNested).Symbol); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void NestedVarDeconstructionDeclaration_WithCSharp7_1() { string source = @" class C { static void Main() { (int x1, var (x2, (x3, x4)), var x5) = (1, (2, (3, ""hello"")), 5); System.Console.WriteLine($""{x1} {x2} {x3} {x4} {x5}""); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(int x1, var (x2, (x3, x4)), var x5)", lhs.ToString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, (System.Int32 x3, System.String x4)), System.Int32 x5)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhs).Symbol); var x234 = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1); Assert.Equal(@"var (x2, (x3, x4))", x234.ToString()); Assert.Equal("(System.Int32 x2, (System.Int32 x3, System.String x4))", model.GetTypeInfo(x234).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x234).Symbol); var x34 = tree.GetRoot().DescendantNodes().OfType<ParenthesizedVariableDesignationSyntax>().ElementAt(1); Assert.Equal(@"(x3, x4)", x34.ToString()); Assert.Null(model.GetTypeInfo(x34).Type); Assert.Null(model.GetSymbolInfo(x34).Symbol); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); var x4 = GetDeconstructionVariable(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForDeconstructionLocal(model, x4, x4Ref); var x5 = GetDeconstructionVariable(tree, "x5"); var x5Ref = GetReference(tree, "x5"); VerifyModelForDeconstructionLocal(model, x5, x5Ref); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 hello 5", sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics(); } [Fact] public void NestedVarDeconstructionAssignment_WithCSharp7_1() { string source = @" class C { static void Main() { int x1, x2, x3; (x1, (x2, x3)) = (1, (2, 3)); System.Console.WriteLine($""{x1} {x2} {x3}""); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x123 = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(x1, (x2, x3))", x123.ToString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.Int32 x3))", model.GetTypeInfo(x123).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x123).Symbol); var x23 = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(x2, x3)", x23.ToString()); Assert.Equal("(System.Int32 x2, System.Int32 x3)", model.GetTypeInfo(x23).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x23).Symbol); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 3", sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics(); } [Fact] public void NestedVarDeconstructionDeclaration2() { string source = @" class C { static void Main() { (var x1, var (x2, x3)) = (1, (2, ""hello"")); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal("(var x1, var (x2, x3))", lhs.ToString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhs).Symbol); var lhsNested = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1); Assert.Equal("var (x2, x3)", lhsNested.ToString()); Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).ConvertedType.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhsNested).Symbol); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void NestedVarDeconstructionDeclarationWithCSharp7_1() { string source = @" class C { static void Main() { (var x1, byte _, var (x2, x3)) = (1, 2, (3, ""hello"")); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal("(var x1, byte _, var (x2, x3))", lhs.ToString()); Assert.Equal("(System.Int32 x1, System.Byte, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x1, System.Byte, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhs).Symbol); var lhsNested = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(2); Assert.Equal("var (x2, x3)", lhsNested.ToString()); Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhsNested).Symbol); }; var comp = CompileAndVerify(source, sourceSymbolValidator: validator, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyDiagnostics(); } [Fact] public void NestedDeconstructionDeclaration() { string source = @" class C { static void Main() { (int x1, (int x2, string x3)) = (1, (2, ""hello"")); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void VarMethodExists() { string source = @" class C { static void Main() { int x1 = 1; int x2 = 1; var (x1, x2); } static void var(int a, int b) { System.Console.WriteLine(""var""); } } "; var comp = CompileAndVerify(source, expectedOutput: "var"); comp.VerifyDiagnostics(); } [Fact] public void TypeMergingSuccess1() { string source = @" class C { static void Main() { (var (x1, x2), string x3) = ((1, 2), null); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; var comp = CompileAndVerify(source, expectedOutput: " 1 2"); comp.VerifyDiagnostics(); } [Fact] public void TypeMergingSuccess2() { string source = @" class C { static void Main() { (string x1, byte x2, var x3) = (null, 2, 3); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(string x1, byte x2, var x3)", lhs.ToString()); Assert.Equal("(System.String x1, System.Byte x2, System.Int32 x3)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); var literal = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(null, 2, 3)", literal.ToString()); Assert.Null(model.GetTypeInfo(literal).Type); Assert.Equal("(System.String, System.Byte, System.Int32)", model.GetTypeInfo(literal).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(literal).Kind); }; var comp = CompileAndVerify(source, expectedOutput: " 2 3", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void TypeMergingSuccess3() { string source = @" class C { static void Main() { (string x1, var x2) = (null, (1, 2)); System.Console.WriteLine(x1 + "" "" + x2); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(string x1, var x2)", lhs.ToString()); Assert.Equal("(System.String x1, (System.Int32, System.Int32) x2)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); var literal = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(null, (1, 2))", literal.ToString()); Assert.Null(model.GetTypeInfo(literal).Type); Assert.Equal("(System.String, (System.Int32, System.Int32))", model.GetTypeInfo(literal).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(literal).Kind); var nestedLiteral = literal.Arguments[1].Expression; Assert.Equal(@"(1, 2)", nestedLiteral.ToString()); Assert.Equal("(System.Int32, System.Int32)", model.GetTypeInfo(nestedLiteral).Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", model.GetTypeInfo(nestedLiteral).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(nestedLiteral).Kind); }; var comp = CompileAndVerify(source, expectedOutput: " (1, 2)", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void TypeMergingSuccess4() { string source = @" class C { static void Main() { ((string x1, byte x2, var x3), int x4) = (M(), 4); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4); } static (string, byte, int) M() { return (null, 2, 3); } } "; var comp = CompileAndVerify(source, expectedOutput: " 2 3 4"); comp.VerifyDiagnostics(); } [Fact] public void VarVarDeclaration() { string source = @" class C { static void Main() { (var (x1, x2), var x3) = Pair.Create(Pair.Create(1, ""hello""), 2); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } " + commonSource; string expected = @"Deconstructing ((1, hello), 2) Deconstructing (1, hello) 1 hello 2"; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); }; var comp = CompileAndVerify(source, expectedOutput: expected, parseOptions: TestOptions.Regular, sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } private static void VerifyModelForDeconstructionLocal(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForDeconstruction(model, decl, LocalDeclarationKind.DeconstructionVariable, references); } private static void VerifyModelForLocal(SemanticModel model, SingleVariableDesignationSyntax decl, LocalDeclarationKind kind, params IdentifierNameSyntax[] references) { VerifyModelForDeconstruction(model, decl, kind, references); } private static void VerifyModelForDeconstructionForeach(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForDeconstruction(model, decl, LocalDeclarationKind.ForEachIterationVariable, references); } private static void VerifyModelForDeconstruction(SemanticModel model, SingleVariableDesignationSyntax decl, LocalDeclarationKind kind, params IdentifierNameSyntax[] references) { var symbol = model.GetDeclaredSymbol(decl); Assert.Equal(decl.Identifier.ValueText, symbol.Name); Assert.Equal(kind, symbol.GetSymbol<LocalSymbol>().DeclarationKind); Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)decl)); Assert.Same(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier.ValueText).Single()); Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier.ValueText)); var local = symbol.GetSymbol<SourceLocalSymbol>(); var typeSyntax = GetTypeSyntax(decl); if (local.IsVar && local.Type.IsErrorType()) { Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol); } else { if (typeSyntax != null) { Assert.Equal(local.Type.GetPublicSymbol(), model.GetSymbolInfo(typeSyntax).Symbol); } } foreach (var reference in references) { Assert.Same(symbol, model.GetSymbolInfo(reference).Symbol); Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: decl.Identifier.ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier.ValueText)); Assert.Equal(local.Type.GetPublicSymbol(), model.GetTypeInfo(reference).Type); } } private static void VerifyModelForDeconstructionField(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references) { var field = (IFieldSymbol)model.GetDeclaredSymbol(decl); Assert.Equal(decl.Identifier.ValueText, field.Name); Assert.Equal(SymbolKind.Field, field.Kind); Assert.Same(field, model.GetDeclaredSymbol((SyntaxNode)decl)); Assert.Same(field, model.LookupSymbols(decl.SpanStart, name: decl.Identifier.ValueText).Single()); Assert.Equal(Accessibility.Private, field.DeclaredAccessibility); Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier.ValueText)); foreach (var reference in references) { Assert.Same(field, model.GetSymbolInfo(reference).Symbol); Assert.Same(field, model.LookupSymbols(reference.SpanStart, name: decl.Identifier.ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier.ValueText)); Assert.Equal(field.Type, model.GetTypeInfo(reference).Type); } } private static TypeSyntax GetTypeSyntax(SingleVariableDesignationSyntax decl) { return (decl.Parent as DeclarationExpressionSyntax)?.Type; } private static SingleVariableDesignationSyntax GetDeconstructionVariable(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == name).Single(); } private static IEnumerable<DiscardDesignationSyntax> GetDiscardDesignations(SyntaxTree tree) { return tree.GetRoot().DescendantNodes().OfType<DiscardDesignationSyntax>(); } private static IEnumerable<IdentifierNameSyntax> GetDiscardIdentifiers(SyntaxTree tree) { return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(i => i.Identifier.ContextualKind() == SyntaxKind.UnderscoreToken); } private static IdentifierNameSyntax GetReference(SyntaxTree tree, string name) { return GetReferences(tree, name).Single(); } private static IdentifierNameSyntax[] GetReferences(SyntaxTree tree, string name, int count) { var nameRef = GetReferences(tree, name).ToArray(); Assert.Equal(count, nameRef.Length); return nameRef; } private static IEnumerable<IdentifierNameSyntax> GetReferences(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == name); } [Fact] public void DeclarationWithActualVarType() { string source = @" class C { static void Main() { (var x1, int x2) = (new var(), 2); System.Console.WriteLine(x1 + "" "" + x2); } } class var { public override string ToString() { return ""var""; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("var", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); // extra checks on x2 var x2Type = GetTypeSyntax(x2); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: "var 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void DeclarationWithImplicitVarType() { string source = @" class C { static void Main() { (var x1, var x2) = (1, 2); var (x3, x4) = (3, 4); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); var x4 = GetDeconstructionVariable(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForDeconstructionLocal(model, x4, x4Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x1Type)); var x34Var = (DeclarationExpressionSyntax)x3.Parent.Parent; Assert.Equal("var", x34Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x34Var.Type).Symbol); // The var in `var (x3, x4)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void DeclarationWithAliasedVarType() { string source = @" using var = D; class C { static void Main() { (var x1, int x2) = (new var(), 2); System.Console.WriteLine(x1 + "" "" + x2); } } class D { public override string ToString() { return ""var""; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("D", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); var x1Alias = model.GetAliasInfo(x1Type); Assert.Equal(SymbolKind.NamedType, x1Alias.Target.Kind); Assert.Equal("D", x1Alias.Target.ToDisplayString()); // extra checks on x2 var x2Type = GetTypeSyntax(x2); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x2Type)); }; var comp = CompileAndVerify(source, expectedOutput: "var 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForWithImplicitVarType() { string source = @" class C { static void Main() { for (var (x1, x2) = (1, 2); x1 < 2; (x1, x2) = (x1 + 1, x2 + 1)) { System.Console.WriteLine(x1 + "" "" + x2); } } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 4); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReferences(tree, "x2", 3); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForWithVarDeconstructInitializersCanParse() { string source = @" using System; class C { static void Main() { int x3; for (var (x1, x2) = (1, 2), x3 = 3; true; ) { Console.WriteLine(x1); Console.WriteLine(x2); Console.WriteLine(x3); break; } } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); }; var comp = CompileAndVerify(source, expectedOutput: @"1 2 3", sourceSymbolValidator: validator); comp.VerifyDiagnostics( // this is permitted now, as it is just an assignment expression ); } [Fact] public void ForWithActualVarType() { string source = @" class C { static void Main() { for ((int x1, var x2) = (1, new var()); x1 < 2; x1++) { System.Console.WriteLine(x1 + "" "" + x2); } } } class var { public override string ToString() { return ""var""; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 3); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); // extra checks on x2 var x2Type = GetTypeSyntax(x2); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind); Assert.Equal("var", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: "1 var", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForWithTypes() { string source = @" class C { static void Main() { for ((int x1, var x2) = (1, 2); x1 < 2; x1++) { System.Console.WriteLine(x1 + "" "" + x2); } } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 3); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); // extra checks on x2 var x2Type = GetTypeSyntax(x2); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForEachIEnumerableDeclarationWithImplicitVarType() { string source = @" using System.Collections.Generic; class C { static void Main() { foreach (var (x1, x2) in M()) { Print(x1, x2); } } static IEnumerable<(int, int)> M() { yield return (1, 2); } static void Print(object a, object b) { System.Console.WriteLine(a + "" "" + b); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Equal("(System.Int32 x1, System.Int32 x2)", model.GetTypeInfo(x12Var).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol // verify deconstruction info var deconstructionForeach = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single(); var deconstructionInfo = model.GetDeconstructionInfo(deconstructionForeach); Assert.Null(deconstructionInfo.Method); Assert.Null(deconstructionInfo.Conversion); var nested = deconstructionInfo.Nested; Assert.Equal(2, nested.Length); Assert.Null(nested[0].Method); Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind); Assert.Empty(nested[0].Nested); Assert.Null(nested[1].Method); Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind); Assert.Empty(nested[1].Nested); }; var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); var comp7_1 = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1); comp7_1.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 70 (0x46) .maxstack 2 .locals init (System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>> V_0, int V_1, //x1 int V_2) //x2 IL_0000: call ""System.Collections.Generic.IEnumerable<System.ValueTuple<int, int>> C.M()"" IL_0005: callvirt ""System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>> System.Collections.Generic.IEnumerable<System.ValueTuple<int, int>>.GetEnumerator()"" IL_000a: stloc.0 .try { IL_000b: br.s IL_0031 IL_000d: ldloc.0 IL_000e: callvirt ""System.ValueTuple<int, int> System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>>.Current.get"" IL_0013: dup IL_0014: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0019: stloc.1 IL_001a: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_001f: stloc.2 IL_0020: ldloc.1 IL_0021: box ""int"" IL_0026: ldloc.2 IL_0027: box ""int"" IL_002c: call ""void C.Print(object, object)"" IL_0031: ldloc.0 IL_0032: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_0037: brtrue.s IL_000d IL_0039: leave.s IL_0045 } finally { IL_003b: ldloc.0 IL_003c: brfalse.s IL_0044 IL_003e: ldloc.0 IL_003f: callvirt ""void System.IDisposable.Dispose()"" IL_0044: endfinally } IL_0045: ret }"); } [Fact] public void ForEachSZArrayDeclarationWithImplicitVarType() { string source = @" class C { static void Main() { foreach (var (x1, x2) in M()) { System.Console.Write(x1 + "" "" + x2 + "" - ""); } } static (int, int)[] M() { return new[] { (1, 2), (3, 4) }; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); var symbol = model.GetDeclaredSymbol(x1); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 -", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 75 (0x4b) .maxstack 4 .locals init (System.ValueTuple<int, int>[] V_0, int V_1, int V_2, //x1 int V_3) //x2 IL_0000: call ""System.ValueTuple<int, int>[] C.M()"" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 IL_0008: br.s IL_0044 IL_000a: ldloc.0 IL_000b: ldloc.1 IL_000c: ldelem ""System.ValueTuple<int, int>"" IL_0011: dup IL_0012: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0017: stloc.2 IL_0018: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_001d: stloc.3 IL_001e: ldloca.s V_2 IL_0020: call ""string int.ToString()"" IL_0025: ldstr "" "" IL_002a: ldloca.s V_3 IL_002c: call ""string int.ToString()"" IL_0031: ldstr "" - "" IL_0036: call ""string string.Concat(string, string, string, string)"" IL_003b: call ""void System.Console.Write(string)"" IL_0040: ldloc.1 IL_0041: ldc.i4.1 IL_0042: add IL_0043: stloc.1 IL_0044: ldloc.1 IL_0045: ldloc.0 IL_0046: ldlen IL_0047: conv.i4 IL_0048: blt.s IL_000a IL_004a: ret }"); } [Fact] public void ForEachMDArrayDeclarationWithImplicitVarType() { string source = @" class C { static void Main() { foreach (var (x1, x2) in M()) { Print(x1, x2); } } static (int, int)[,] M() { return new (int, int)[2, 2] { { (1, 2), (3, 4) }, { (5, 6), (7, 8) } }; } static void Print(object a, object b) { System.Console.Write(a + "" "" + b + "" - ""); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 - 5 6 - 7 8 -", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 106 (0x6a) .maxstack 3 .locals init (System.ValueTuple<int, int>[,] V_0, int V_1, int V_2, int V_3, int V_4, int V_5, //x1 int V_6) //x2 IL_0000: call ""System.ValueTuple<int, int>[,] C.M()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: callvirt ""int System.Array.GetUpperBound(int)"" IL_000d: stloc.1 IL_000e: ldloc.0 IL_000f: ldc.i4.1 IL_0010: callvirt ""int System.Array.GetUpperBound(int)"" IL_0015: stloc.2 IL_0016: ldloc.0 IL_0017: ldc.i4.0 IL_0018: callvirt ""int System.Array.GetLowerBound(int)"" IL_001d: stloc.3 IL_001e: br.s IL_0065 IL_0020: ldloc.0 IL_0021: ldc.i4.1 IL_0022: callvirt ""int System.Array.GetLowerBound(int)"" IL_0027: stloc.s V_4 IL_0029: br.s IL_005c IL_002b: ldloc.0 IL_002c: ldloc.3 IL_002d: ldloc.s V_4 IL_002f: call ""(int, int)[*,*].Get"" IL_0034: dup IL_0035: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003a: stloc.s V_5 IL_003c: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0041: stloc.s V_6 IL_0043: ldloc.s V_5 IL_0045: box ""int"" IL_004a: ldloc.s V_6 IL_004c: box ""int"" IL_0051: call ""void C.Print(object, object)"" IL_0056: ldloc.s V_4 IL_0058: ldc.i4.1 IL_0059: add IL_005a: stloc.s V_4 IL_005c: ldloc.s V_4 IL_005e: ldloc.2 IL_005f: ble.s IL_002b IL_0061: ldloc.3 IL_0062: ldc.i4.1 IL_0063: add IL_0064: stloc.3 IL_0065: ldloc.3 IL_0066: ldloc.1 IL_0067: ble.s IL_0020 IL_0069: ret }"); } [Fact] public void ForEachStringDeclarationWithImplicitVarType() { string source = @" class C { static void Main() { foreach (var (x1, x2) in M()) { Print(x1, x2); } } static string M() { return ""123""; } static void Print(object a, object b) { System.Console.Write(a + "" "" + b + "" - ""); } } static class Extension { public static void Deconstruct(this char value, out int item1, out int item2) { item1 = item2 = System.Int32.Parse(value.ToString()); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 1 - 2 2 - 3 3 - ", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 60 (0x3c) .maxstack 3 .locals init (string V_0, int V_1, int V_2, //x2 int V_3, int V_4) IL_0000: call ""string C.M()"" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 IL_0008: br.s IL_0032 IL_000a: ldloc.0 IL_000b: ldloc.1 IL_000c: callvirt ""char string.this[int].get"" IL_0011: ldloca.s V_3 IL_0013: ldloca.s V_4 IL_0015: call ""void Extension.Deconstruct(char, out int, out int)"" IL_001a: ldloc.3 IL_001b: ldloc.s V_4 IL_001d: stloc.2 IL_001e: box ""int"" IL_0023: ldloc.2 IL_0024: box ""int"" IL_0029: call ""void C.Print(object, object)"" IL_002e: ldloc.1 IL_002f: ldc.i4.1 IL_0030: add IL_0031: stloc.1 IL_0032: ldloc.1 IL_0033: ldloc.0 IL_0034: callvirt ""int string.Length.get"" IL_0039: blt.s IL_000a IL_003b: ret }"); } [Fact] [WorkItem(22495, "https://github.com/dotnet/roslyn/issues/22495")] public void ForEachCollectionSymbol() { string source = @" using System.Collections.Generic; class Deconstructable { void M(IEnumerable<Deconstructable> x) { foreach (var (y1, y2) in x) { } } void Deconstruct(out int i, out int j) { i = 0; j = 0; } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var collection = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single().Expression; Assert.Equal("x", collection.ToString()); var symbol = model.GetSymbolInfo(collection).Symbol; Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("x", symbol.Name); Assert.Equal("System.Collections.Generic.IEnumerable<Deconstructable> x", symbol.ToTestDisplayString()); } [Fact] public void ForEachIEnumerableDeclarationWithNesting() { string source = @" using System.Collections.Generic; class C { static void Main() { foreach ((int x1, var (x2, x3), (int x4, int x5)) in M()) { System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - ""); } } static IEnumerable<(int, (int, int), (int, int))> M() { yield return (1, (2, 3), (4, 5)); yield return (6, (7, 8), (9, 10)); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionForeach(model, x3, x3Ref); var x4 = GetDeconstructionVariable(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForDeconstructionForeach(model, x4, x4Ref); var x5 = GetDeconstructionVariable(tree, "x5"); var x5Ref = GetReference(tree, "x5"); VerifyModelForDeconstructionForeach(model, x5, x5Ref); // extra check on var var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent; Assert.Equal("var", x23Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForEachSZArrayDeclarationWithNesting() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3), (int x4, int x5)) in M()) { System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - ""); } } static (int, (int, int), (int, int))[] M() { return new[] { (1, (2, 3), (4, 5)), (6, (7, 8), (9, 10)) }; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -"); comp.VerifyDiagnostics(); } [Fact] public void ForEachMDArrayDeclarationWithNesting() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3), (int x4, int x5)) in M()) { System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - ""); } } static (int, (int, int), (int, int))[,] M() { return new(int, (int, int), (int, int))[1, 2] { { (1, (2, 3), (4, 5)), (6, (7, 8), (9, 10)) } }; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -"); comp.VerifyDiagnostics(); } [Fact] public void ForEachStringDeclarationWithNesting() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3)) in M()) { System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" - ""); } } static string M() { return ""12""; } } static class Extension { public static void Deconstruct(this char value, out int item1, out (int, int) item2) { item1 = System.Int32.Parse(value.ToString()); item2 = (item1, item1); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 1 1 - 2 2 2 - "); comp.VerifyDiagnostics(); } [Fact] public void DeconstructExtensionOnInterface() { string source = @" public interface Interface { } class C : Interface { static void Main() { var (x, y) = new C(); System.Console.Write($""{x} {y}""); } } static class Extension { public static void Deconstruct(this Interface value, out int item1, out string item2) { item1 = 42; item2 = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "42 hello"); comp.VerifyDiagnostics(); } [Fact] public void ForEachIEnumerableDeclarationWithDeconstruct() { string source = @" using System.Collections.Generic; class C { static void Main() { foreach ((long x1, var (x2, x3)) in M()) { Print(x1, x2, x3); } } static IEnumerable<Pair<int, Pair<int, int>>> M() { yield return Pair.Create(1, Pair.Create(2, 3)); yield return Pair.Create(4, Pair.Create(5, 6)); } static void Print(object a, object b, object c) { System.Console.WriteLine(a + "" "" + b + "" "" + c); } } " + commonSource; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionForeach(model, x3, x3Ref); // extra check on var var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent; Assert.Equal("var", x23Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol }; string expected = @"Deconstructing (1, (2, 3)) Deconstructing (2, 3) 1 2 3 Deconstructing (4, (5, 6)) Deconstructing (5, 6) 4 5 6"; var comp = CompileAndVerify(source, expectedOutput: expected, sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 90 (0x5a) .maxstack 3 .locals init (System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>> V_0, int V_1, //x2 int V_2, //x3 int V_3, Pair<int, int> V_4, int V_5, int V_6) IL_0000: call ""System.Collections.Generic.IEnumerable<Pair<int, Pair<int, int>>> C.M()"" IL_0005: callvirt ""System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>> System.Collections.Generic.IEnumerable<Pair<int, Pair<int, int>>>.GetEnumerator()"" IL_000a: stloc.0 .try { IL_000b: br.s IL_0045 IL_000d: ldloc.0 IL_000e: callvirt ""Pair<int, Pair<int, int>> System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>>.Current.get"" IL_0013: ldloca.s V_3 IL_0015: ldloca.s V_4 IL_0017: callvirt ""void Pair<int, Pair<int, int>>.Deconstruct(out int, out Pair<int, int>)"" IL_001c: ldloc.s V_4 IL_001e: ldloca.s V_5 IL_0020: ldloca.s V_6 IL_0022: callvirt ""void Pair<int, int>.Deconstruct(out int, out int)"" IL_0027: ldloc.3 IL_0028: conv.i8 IL_0029: ldloc.s V_5 IL_002b: stloc.1 IL_002c: ldloc.s V_6 IL_002e: stloc.2 IL_002f: box ""long"" IL_0034: ldloc.1 IL_0035: box ""int"" IL_003a: ldloc.2 IL_003b: box ""int"" IL_0040: call ""void C.Print(object, object, object)"" IL_0045: ldloc.0 IL_0046: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_004b: brtrue.s IL_000d IL_004d: leave.s IL_0059 } finally { IL_004f: ldloc.0 IL_0050: brfalse.s IL_0058 IL_0052: ldloc.0 IL_0053: callvirt ""void System.IDisposable.Dispose()"" IL_0058: endfinally } IL_0059: ret } "); } [Fact] public void ForEachSZArrayDeclarationWithDeconstruct() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3)) in M()) { System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } static Pair<int, Pair<int, int>>[] M() { return new[] { Pair.Create(1, Pair.Create(2, 3)), Pair.Create(4, Pair.Create(5, 6)) }; } } " + commonSource; string expected = @"Deconstructing (1, (2, 3)) Deconstructing (2, 3) 1 2 3 Deconstructing (4, (5, 6)) Deconstructing (5, 6) 4 5 6"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void ForEachMDArrayDeclarationWithDeconstruct() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3)) in M()) { System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } static Pair<int, Pair<int, int>>[,] M() { return new Pair<int, Pair<int, int>> [1, 2] { { Pair.Create(1, Pair.Create(2, 3)), Pair.Create(4, Pair.Create(5, 6)) } }; } } " + commonSource; string expected = @"Deconstructing (1, (2, 3)) Deconstructing (2, 3) 1 2 3 Deconstructing (4, (5, 6)) Deconstructing (5, 6) 4 5 6"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void ForEachWithExpressionBody() { string source = @" class C { static void Main() { foreach (var (x1, x2) in new[] { (1, 2), (3, 4) }) System.Console.Write(x1 + "" "" + x2 + "" - ""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 -"); comp.VerifyDiagnostics(); } [Fact] public void ForEachCreatesNewVariables() { string source = @" class C { static void Main() { var lambdas = new System.Action[2]; int index = 0; foreach (var (x1, x2) in M()) { lambdas[index] = () => { System.Console.Write(x1 + "" ""); }; index++; } lambdas[0](); lambdas[1](); } static (int, int)[] M() { return new[] { (0, 0), (10, 10) }; } } "; var comp = CompileAndVerify(source, expectedOutput: "0 10 "); comp.VerifyDiagnostics(); } [Fact] public void TupleDeconstructionIntoDynamicArrayIndexer() { string source = @" class C { static void Main() { dynamic x = new string[] { """", """" }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic x) { (x[0], x[1]) = (""hello"", ""world""); } } "; var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void IntTupleDeconstructionIntoDynamicArrayIndexer() { string source = @" class C { static void Main() { dynamic x = new int[] { 1, 2 }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic x) { (x[0], x[1]) = (3, 4); } } "; var comp = CompileAndVerify(source, expectedOutput: "3 4", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructionIntoDynamicArrayIndexer() { string source = @" class C { static void Main() { dynamic x = new string[] { """", """" }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic x) { (x[0], x[1]) = new C(); } public void Deconstruct(out string a, out string b) { a = ""hello""; b = ""world""; } } "; var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void TupleDeconstructionIntoDynamicArray() { string source = @" class C { static void Main() { dynamic[] x = new string[] { """", """" }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic[] x) { (x[0], x[1]) = (""hello"", ""world""); } } "; var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructionIntoDynamicArray() { string source = @" class C { static void Main() { dynamic[] x = new string[] { """", """" }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic[] x) { (x[0], x[1]) = new C(); } public void Deconstruct(out string a, out string b) { a = ""hello""; b = ""world""; } } "; var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructionIntoDynamicMember() { string source = @" class C { static void Main() { dynamic x = System.ValueTuple.Create(1, 2); (x.Item1, x.Item2) = new C(); System.Console.WriteLine($""{x.Item1} {x.Item2}""); } public void Deconstruct(out int a, out int b) { a = 3; b = 4; } } "; var comp = CompileAndVerify(source, expectedOutput: "3 4", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void FieldAndLocalWithSameName() { string source = @" class C { public int x = 3; static void Main() { new C().M(); } void M() { var (x, y) = (1, 2); System.Console.Write($""{x} {y} {this.x}""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 3"); comp.VerifyDiagnostics(); } [Fact] public void NoGlobalDeconstructionUnlessScript() { string source = @" class C { var (x, y) = (1, 2); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,11): error CS1001: Identifier expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(4, 11), // (4,14): error CS1001: Identifier expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 14), // (4,16): error CS1002: ; expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_SemicolonExpected, "=").WithLocation(4, 16), // (4,16): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(4, 16), // (4,19): error CS1031: Type expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_TypeExpected, "1").WithLocation(4, 19), // (4,19): error CS8124: Tuple must contain at least two elements. // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_TupleTooFewElements, "1").WithLocation(4, 19), // (4,19): error CS1026: ) expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_CloseParenExpected, "1").WithLocation(4, 19), // (4,19): error CS1519: Invalid token '1' in class, record, struct, or interface member declaration // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "1").WithArguments("1").WithLocation(4, 19), // (4,5): error CS1520: Method must have a return type // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_MemberNeedsType, "var").WithLocation(4, 5), // (4,5): error CS0501: 'C.C(x, y)' must declare a body because it is not marked abstract, extern, or partial // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "var").WithArguments("C.C(x, y)").WithLocation(4, 5), // (4,10): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?) // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x").WithLocation(4, 10), // (4,13): error CS0246: The type or namespace name 'y' could not be found (are you missing a using directive or an assembly reference?) // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "y").WithArguments("y").WithLocation(4, 13) ); var nodes = comp.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf(); Assert.False(nodes.Any(n => n.Kind() == SyntaxKind.SimpleAssignmentExpression)); } [Fact] public void SimpleDeconstructionInScript() { var source = @" using alias = System.Int32; (string x, alias y) = (""hello"", 42); System.Console.Write($""{x} {y}""); "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); var xRef = GetReference(tree, "x"); Assert.Equal("System.String Script.x", xSymbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x, xRef); var y = GetDeconstructionVariable(tree, "y"); var ySymbol = model.GetDeclaredSymbol(y); var yRef = GetReference(tree, "y"); Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, y, yRef); // extra checks on x var xType = GetTypeSyntax(x); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(xType).Symbol.Kind); Assert.Equal("string", model.GetSymbolInfo(xType).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(xType)); // extra checks on y var yType = GetTypeSyntax(y); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(yType).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(yType).Symbol.ToDisplayString()); Assert.Equal("alias=System.Int32", model.GetAliasInfo(yType).ToTestDisplayString()); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42", sourceSymbolValidator: validator); verifier.VerifyIL("<<Initialize>>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 129 (0x81) .maxstack 3 .locals init (int V_0, object V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""int <<Initialize>>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldarg.0 IL_0008: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_000d: ldstr ""hello"" IL_0012: stfld ""string x"" IL_0017: ldarg.0 IL_0018: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_001d: ldc.i4.s 42 IL_001f: stfld ""int y"" IL_0024: ldstr ""{0} {1}"" IL_0029: ldarg.0 IL_002a: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_002f: ldfld ""string x"" IL_0034: ldarg.0 IL_0035: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_003a: ldfld ""int y"" IL_003f: box ""int"" IL_0044: call ""string string.Format(string, object, object)"" IL_0049: call ""void System.Console.Write(string)"" IL_004e: nop IL_004f: ldnull IL_0050: stloc.1 IL_0051: leave.s IL_006b } catch System.Exception { IL_0053: stloc.2 IL_0054: ldarg.0 IL_0055: ldc.i4.s -2 IL_0057: stfld ""int <<Initialize>>d__0.<>1__state"" IL_005c: ldarg.0 IL_005d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0062: ldloc.2 IL_0063: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)"" IL_0068: nop IL_0069: leave.s IL_0080 } IL_006b: ldarg.0 IL_006c: ldc.i4.s -2 IL_006e: stfld ""int <<Initialize>>d__0.<>1__state"" IL_0073: ldarg.0 IL_0074: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0079: ldloc.1 IL_007a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)"" IL_007f: nop IL_0080: ret }"); } [Fact] public void GlobalDeconstructionOutsideScript() { var source = @" (string x, int y) = (""hello"", 42); System.Console.Write(x); System.Console.Write(y); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var nodes = comp.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf(); Assert.True(nodes.Any(n => n.Kind() == SyntaxKind.SimpleAssignmentExpression)); CompileAndVerify(comp, expectedOutput: "hello42"); } [Fact] public void NestedDeconstructionInScript() { var source = @" (string x, (int y, int z)) = (""hello"", (42, 43)); System.Console.Write($""{x} {y} {z}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 43"); } [Fact] public void VarDeconstructionInScript() { var source = @" (var x, var y) = (""hello"", 42); System.Console.Write($""{x} {y}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42"); } [Fact] public void NestedVarDeconstructionInScript() { var source = @" (var x1, var (x2, x3)) = (""hello"", (42, 43)); System.Console.Write($""{x1} {x2} {x3}""); "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.String Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); var x2Ref = GetReference(tree, "x2"); Assert.Equal("System.Int32 Script.x2", x2Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x2, x2Ref); // extra checks on x1's var var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("string", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x1Type)); // extra check on x2 and x3's var var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent; Assert.Equal("var", x23Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 43", sourceSymbolValidator: validator); } [Fact] public void EvaluationOrderForDeconstructionInScript() { var source = @" (int, int) M(out int x) { x = 1; return (2, 3); } var (x2, x3) = M(out var x1); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "1 2 3"); verifier.VerifyIL("<<Initialize>>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 178 (0xb2) .maxstack 4 .locals init (int V_0, object V_1, System.ValueTuple<int, int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int <<Initialize>>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldarg.0 IL_0008: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_000d: ldarg.0 IL_000e: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_0013: ldflda ""int x1"" IL_0018: call ""System.ValueTuple<int, int> M(out int)"" IL_001d: stloc.2 IL_001e: ldarg.0 IL_001f: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_0024: ldloc.2 IL_0025: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_002a: stfld ""int x2"" IL_002f: ldarg.0 IL_0030: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_0035: ldloc.2 IL_0036: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_003b: stfld ""int x3"" IL_0040: ldstr ""{0} {1} {2}"" IL_0045: ldarg.0 IL_0046: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_004b: ldfld ""int x1"" IL_0050: box ""int"" IL_0055: ldarg.0 IL_0056: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_005b: ldfld ""int x2"" IL_0060: box ""int"" IL_0065: ldarg.0 IL_0066: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_006b: ldfld ""int x3"" IL_0070: box ""int"" IL_0075: call ""string string.Format(string, object, object, object)"" IL_007a: call ""void System.Console.Write(string)"" IL_007f: nop IL_0080: ldnull IL_0081: stloc.1 IL_0082: leave.s IL_009c } catch System.Exception { IL_0084: stloc.3 IL_0085: ldarg.0 IL_0086: ldc.i4.s -2 IL_0088: stfld ""int <<Initialize>>d__0.<>1__state"" IL_008d: ldarg.0 IL_008e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0093: ldloc.3 IL_0094: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)"" IL_0099: nop IL_009a: leave.s IL_00b1 } IL_009c: ldarg.0 IL_009d: ldc.i4.s -2 IL_009f: stfld ""int <<Initialize>>d__0.<>1__state"" IL_00a4: ldarg.0 IL_00a5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_00aa: ldloc.1 IL_00ab: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)"" IL_00b0: nop IL_00b1: ret } "); } [Fact] public void DeconstructionForEachInScript() { var source = @" foreach ((string x1, var (x2, x3)) in new[] { (""hello"", (42, ""world"")) }) { System.Console.Write($""{x1} {x2} {x3}""); } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); Assert.Equal("System.String x1", x1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, x1Symbol.Kind); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); Assert.Equal("System.Int32 x2", x2Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, x2Symbol.Kind); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 world", sourceSymbolValidator: validator); } [Fact] public void DeconstructionInForLoopInScript() { var source = @" for ((string x1, var (x2, x3)) = (""hello"", (42, ""world"")); ; ) { System.Console.Write($""{x1} {x2} {x3}""); break; } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); Assert.Equal("System.String x1", x1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, x1Symbol.Kind); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); Assert.Equal("System.Int32 x2", x2Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, x2Symbol.Kind); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 world", sourceSymbolValidator: validator); } [Fact] public void DeconstructionInCSharp6Script() { var source = @" var (x, y) = (1, 2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp6), options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (2,5): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(x, y)").WithArguments("tuples", "7.0").WithLocation(2, 5), // (2,14): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7 or greater. // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2)").WithArguments("tuples", "7.0").WithLocation(2, 14) ); } [Fact] public void InvalidDeconstructionInScript() { var source = @" int (x, y) = (1, 2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (2,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // int (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x, y)").WithLocation(2, 5) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString()); var xType = ((IFieldSymbol)xSymbol).Type; Assert.False(xType.IsErrorType()); Assert.Equal("System.Int32", xType.ToTestDisplayString()); var y = GetDeconstructionVariable(tree, "y"); var ySymbol = model.GetDeclaredSymbol(y); Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString()); var yType = ((IFieldSymbol)ySymbol).Type; Assert.False(yType.IsErrorType()); Assert.Equal("System.Int32", yType.ToTestDisplayString()); } [Fact] public void InvalidDeconstructionInScript_2() { var source = @" (int (x, y), int z) = ((1, 2), 3); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (2,6): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // (int (x, y), int z) = ((1, 2), 3); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x, y)").WithLocation(2, 6) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString()); var xType = ((IFieldSymbol)xSymbol).Type; Assert.False(xType.IsErrorType()); Assert.Equal("System.Int32", xType.ToTestDisplayString()); var y = GetDeconstructionVariable(tree, "y"); var ySymbol = model.GetDeclaredSymbol(y); Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString()); var yType = ((IFieldSymbol)ySymbol).Type; Assert.False(yType.IsErrorType()); Assert.Equal("System.Int32", yType.ToTestDisplayString()); } [Fact] public void NameConflictInDeconstructionInScript() { var source = @" int x1; var (x1, x2) = (1, 2); System.Console.Write(x1); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (3,6): error CS0102: The type 'Script' already contains a definition for 'x1' // var (x1, x2) = (1, 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x1").WithArguments("Script", "x1").WithLocation(3, 6), // (4,22): error CS0229: Ambiguity between 'x1' and 'x1' // System.Console.Write(x1); Diagnostic(ErrorCode.ERR_AmbigMember, "x1").WithArguments("x1", "x1").WithLocation(4, 22) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var firstX1 = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "x1").Single(); var firstX1Symbol = model.GetDeclaredSymbol(firstX1); Assert.Equal("System.Int32 Script.x1", firstX1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, firstX1Symbol.Kind); var secondX1 = GetDeconstructionVariable(tree, "x1"); var secondX1Symbol = model.GetDeclaredSymbol(secondX1); Assert.Equal("System.Int32 Script.x1", secondX1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, secondX1Symbol.Kind); Assert.NotEqual(firstX1Symbol, secondX1Symbol); } [Fact] public void NameConflictInDeconstructionInScript2() { var source = @" var (x, y) = (1, 2); var (z, y) = (1, 2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (3,9): error CS0102: The type 'Script' already contains a definition for 'y' // var (z, y) = (1, 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "y").WithArguments("Script", "y").WithLocation(3, 9) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var firstY = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "y").First(); var firstYSymbol = model.GetDeclaredSymbol(firstY); Assert.Equal("System.Int32 Script.y", firstYSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, firstYSymbol.Kind); var secondY = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "y").ElementAt(1); var secondYSymbol = model.GetDeclaredSymbol(secondY); Assert.Equal("System.Int32 Script.y", secondYSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, secondYSymbol.Kind); Assert.NotEqual(firstYSymbol, secondYSymbol); } [Fact] public void NameConflictInDeconstructionInScript3() { var source = @" var (x, (y, x)) = (1, (2, ""hello"")); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (2,13): error CS0102: The type 'Script' already contains a definition for 'x' // var (x, (y, x)) = (1, (2, "hello")); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x").WithArguments("Script", "x").WithLocation(2, 13) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var firstX = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "x").First(); var firstXSymbol = model.GetDeclaredSymbol(firstX); Assert.Equal("System.Int32 Script.x", firstXSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, firstXSymbol.Kind); var secondX = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "x").ElementAt(1); var secondXSymbol = model.GetDeclaredSymbol(secondX); Assert.Equal("System.String Script.x", secondXSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, secondXSymbol.Kind); Assert.NotEqual(firstXSymbol, secondXSymbol); } [Fact] public void UnassignedUsedInDeconstructionInScript() { var source = @" System.Console.Write(x); var (x, y) = (1, 2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "0"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); var xRef = GetReference(tree, "x"); Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x, xRef); var xType = ((IFieldSymbol)xSymbol).Type; Assert.False(xType.IsErrorType()); Assert.Equal("System.Int32", xType.ToTestDisplayString()); } [Fact] public void FailedInferenceInDeconstructionInScript() { var source = @" var (x, y) = (1, null); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.GetDeclarationDiagnostics().Verify( // (2,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (1, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(2, 6), // (2,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (1, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(2, 9) ); comp.VerifyDiagnostics( // (2,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (1, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(2, 6), // (2,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (1, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(2, 9) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); Assert.Equal("var Script.x", xSymbol.ToTestDisplayString()); var xType = xSymbol.GetSymbol<FieldSymbol>().TypeWithAnnotations; Assert.True(xType.Type.IsErrorType()); Assert.Equal("var", xType.ToTestDisplayString()); var xTypeISymbol = xType.Type.GetPublicSymbol(); Assert.Equal(SymbolKind.ErrorType, xTypeISymbol.Kind); var y = GetDeconstructionVariable(tree, "y"); var ySymbol = model.GetDeclaredSymbol(y); Assert.Equal("var Script.y", ySymbol.ToTestDisplayString()); var yType = ((IFieldSymbol)ySymbol).Type; Assert.True(yType.IsErrorType()); Assert.Equal("var", yType.ToTestDisplayString()); } [Fact] public void FailedCircularInferenceInDeconstructionInScript() { var source = @" var (x1, x2) = (x2, x1); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.GetDeclarationDiagnostics().Verify( // (2,10): error CS7019: Type of 'x2' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (x1, x2) = (x2, x1); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x2").WithArguments("x2").WithLocation(2, 10), // (2,6): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (x1, x2) = (x2, x1); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 6) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("var Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x1Type = ((IFieldSymbol)x1Symbol).Type; Assert.True(x1Type.IsErrorType()); Assert.Equal("var", x1Type.Name); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); var x2Ref = GetReference(tree, "x2"); Assert.Equal("var Script.x2", x2Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x2, x2Ref); var x2Type = ((IFieldSymbol)x2Symbol).Type; Assert.True(x2Type.IsErrorType()); Assert.Equal("var", x2Type.Name); } [Fact] public void FailedCircularInferenceInDeconstructionInScript2() { var source = @" var (x1, x2) = (y1, y2); var (y1, y2) = (x1, x2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.GetDeclarationDiagnostics().Verify( // (3,6): error CS7019: Type of 'y1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (y1, y2) = (x1, x2); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "y1").WithArguments("y1").WithLocation(3, 6), // (2,6): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (x1, x2) = (y1, y2); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 6), // (2,10): error CS7019: Type of 'x2' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (x1, x2) = (y1, y2); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x2").WithArguments("x2").WithLocation(2, 10) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("var Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x1Type = ((IFieldSymbol)x1Symbol).Type; Assert.True(x1Type.IsErrorType()); Assert.Equal("var", x1Type.Name); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); var x2Ref = GetReference(tree, "x2"); Assert.Equal("var Script.x2", x2Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x2, x2Ref); var x2Type = ((IFieldSymbol)x2Symbol).Type; Assert.True(x2Type.IsErrorType()); Assert.Equal("var", x2Type.Name); } [Fact] public void VarAliasInVarDeconstructionInScript() { var source = @" using var = System.Byte; var (x1, (x2, x3)) = (1, (2, 3)); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (3,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // var (x1, (x2, x3)) = (1, (2, 3)); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x1, (x2, x3))").WithLocation(3, 5) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.Byte Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Symbol = model.GetDeclaredSymbol(x3); var x3Ref = GetReference(tree, "x3"); Assert.Equal("System.Byte Script.x3", x3Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x3, x3Ref); // extra check on var var x123Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x123Var.Type.ToString()); Assert.Null(model.GetTypeInfo(x123Var.Type).Type); Assert.Null(model.GetSymbolInfo(x123Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol } [Fact] public void VarTypeInVarDeconstructionInScript() { var source = @" class var { public static implicit operator var(int i) { return null; } } var (x1, (x2, x3)) = (1, (2, 3)); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (6,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // var (x1, (x2, x3)) = (1, (2, 3)); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x1, (x2, x3))").WithLocation(6, 5) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("Script.var Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Symbol = model.GetDeclaredSymbol(x3); var x3Ref = GetReference(tree, "x3"); Assert.Equal("Script.var Script.x3", x3Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x3, x3Ref); // extra check on var var x123Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x123Var.Type.ToString()); Assert.Null(model.GetTypeInfo(x123Var.Type).Type); Assert.Null(model.GetSymbolInfo(x123Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol } [Fact] public void VarAliasInTypedDeconstructionInScript() { var source = @" using var = System.Byte; (var x1, (var x2, var x3)) = (1, (2, 3)); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1 2 3"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.Byte Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Symbol = model.GetDeclaredSymbol(x3); var x3Ref = GetReference(tree, "x3"); Assert.Equal("System.Byte Script.x3", x3Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x3, x3Ref); // extra checks on x1's var var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("byte", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); var x1Alias = model.GetAliasInfo(x1Type); Assert.Equal(SymbolKind.NamedType, x1Alias.Target.Kind); Assert.Equal("byte", x1Alias.Target.ToDisplayString()); // extra checks on x3's var var x3Type = GetTypeSyntax(x3); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x3Type).Symbol.Kind); Assert.Equal("byte", model.GetSymbolInfo(x3Type).Symbol.ToDisplayString()); var x3Alias = model.GetAliasInfo(x3Type); Assert.Equal(SymbolKind.NamedType, x3Alias.Target.Kind); Assert.Equal("byte", x3Alias.Target.ToDisplayString()); } [Fact] public void VarTypeInTypedDeconstructionInScript() { var source = @" class var { public static implicit operator var(int i) { return new var(); } public override string ToString() { return ""var""; } } (var x1, (var x2, var x3)) = (1, (2, 3)); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "var var var"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("Script.var Script.x1", x1Symbol.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x1).Symbol); VerifyModelForDeconstructionField(model, x1, x1Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Symbol = model.GetDeclaredSymbol(x3); var x3Ref = GetReference(tree, "x3"); Assert.Equal("Script.var Script.x3", x3Symbol.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x3).Symbol); VerifyModelForDeconstructionField(model, x3, x3Ref); // extra checks on x1's var var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("var", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x1Type)); // extra checks on x3's var var x3Type = GetTypeSyntax(x3); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x3Type).Symbol.Kind); Assert.Equal("var", model.GetSymbolInfo(x3Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x3Type)); } [Fact] public void SimpleDiscardWithConversion() { var source = @" class C { static void Main() { (int _, var x) = (new C(1), 1); (var _, var y) = (new C(2), 2); var (_, z) = (new C(3), 3); System.Console.Write($""Output {x} {y} {z}.""); } int _i; public C(int i) { _i = i; } public static implicit operator int(C c) { System.Console.Write($""Converted {c._i}. ""); return 0; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Converted 1. Output 1 2 3."); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("int _", declaration1.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); var discard2 = GetDiscardDesignations(tree).ElementAt(1); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Null(model.GetSymbolInfo(discard2).Symbol); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("var _", declaration2.ToString()); Assert.Equal("C", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); var discard3 = GetDiscardDesignations(tree).ElementAt(2); var declaration3 = (DeclarationExpressionSyntax)discard3.Parent.Parent; Assert.Equal("var (_, z)", declaration3.ToString()); Assert.Equal("(C, System.Int32 z)", model.GetTypeInfo(declaration3).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration3).Symbol); } [Fact] public void CannotDeconstructIntoDiscardOfWrongType() { var source = @" class C { static void Main() { (int _, string _) = (""hello"", 42); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,30): error CS0029: Cannot implicitly convert type 'string' to 'int' // (int _, string _) = ("hello", 42); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""hello""").WithArguments("string", "int").WithLocation(6, 30), // (6,39): error CS0029: Cannot implicitly convert type 'int' to 'string' // (int _, string _) = ("hello", 42); Diagnostic(ErrorCode.ERR_NoImplicitConv, "42").WithArguments("int", "string").WithLocation(6, 39) ); } [Fact] public void DiscardFromDeconstructMethod() { var source = @" class C { static void Main() { (var _, string y) = new C(); System.Console.Write(y); } void Deconstruct(out int x, out string y) { x = 42; y = ""hello""; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "hello"); } [Fact] public void ShortDiscardInDeclaration() { var source = @" class C { static void Main() { (_, var x) = (1, 2); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard = GetDiscardIdentifiers(tree).First(); var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol; Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal("System.Int32", model.GetTypeInfo(discard).Type.ToTestDisplayString()); var isymbol = (ISymbol)symbol; Assert.Equal(SymbolKind.Discard, isymbol.Kind); } [Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")] public void SameTypeDiscardsAreEqual01() { var source = @" class C { static void Main() { (_, _) = (1, 2); _ = 3; M(out _); } static void M(out int x) => x = 1; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discards = GetDiscardIdentifiers(tree).ToArray(); Assert.Equal(4, discards.Length); var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol; Assert.Equal(symbol0, symbol0); var set = new HashSet<ISymbol>(); foreach (var discard in discards) { var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol; set.Add(symbol); Assert.Equal(SymbolKind.Discard, symbol.Kind); Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal(symbol0, symbol); Assert.Equal(symbol, symbol); Assert.Equal(symbol.GetHashCode(), symbol0.GetHashCode()); // Test to show that reference-unequal discards are equal by type. IDiscardSymbol symbolClone = new DiscardSymbol(TypeWithAnnotations.Create(symbol.Type.GetSymbol())).GetPublicSymbol(); Assert.NotSame(symbol, symbolClone); Assert.Equal(SymbolKind.Discard, symbolClone.Kind); Assert.Equal("int _", symbolClone.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal(symbol.Type, symbolClone.Type); Assert.Equal(symbol0, symbolClone); Assert.Equal(symbol, symbolClone); Assert.Same(symbol.Type, symbolClone.Type); // original symbol for System.Int32 has identity. Assert.Equal(symbol.GetHashCode(), symbolClone.GetHashCode()); } Assert.Equal(1, set.Count); } [Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")] public void SameTypeDiscardsAreEqual02() { var source = @"using System.Collections.Generic; class C { static void Main() { (_, _) = (new List<int>(), new List<int>()); _ = new List<int>(); M(out _); } static void M(out List<int> x) => x = new List<int>(); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discards = GetDiscardIdentifiers(tree).ToArray(); Assert.Equal(4, discards.Length); var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol; Assert.Equal(symbol0, symbol0); var set = new HashSet<ISymbol>(); foreach (var discard in discards) { var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol; set.Add(symbol); Assert.Equal(SymbolKind.Discard, symbol.Kind); Assert.Equal("List<int> _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal(symbol0, symbol); Assert.Equal(symbol0.Type, symbol.Type); Assert.Equal(symbol, symbol); Assert.Equal(symbol.GetHashCode(), symbol0.GetHashCode()); if (discard != discards[0]) { // Although it is not part of the compiler's contract, at the moment distinct constructions are distinct Assert.NotSame(symbol.Type, symbol0.Type); Assert.NotSame(symbol, symbol0); } } Assert.Equal(1, set.Count); } [Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")] public void DifferentTypeDiscardsAreNotEqual() { var source = @" class C { static void Main() { (_, _) = (1.0, 2); _ = 3; M(out _); } static void M(out int x) => x = 1; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discards = GetDiscardIdentifiers(tree).ToArray(); Assert.Equal(4, discards.Length); var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol; var set = new HashSet<ISymbol>(); foreach (var discard in discards) { var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol; Assert.Equal(SymbolKind.Discard, symbol.Kind); set.Add(symbol); if (discard == discards[0]) { Assert.Equal("double _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal(symbol0, symbol); Assert.Equal(symbol0.GetHashCode(), symbol.GetHashCode()); } else { Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.NotEqual(symbol0, symbol); } } Assert.Equal(2, set.Count); } [Fact] public void EscapedUnderscoreInDeclaration() { var source = @" class C { static void Main() { (@_, var x) = (1, 2); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,10): error CS0103: The name '_' does not exist in the current context // (@_, var x) = (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "@_").WithArguments("_").WithLocation(6, 10) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); Assert.Empty(GetDiscardIdentifiers(tree)); } [Fact] public void EscapedUnderscoreInDeclarationCSharp9() { var source = @" class C { static void Main() { (@_, var x) = (1, 2); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (@_, var x) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(@_, var x) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(6, 9), // (6,10): error CS0103: The name '_' does not exist in the current context // (@_, var x) = (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "@_").WithArguments("_").WithLocation(6, 10) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); Assert.Empty(GetDiscardIdentifiers(tree)); } [Fact] public void UnderscoreLocalInDeconstructDeclaration() { var source = @" class C { static void Main() { int _; (_, var x) = (1, 2); System.Console.Write(_); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1") .VerifyIL("C.Main", @" { // Code size 13 (0xd) .maxstack 1 .locals init (int V_0, //_ int V_1) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: call ""void System.Console.Write(int)"" IL_000b: nop IL_000c: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard = GetDiscardIdentifiers(tree).First(); Assert.Equal("(_, var x)", discard.Parent.Parent.ToString()); var symbol = (ILocalSymbol)model.GetSymbolInfo(discard).Symbol; Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal("System.Int32", model.GetTypeInfo(discard).Type.ToTestDisplayString()); } [Fact] public void ShortDiscardInDeconstructAssignment() { var source = @" class C { static void Main() { int x; (_, _, x) = (1, 2, 3); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void DiscardInDeconstructAssignment() { var source = @" class C { static void Main() { int x; (_, x) = (1L, 2); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardIdentifiers(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Equal("long _", model.GetSymbolInfo(discard1).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); var tuple1 = (TupleExpressionSyntax)discard1.Parent.Parent; Assert.Equal("(_, x)", tuple1.ToString()); Assert.Equal("(System.Int64, System.Int32 x)", model.GetTypeInfo(tuple1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(tuple1).Symbol); } [Fact] public void DiscardInDeconstructDeclaration() { var source = @" class C { static void Main() { var (_, x) = (1, 2); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); var tuple1 = (DeclarationExpressionSyntax)discard1.Parent.Parent; Assert.Equal("var (_, x)", tuple1.ToString()); Assert.Equal("(System.Int32, System.Int32 x)", model.GetTypeInfo(tuple1).Type.ToTestDisplayString()); } [Fact] public void UnderscoreLocalInDeconstructAssignment() { var source = @" class C { static void Main() { int x, _; (_, x) = (1, 2); System.Console.Write($""{_} {x}""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1 2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard = GetDiscardIdentifiers(tree).First(); Assert.Equal("(_, x)", discard.Parent.Parent.ToString()); var symbol = (ILocalSymbol)model.GetSymbolInfo(discard).Symbol; Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } [Fact] public void DiscardInForeach() { var source = @" class C { static void Main() { foreach (var (_, x) in new[] { (1, ""hello"") }) { System.Console.Write(""1 ""); } foreach ((_, (var y, int z)) in new[] { (1, (""hello"", 2)) }) { System.Console.Write(""2""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1 2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); DiscardDesignationSyntax discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetTypeInfo(discard1).Type); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent.Parent; Assert.Equal("var (_, x)", declaration1.ToString()); Assert.Null(model.GetTypeInfo(discard1).Type); Assert.Equal("(System.Int32, System.String x)", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); IdentifierNameSyntax discard2 = GetDiscardIdentifiers(tree).First(); Assert.Equal("(_, (var y, int z))", discard2.Parent.Parent.ToString()); Assert.Equal("int _", model.GetSymbolInfo(discard2).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal("System.Int32", model.GetTypeInfo(discard2).Type.ToTestDisplayString()); var yz = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(2); Assert.Equal("(var y, int z)", yz.ToString()); Assert.Equal("(System.String y, System.Int32 z)", model.GetTypeInfo(yz).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(yz).Symbol); var y = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1); Assert.Equal("var y", y.ToString()); Assert.Equal("System.String", model.GetTypeInfo(y).Type.ToTestDisplayString()); Assert.Equal("System.String y", model.GetSymbolInfo(y).Symbol.ToTestDisplayString()); } [Fact] public void TwoDiscardsInForeach() { var source = @" class C { static void Main() { foreach ((_, _) in new[] { (1, ""hello"") }) { System.Console.Write(""2""); } } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var refs = GetReferences(tree, "_"); Assert.Equal(2, refs.Count()); model.GetTypeInfo(refs.ElementAt(0)); // Assert.Equal("int", model.GetTypeInfo(refs.ElementAt(0)).Type.ToDisplayString()); model.GetTypeInfo(refs.ElementAt(1)); // Assert.Equal("string", model.GetTypeInfo(refs.ElementAt(1)).Type.ToDisplayString()); var tuple = (TupleExpressionSyntax)refs.ElementAt(0).Parent.Parent; Assert.Equal("(_, _)", tuple.ToString()); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(tuple).Type.ToTestDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: @"2", sourceSymbolValidator: validator); comp.VerifyDiagnostics( // this is permitted now, as it is just an assignment expression ); } [Fact] public void UnderscoreLocalDisallowedInForEach() { var source = @" class C { static void Main() { { foreach ((var x, _) in new[] { (1, ""hello"") }) { System.Console.Write(""2 ""); } } { int _; foreach ((var y, _) in new[] { (1, ""hello"") }) { System.Console.Write(""4""); } // error } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (11,30): error CS0029: Cannot implicitly convert type 'string' to 'int' // foreach ((var y, _) in new[] { (1, "hello") }) { System.Console.Write("4"); } // error Diagnostic(ErrorCode.ERR_NoImplicitConv, "_").WithArguments("string", "int").WithLocation(11, 30), // (11,22): error CS8186: A foreach loop must declare its iteration variables. // foreach ((var y, _) in new[] { (1, "hello") }) { System.Console.Write("4"); } // error Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(var y, _)").WithLocation(11, 22), // (10,17): warning CS0168: The variable '_' is declared but never used // int _; Diagnostic(ErrorCode.WRN_UnreferencedVar, "_").WithArguments("_").WithLocation(10, 17) ); } [Fact] public void TwoDiscardsInDeconstructAssignment() { var source = @" class C { static void Main() { (_, _) = (new C(), new C()); } public C() { System.Console.Write(""C""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "CC"); } [Fact] public void VerifyDiscardIL() { var source = @" class C { C() { System.Console.Write(""ctor""); } static int Main() { var (x, _, _) = (1, new C(), 2); return x; } } "; var comp = CompileAndVerify(source, expectedOutput: "ctor"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main()", @" { // Code size 8 (0x8) .maxstack 1 IL_0000: newobj ""C..ctor()"" IL_0005: pop IL_0006: ldc.i4.1 IL_0007: ret }"); } [Fact] public void SingleDiscardInAssignment() { var source = @" class C { static void Main() { _ = M(); } public static int M() { System.Console.Write(""M""); return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "M"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardIdentifiers(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Equal("System.Int32", model.GetTypeInfo(discard1).Type.ToTestDisplayString()); } [Fact] public void SingleDiscardInAssignmentInCSharp6() { var source = @" class C { static void Error() { _ = 1; } static void Ok() { int _; _ = 1; System.Console.Write(_); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (6,9): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater. // _ = 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(6, 9) ); } [Fact] public void VariousDiscardsInCSharp6() { var source = @" class C { static void M1(out int x) { (_, var _, int _) = (1, 2, 3); var (_, _) = (1, 2); bool b = 3 is int _; switch (3) { case int _: break; } M1(out var _); M1(out int _); M1(out _); x = 2; } static void M2() { const int _ = 3; switch (3) { case _: // not a discard break; } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (6,9): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // (_, var _, int _) = (1, 2, 3); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(_, var _, int _)").WithArguments("tuples", "7.0").WithLocation(6, 9), // (6,10): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater. // (_, var _, int _) = (1, 2, 3); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(6, 10), // (6,29): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // (_, var _, int _) = (1, 2, 3); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2, 3)").WithArguments("tuples", "7.0").WithLocation(6, 29), // (7,13): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // var (_, _) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(_, _)").WithArguments("tuples", "7.0").WithLocation(7, 13), // (7,22): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // var (_, _) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2)").WithArguments("tuples", "7.0").WithLocation(7, 22), // (8,18): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // bool b = 3 is int _; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "3 is int _").WithArguments("pattern matching", "7.0").WithLocation(8, 18), // (11,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case int _: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case int _:").WithArguments("pattern matching", "7.0").WithLocation(11, 13), // (14,20): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // M1(out var _); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("out variable declaration", "7.0").WithLocation(14, 20), // (15,20): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // M1(out int _); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("out variable declaration", "7.0").WithLocation(15, 20), // (16,16): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater. // M1(out _); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(16, 16), // (24,18): warning CS8512: The name '_' refers to the constant, not the discard pattern. Use 'var _' to discard the value, or '@_' to refer to a constant by that name. // case _: // not a discard Diagnostic(ErrorCode.WRN_CaseConstantNamedUnderscore, "_").WithLocation(24, 18) ); } [Fact] public void SingleDiscardInAsyncAssignment() { var source = @" class C { async void M() { System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); // warning _ = System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); // fire-and-forget await System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); } } "; var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (6,9): warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call. // System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); Diagnostic(ErrorCode.WRN_UnobservedAwaitableExpression, "System.Threading.Tasks.Task.Delay(new System.TimeSpan(0))").WithLocation(6, 9) ); } [Fact] public void SingleDiscardInUntypedAssignment() { var source = @" class C { static void Main() { _ = null; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,9): error CS8183: Cannot infer the type of implicitly-typed discard. // _ = null; Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(6, 9) ); } [Fact] public void UnderscoreLocalInAssignment() { var source = @" class C { static void Main() { int _; _ = M(); System.Console.Write(_); } public static int M() { return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1"); } [Fact] public void DeclareAndUseLocalInDeconstruction() { var source = @" class C { static void Main() { (var x, x) = (1, 2); (y, var y) = (1, 2); } } "; var compCSharp9 = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compCSharp9.VerifyDiagnostics( // (6,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (var x, x) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(var x, x) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(6, 9), // (6,17): error CS0841: Cannot use local variable 'x' before it is declared // (var x, x) = (1, 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 17), // (7,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (y, var y) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(y, var y) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(7, 9), // (7,10): error CS0841: Cannot use local variable 'y' before it is declared // (y, var y) = (1, 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(7, 10) ); var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (6,17): error CS0841: Cannot use local variable 'x' before it is declared // (var x, x) = (1, 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 17), // (7,10): error CS0841: Cannot use local variable 'y' before it is declared // (y, var y) = (1, 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(7, 10) ); } [Fact] public void OutVarAndUsageInDeconstructAssignment() { var source = @" class C { static void Main() { (M(out var x).P, x) = (1, x); System.Console.Write(x); } static C M(out int i) { i = 42; return new C(); } int P { set { System.Console.Write($""Written {value}. ""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,26): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (M(out var x).P, x) = (1, x); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(6, 26) ); CompileAndVerify(comp, expectedOutput: "Written 1. 42"); } [Fact] public void OutDiscardInDeconstructAssignment() { var source = @" class C { static void Main() { int _; (M(out var _).P, _) = (1, 2); System.Console.Write(_); } static C M(out int i) { i = 42; return new C(); } int P { set { System.Console.Write($""Written {value}. ""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Written 1. 2"); } [Fact] public void OutDiscardInDeconstructTarget() { var source = @" class C { static void Main() { (x, _) = (M(out var x), 2); System.Console.Write(x); } static int M(out int i) { i = 42; return 3; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,10): error CS0841: Cannot use local variable 'x' before it is declared // (x, _) = (M(out var x), 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 10) ); } [Fact] public void SimpleDiscardDeconstructInScript() { var source = @" using alias = System.Int32; (string _, alias _) = (""hello"", 42); "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("string _", declaration1.ToString()); Assert.Null(model.GetDeclaredSymbol(declaration1)); Assert.Null(model.GetDeclaredSymbol(discard1)); var discard2 = GetDiscardDesignations(tree).ElementAt(1); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("alias _", declaration2.ToString()); Assert.Null(model.GetDeclaredSymbol(declaration2)); Assert.Null(model.GetDeclaredSymbol(discard2)); var tuple = (TupleExpressionSyntax)declaration1.Parent.Parent; Assert.Equal("(string _, alias _)", tuple.ToString()); Assert.Equal("(System.String, System.Int32)", model.GetTypeInfo(tuple).Type.ToTestDisplayString()); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, sourceSymbolValidator: validator); } [Fact] public void SimpleDiscardDeconstructInScript2() { var source = @" public class C { public C() { System.Console.Write(""ctor""); } public void Deconstruct(out string x, out string y) { x = y = null; } } (string _, string _) = new C(); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "ctor"); } [Fact] public void SingleDiscardInAssignmentInScript() { var source = @" int M() { System.Console.Write(""M""); return 1; } _ = M(); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "M"); } [Fact] public void NestedVarDiscardDeconstructionInScript() { var source = @" (var _, var (_, x3)) = (""hello"", (42, 43)); System.Console.Write($""{x3}""); "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var discard2 = GetDiscardDesignations(tree).ElementAt(1); var nestedDeclaration = (DeclarationExpressionSyntax)discard2.Parent.Parent; Assert.Equal("var (_, x3)", nestedDeclaration.ToString()); Assert.Null(model.GetDeclaredSymbol(nestedDeclaration)); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Equal("(System.Int32, System.Int32 x3)", model.GetTypeInfo(nestedDeclaration).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(nestedDeclaration).Symbol); var tuple = (TupleExpressionSyntax)discard2.Parent.Parent.Parent.Parent; Assert.Equal("(var _, var (_, x3))", tuple.ToString()); Assert.Equal("(System.String, (System.Int32, System.Int32 x3))", model.GetTypeInfo(tuple).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(tuple).Symbol); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "43", sourceSymbolValidator: validator); } [Fact] public void VariousDiscardsInForeach() { var source = @" class C { static void Main() { foreach ((var _, int _, _, var (_, _), int x) in new[] { (1L, 2, 3, (""hello"", 5), 6) }) { System.Console.Write(x); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "6"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.True(model.GetSymbolInfo(discard1).IsEmpty); Assert.Null(model.GetTypeInfo(discard1).Type); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("var _", declaration1.ToString()); Assert.Equal("System.Int64", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); var discard2 = GetDiscardDesignations(tree).ElementAt(1); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.True(model.GetSymbolInfo(discard2).IsEmpty); Assert.Null(model.GetTypeInfo(discard2).Type); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("int _", declaration2.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); var discard3 = GetDiscardIdentifiers(tree).First(); Assert.Equal("_", discard3.Parent.ToString()); Assert.Null(model.GetDeclaredSymbol(discard3)); Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString()); Assert.Equal("int _", model.GetSymbolInfo(discard3).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol; Assert.Equal("System.Int32", discard3Symbol.Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString()); var discard4 = GetDiscardDesignations(tree).ElementAt(2); Assert.Null(model.GetDeclaredSymbol(discard4)); Assert.True(model.GetSymbolInfo(discard4).IsEmpty); Assert.Null(model.GetTypeInfo(discard4).Type); var nestedDeclaration = (DeclarationExpressionSyntax)discard4.Parent.Parent; Assert.Equal("var (_, _)", nestedDeclaration.ToString()); Assert.Equal("(System.String, System.Int32)", model.GetTypeInfo(nestedDeclaration).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(nestedDeclaration).Symbol); } [Fact] public void UnderscoreInCSharp6Foreach() { var source = @" class C { static void Main() { foreach (var _ in M()) { System.Console.Write(_); } } static System.Collections.Generic.IEnumerable<int> M() { System.Console.Write(""M ""); yield return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "M 1"); } [Fact] public void ShortDiscardDisallowedInForeach() { var source = @" class C { static void Main() { foreach (_ in M()) { } } static System.Collections.Generic.IEnumerable<int> M() { yield return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,18): error CS8186: A foreach loop must declare its iteration variables. // foreach (_ in M()) Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "_").WithLocation(6, 18) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var discard = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().First(); var symbol = (DiscardSymbol)model.GetSymbolInfo(discard).Symbol.GetSymbol(); Assert.True(symbol.TypeWithAnnotations.Type.IsErrorType()); } [Fact] public void ExistingUnderscoreLocalInLegacyForeach() { var source = @" class C { static void Main() { int _; foreach (var _ in new[] { 1 }) { } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,22): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var _ in new[] { 1 }) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "_").WithArguments("_").WithLocation(7, 22), // (6,13): warning CS0168: The variable '_' is declared but never used // int _; Diagnostic(ErrorCode.WRN_UnreferencedVar, "_").WithArguments("_").WithLocation(6, 13) ); } [Fact] public void MixedDeconstruction_01() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); var x = (int x1, int x2) = t; System.Console.WriteLine(x1); System.Console.WriteLine(x2); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (7,18): error CS8185: A declaration is not allowed in this context. // var x = (int x1, int x2) = t; Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(7, 18) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); } [Fact] public void MixedDeconstruction_02() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); int z; (int x1, z) = t; System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "1") .VerifyIL("Program.Main", @" { // Code size 32 (0x20) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0, //t int V_1, //z int V_2) //x1 IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: ldloc.0 IL_000b: dup IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0011: stloc.2 IL_0012: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0017: stloc.1 IL_0018: ldloc.2 IL_0019: call ""void System.Console.WriteLine(int)"" IL_001e: nop IL_001f: ret }"); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); } [Fact] public void MixedDeconstruction_03() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); int z; for ((int x1, z) = t; ; ) { System.Console.WriteLine(x1); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "1") .VerifyIL("Program.Main", @" { // Code size 39 (0x27) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0, //t int V_1, //z int V_2) //x1 IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: ldloc.0 IL_000b: dup IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0011: stloc.2 IL_0012: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0017: stloc.1 IL_0018: br.s IL_0024 IL_001a: nop IL_001b: ldloc.2 IL_001c: call ""void System.Console.WriteLine(int)"" IL_0021: nop IL_0022: br.s IL_0026 IL_0024: br.s IL_001a IL_0026: ret }"); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var symbolInfo = model.GetSymbolInfo(x1Ref); Assert.Equal(symbolInfo.Symbol, model.GetDeclaredSymbol(x1)); Assert.Equal(SpecialType.System_Int32, symbolInfo.Symbol.GetTypeOrReturnType().SpecialType); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(int x1, z)", lhs.ToString()); Assert.Equal("(System.Int32 x1, System.Int32 z)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x1, System.Int32 z)", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); } [Fact] public void MixedDeconstruction_03CSharp9() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); int z; for ((int x1, z) = t; ; ) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (8,14): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // for ((int x1, z) = t; ; ) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x1, z) = t").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(8, 14)); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); } [Fact] public void MixedDeconstruction_04() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); for (; ; (int x1, int x2) = t) { System.Console.WriteLine(x1); System.Console.WriteLine(x2); } } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8185: A declaration is not allowed in this context. // for (; ; (int x1, int x2) = t) Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(7, 19), // (9,38): error CS0103: The name 'x1' does not exist in the current context // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(9, 38), // (10,38): error CS0103: The name 'x2' does not exist in the current context // System.Console.WriteLine(x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(10, 38) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1); var symbolInfo = model.GetSymbolInfo(x1Ref); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2); symbolInfo = model.GetSymbolInfo(x2Ref); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); } [Fact] public void MixedDeconstruction_05() { string source = @" class Program { static void Main(string[] args) { foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) }) { System.Console.WriteLine(x1); System.Console.WriteLine(x2); } } static int _M; static ref int M(out int x) { x = 2; return ref _M; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,34): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) }) Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "args is var x2").WithLocation(6, 34), // (6,34): error CS0029: Cannot implicitly convert type 'int' to 'bool' // foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) }) Diagnostic(ErrorCode.ERR_NoImplicitConv, "args is var x2").WithArguments("int", "bool").WithLocation(6, 34), // (6,18): error CS8186: A foreach loop must declare its iteration variables. // foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) }) Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(M(out var x1), args is var x2, _)").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString()); model = compilation.GetSemanticModel(tree); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); Assert.Equal("string[]", model.GetTypeInfo(x2Ref).Type.ToDisplayString()); VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref); VerifyModelForLocal(model, x2, LocalDeclarationKind.PatternVariable, x2Ref); } [Fact] public void ForeachIntoExpression() { string source = @" class Program { static void Main(string[] args) { foreach (M(out var x1) in new[] { 1, 2, 3 }) { System.Console.WriteLine(x1); } } static int _M; static ref int M(out int x) { x = 2; return ref _M; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,32): error CS0230: Type and identifier are both required in a foreach statement // foreach (M(out var x1) in new[] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 32) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString()); VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref); } [Fact] public void MixedDeconstruction_06() { string source = @" class Program { static void Main(string[] args) { foreach (M1(M2(out var x1, args is var x2), x1, x2) in new[] {1, 2, 3}) { System.Console.WriteLine(x1); System.Console.WriteLine(x2); } } static int _M; static ref int M1(int m2, int x, string[] y) { return ref _M; } static int M2(out int x, bool b) => x = 2; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,61): error CS0230: Type and identifier are both required in a foreach statement // foreach (M1(M2(out var x1, args is var x2), x1, x2) in new[] {1, 2, 3}) Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 61) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReferences(tree, "x1"); Assert.Equal("int", model.GetTypeInfo(x1Ref.First()).Type.ToDisplayString()); model = compilation.GetSemanticModel(tree); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReferences(tree, "x2"); Assert.Equal("string[]", model.GetTypeInfo(x2Ref.First()).Type.ToDisplayString()); VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref.ToArray()); VerifyModelForLocal(model, x2, LocalDeclarationKind.PatternVariable, x2Ref.ToArray()); } [Fact] public void MixedDeconstruction_07() { string source = @" class Program { static void Main(string[] args) { var t = (1, ("""", true)); string y; for ((int x, (y, var z)) = t; ; ) { System.Console.Write(x); System.Console.Write(z); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation, expectedOutput: "1True") .VerifyIL("Program.Main", @" { // Code size 73 (0x49) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<string, bool>> V_0, //t string V_1, //y int V_2, //x bool V_3, //z System.ValueTuple<string, bool> V_4) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldstr """" IL_0009: ldc.i4.1 IL_000a: newobj ""System.ValueTuple<string, bool>..ctor(string, bool)"" IL_000f: call ""System.ValueTuple<int, System.ValueTuple<string, bool>>..ctor(int, System.ValueTuple<string, bool>)"" IL_0014: ldloc.0 IL_0015: dup IL_0016: ldfld ""System.ValueTuple<string, bool> System.ValueTuple<int, System.ValueTuple<string, bool>>.Item2"" IL_001b: stloc.s V_4 IL_001d: ldfld ""int System.ValueTuple<int, System.ValueTuple<string, bool>>.Item1"" IL_0022: stloc.2 IL_0023: ldloc.s V_4 IL_0025: ldfld ""string System.ValueTuple<string, bool>.Item1"" IL_002a: stloc.1 IL_002b: ldloc.s V_4 IL_002d: ldfld ""bool System.ValueTuple<string, bool>.Item2"" IL_0032: stloc.3 IL_0033: br.s IL_0046 IL_0035: nop IL_0036: ldloc.2 IL_0037: call ""void System.Console.Write(int)"" IL_003c: nop IL_003d: ldloc.3 IL_003e: call ""void System.Console.Write(bool)"" IL_0043: nop IL_0044: br.s IL_0048 IL_0046: br.s IL_0035 IL_0048: ret }"); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xRef = GetReference(tree, "x"); VerifyModelForDeconstructionLocal(model, x, xRef); var xSymbolInfo = model.GetSymbolInfo(xRef); Assert.Equal(xSymbolInfo.Symbol, model.GetDeclaredSymbol(x)); Assert.Equal(SpecialType.System_Int32, xSymbolInfo.Symbol.GetTypeOrReturnType().SpecialType); var z = GetDeconstructionVariable(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForDeconstructionLocal(model, z, zRef); var zSymbolInfo = model.GetSymbolInfo(zRef); Assert.Equal(zSymbolInfo.Symbol, model.GetDeclaredSymbol(z)); Assert.Equal(SpecialType.System_Boolean, zSymbolInfo.Symbol.GetTypeOrReturnType().SpecialType); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(2); Assert.Equal(@"(int x, (y, var z))", lhs.ToString()); Assert.Equal("(System.Int32 x, (System.String y, System.Boolean z))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x, (System.String y, System.Boolean z))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); } [Fact] public void IncompleteDeclarationIsSeenAsTupleLiteral() { string source = @" class C { static void Main() { (int x1, string x2); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,10): error CS8185: A declaration is not allowed in this context. // (int x1, string x2); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 10), // (6,18): error CS8185: A declaration is not allowed in this context. // (int x1, string x2); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "string x2").WithLocation(6, 18), // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (int x1, string x2); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x1, string x2)").WithLocation(6, 9), // (6,10): error CS0165: Use of unassigned local variable 'x1' // (int x1, string x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 10), // (6,18): error CS0165: Use of unassigned local variable 'x2' // (int x1, string x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "string x2").WithArguments("x2").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString()); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); Assert.Equal("string", model.GetTypeInfo(x2Ref).Type.ToDisplayString()); VerifyModelForDeconstruction(model, x1, LocalDeclarationKind.DeclarationExpressionVariable, x1Ref); VerifyModelForDeconstruction(model, x2, LocalDeclarationKind.DeclarationExpressionVariable, x2Ref); } [Fact] [WorkItem(15893, "https://github.com/dotnet/roslyn/issues/15893")] public void DeconstructionOfOnlyOneElement() { string source = @" class C { static void Main() { var (p2) = (1, 2); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,16): error CS1003: Syntax error, ',' expected // var (p2) = (1, 2); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(",", ")").WithLocation(6, 16), // (6,16): error CS1001: Identifier expected // var (p2) = (1, 2); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(6, 16) ); } [Fact] [WorkItem(14876, "https://github.com/dotnet/roslyn/issues/14876")] public void TupleTypeInDeconstruction() { string source = @" class C { static void Main() { (int x, (string, long) y) = M(); System.Console.Write($""{x} {y}""); } static (int, (string, long)) M() { return (5, (""Goo"", 34983490)); } } "; var comp = CompileAndVerify(source, expectedOutput: "5 (Goo, 34983490)"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(12468, "https://github.com/dotnet/roslyn/issues/12468")] public void RefReturningVarInvocation() { string source = @" class C { static int i; static void Main() { int x = 0, y = 0; (var(x, y)) = 42; // parsed as invocation System.Console.Write(i); } static ref int var(int a, int b) { return ref i; } } "; var comp = CompileAndVerify(source, expectedOutput: "42", verify: Verification.Passes); comp.VerifyDiagnostics(); } [Fact] void InvokeVarForLvalueInParens() { var source = @" class Program { public static void Main() { (var(x, y)) = 10; System.Console.WriteLine(z); } static int x = 1, y = 2, z = 3; static ref int var(int x, int y) { return ref z; } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); // PEVerify fails with ref return https://github.com/dotnet/roslyn/issues/12285 CompileAndVerify(compilation, expectedOutput: "10", verify: Verification.Fails); } [Fact] [WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")] public void DefAssignmentsStruct001() { string source = @" using System.Collections.Generic; public class MyClass { public static void Main() { ((int, int), string)[] arr = new((int, int), string)[1]; Test5(arr); } public static void Test4(IEnumerable<(KeyValuePair<int, int>, string)> en) { foreach ((KeyValuePair<int, int> kv, string s) in en) { var a = kv.Key; // false error CS0170: Use of possibly unassigned field } } public static void Test5(IEnumerable<((int, int), string)> en) { foreach (((int, int k) t, string s) in en) { var a = t.k; // false error CS0170: Use of possibly unassigned field System.Console.WriteLine(a); } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "0"); } [Fact] [WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")] public void DefAssignmentsStruct002() { string source = @" public class MyClass { public static void Main() { var data = new int[10]; var arr = new int[2]; foreach (arr[out int size] in data) {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,36): error CS0230: Type and identifier are both required in a foreach statement // foreach (arr[out int size] in data) {} Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(9, 36) ); } [Fact] [WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")] public void DefAssignmentsStruct003() { string source = @" public class MyClass { public static void Main() { var data = new (int, int)[10]; var arr = new int[2]; foreach ((arr[out int size], int b) in data) {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,27): error CS1615: Argument 1 may not be passed with the 'out' keyword // foreach ((arr[out int size], int b) in data) {} Diagnostic(ErrorCode.ERR_BadArgExtraRef, "int size").WithArguments("1", "out").WithLocation(9, 27), // (9,18): error CS8186: A foreach loop must declare its iteration variables. // foreach ((arr[out int size], int b) in data) {} Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(arr[out int size], int b)").WithLocation(9, 18) ); } [Fact] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_01() { string source = @" class C { static event System.Action E; static void Main() { (E, _) = (null, 1); System.Console.WriteLine(E == null); (E, _) = (Handler, 1); E(); } static void Handler() { System.Console.WriteLine(""Handler""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"True Handler"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_02() { string source = @" struct S { event System.Action E; class C { static void Main() { var s = new S(); (s.E, _) = (null, 1); System.Console.WriteLine(s.E == null); (s.E, _) = (Handler, 1); s.E(); } static void Handler() { System.Console.WriteLine(""Handler""); } } } "; var comp = CompileAndVerify(source, expectedOutput: @"True Handler"); comp.VerifyDiagnostics(); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.WinRTNeedsWindowsDesktop)] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_03() { string source1 = @" public interface EventInterface { event System.Action E; } "; var comp1 = CreateEmptyCompilation(source1, WinRtRefs, TestOptions.ReleaseWinMD, TestOptions.Regular); string source2 = @" class C : EventInterface { public event System.Action E; static void Main() { var c = new C(); c.Test(); } void Test() { (E, _) = (null, 1); System.Console.WriteLine(E == null); (E, _) = (Handler, 1); E(); } static void Handler() { System.Console.WriteLine(""Handler""); } } "; var comp2 = CompileAndVerify(source2, targetFramework: TargetFramework.Empty, expectedOutput: @"True Handler", references: WinRtRefs.Concat(new[] { ValueTupleRef, comp1.ToMetadataReference() })); comp2.VerifyDiagnostics(); Assert.True(comp2.Compilation.GetMember<IEventSymbol>("C.E").IsWindowsRuntimeEvent); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.WinRTNeedsWindowsDesktop)] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_04() { string source1 = @" public interface EventInterface { event System.Action E; } "; var comp1 = CreateEmptyCompilation(source1, WinRtRefs, TestOptions.ReleaseWinMD, TestOptions.Regular); string source2 = @" struct S : EventInterface { public event System.Action E; class C { S s = new S(); static void Main() { var c = new C(); (GetC(c).s.E, _) = (null, GetInt(1)); System.Console.WriteLine(c.s.E == null); (GetC(c).s.E, _) = (Handler, GetInt(2)); c.s.E(); } static int GetInt(int i) { System.Console.WriteLine(i); return i; } static C GetC(C c) { System.Console.WriteLine(""GetC""); return c; } static void Handler() { System.Console.WriteLine(""Handler""); } } } "; var comp2 = CompileAndVerify(source2, targetFramework: TargetFramework.Empty, expectedOutput: @"GetC 1 True GetC 2 Handler", references: WinRtRefs.Concat(new[] { ValueTupleRef, comp1.ToMetadataReference() })); comp2.VerifyDiagnostics(); Assert.True(comp2.Compilation.GetMember<IEventSymbol>("S.E").IsWindowsRuntimeEvent); } [Fact] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_05() { string source = @" class C { public static event System.Action E; } class Program { static void Main() { (C.E, _) = (null, 1); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,12): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // (C.E, _) = (null, 1); Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(11, 12) ); } [Fact] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_06() { string source = @" class C { static event System.Action E { add {} remove {} } static void Main() { (E, _) = (null, 1); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (12,10): error CS0079: The event 'C.E' can only appear on the left hand side of += or -= // (E, _) = (null, 1); Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "E").WithArguments("C.E").WithLocation(12, 10) ); } [Fact] public void SimpleAssignInConstructor() { string source = @" public class C { public long x; public string y; public C(int a, string b) => (x, y) = (a, b); public static void Main() { var c = new C(1, ""hello""); System.Console.WriteLine(c.x + "" "" + c.y); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C..ctor(int, string)", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (long V_0, string V_1) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.1 IL_0007: conv.i8 IL_0008: stloc.0 IL_0009: ldarg.2 IL_000a: stloc.1 IL_000b: ldarg.0 IL_000c: ldloc.0 IL_000d: stfld ""long C.x"" IL_0012: ldarg.0 IL_0013: ldloc.1 IL_0014: stfld ""string C.y"" IL_0019: ret }"); } [Fact] public void DeconstructAssignInConstructor() { string source = @" public class C { public long x; public string y; public C(C oldC) => (x, y) = oldC; public C() { } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } public static void Main() { var oldC = new C() { x = 1, y = ""hello"" }; var newC = new C(oldC); System.Console.WriteLine(newC.x + "" "" + newC.y); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C..ctor(C)", @" { // Code size 34 (0x22) .maxstack 3 .locals init (int V_0, string V_1, long V_2) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.1 IL_0007: ldloca.s V_0 IL_0009: ldloca.s V_1 IL_000b: callvirt ""void C.Deconstruct(out int, out string)"" IL_0010: ldloc.0 IL_0011: conv.i8 IL_0012: stloc.2 IL_0013: ldarg.0 IL_0014: ldloc.2 IL_0015: stfld ""long C.x"" IL_001a: ldarg.0 IL_001b: ldloc.1 IL_001c: stfld ""string C.y"" IL_0021: ret }"); } [Fact] public void AssignInConstructorWithProperties() { string source = @" public class C { public long X { get; set; } public string Y { get; } private int z; public ref int Z { get { return ref z; } } public C(int a, string b, ref int c) => (X, Y, Z) = (a, b, c); public static void Main() { int number = 2; var c = new C(1, ""hello"", ref number); System.Console.WriteLine($""{c.X} {c.Y} {c.Z}""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello 2"); comp.VerifyDiagnostics(); comp.VerifyIL("C..ctor(int, string, ref int)", @" { // Code size 39 (0x27) .maxstack 4 .locals init (long V_0, string V_1, int V_2, long V_3) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: call ""ref int C.Z.get"" IL_000c: ldarg.1 IL_000d: conv.i8 IL_000e: stloc.0 IL_000f: ldarg.2 IL_0010: stloc.1 IL_0011: ldarg.3 IL_0012: ldind.i4 IL_0013: stloc.2 IL_0014: ldarg.0 IL_0015: ldloc.0 IL_0016: dup IL_0017: stloc.3 IL_0018: call ""void C.X.set"" IL_001d: ldarg.0 IL_001e: ldloc.1 IL_001f: stfld ""string C.<Y>k__BackingField"" IL_0024: ldloc.2 IL_0025: stind.i4 IL_0026: ret }"); } [Fact] public void VerifyDeconstructionInAsync() { var source = @" using System.Threading.Tasks; class C { static void Main() { System.Console.Write(C.M().Result); } static async Task<int> M() { await Task.Delay(0); var (x, y) = (1, 2); return x + y; } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void DeconstructionWarnsForSelfAssignment() { var source = @" class C { object x = 1; static object y = 2; void M() { ((x, x), this.x, C.y) = ((x, (1, 2)), x, y); } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,11): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ((x, x), this.x, C.y) = ((x, (1, 2)), x, y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(8, 11), // (8,18): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ((x, x), this.x, C.y) = ((x, (1, 2)), x, y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "this.x").WithLocation(8, 18), // (8,26): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ((x, x), this.x, C.y) = ((x, (1, 2)), x, y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "C.y").WithLocation(8, 26) ); } [Fact] public void DeconstructionWarnsForSelfAssignment2() { var source = @" class C { object x = 1; static object y = 2; void M() { object z = 3; (x, (y, z)) = (x, (y, z)); } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (9,10): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, (y, z)) = (x, (y, z)); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x"), // (9,14): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, (y, z)) = (x, (y, z)); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "y").WithLocation(9, 14), // (9,17): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, (y, z)) = (x, (y, z)); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "z").WithLocation(9, 17) ); } [Fact] public void DeconstructionWarnsForSelfAssignment_WithUserDefinedConversionOnElement() { var source = @" class C { object x = 1; static C y = null; void M() { (x, y) = (x, (C)(D)y); } public static implicit operator C(D d) => null; } class D { public static implicit operator D(C c) => null; } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,10): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, y) = (x, (C)(D)y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(8, 10) ); } [Fact] public void DeconstructionWarnsForSelfAssignment_WithNestedConversions() { var source = @" class C { object x = 1; int y = 2; byte b = 3; void M() { // The conversions on the right-hand-side: // - a deconstruction conversion // - an implicit tuple literal conversion on the entire right-hand-side // - another implicit tuple literal conversion on the nested tuple // - a conversion on element `b` (_, (x, y)) = (1, (x, b)); } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (14,14): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (_, (x, y)) = (1, (x, b)); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(14, 14) ); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DeconstructionWarnsForSelfAssignment_WithExplicitTupleConversion() { var source = @" class C { int y = 2; byte b = 3; void M() { // The conversions on the right-hand-side: // - a deconstruction conversion on the entire right-hand-side // - an identity conversion as its operand // - an explicit tuple literal conversion as its operand (y, _) = ((int, int))(y, b); } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( ); var tree = comp.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); Assert.Equal("((int, int))(y, b)", node.ToString()); comp.VerifyOperationTree(node, expectedOperationTree: @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(y, b)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32 y, System.Int32 b)) (Syntax: '(y, b)') NaturalType: (System.Int32 y, System.Byte b) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Int32 C.y (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'y') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Byte C.b (OperationKind.FieldReference, Type: System.Byte) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'b') "); } [Fact] public void DeconstructionWarnsForSelfAssignment_WithDeconstruct() { var source = @" class C { object x = 1; static object y = 2; void M() { object z = 3; (x, (y, z)) = (x, y); } } static class Extensions { public static void Deconstruct(this object input, out object output1, out object output2) { output1 = input; output2 = input; } }"; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (9,10): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, (y, z)) = (x, y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(9, 10) ); } [Fact] public void TestDeconstructOnErrorType() { var source = @" class C { Error M() { int x, y; (x, y) = M(); throw null; } }"; var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); // no ValueTuple reference comp.VerifyDiagnostics( // (4,5): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // Error M() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 5) ); } [Fact] public void TestDeconstructOnErrorTypeFromImageReference() { var missing_cs = "public class Missing { }"; var missing = CreateCompilationWithMscorlib45(missing_cs, options: TestOptions.DebugDll, assemblyName: "missing"); var lib_cs = "public class C { public Missing M() { throw null; } }"; var lib = CreateCompilationWithMscorlib45(lib_cs, references: new[] { missing.EmitToImageReference() }, options: TestOptions.DebugDll); var source = @" class D { void M() { int x, y; (x, y) = new C().M(); throw null; } }"; var comp = CreateCompilationWithMscorlib45(source, references: new[] { lib.EmitToImageReference() }, options: TestOptions.DebugDll); // no ValueTuple reference comp.VerifyDiagnostics( // (7,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (x, y) = new C().M(); Diagnostic(ErrorCode.ERR_NoTypeDef, "new C().M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18) ); } [Fact] public void TestDeconstructOnErrorTypeFromCompilationReference() { var missing_cs = "public class Missing { }"; var missing = CreateCompilationWithMscorlib45(missing_cs, options: TestOptions.DebugDll, assemblyName: "missing"); var lib_cs = "public class C { public Missing M() { throw null; } }"; var lib = CreateCompilationWithMscorlib45(lib_cs, references: new[] { missing.ToMetadataReference() }, options: TestOptions.DebugDll); var source = @" class D { void M() { int x, y; (x, y) = new C().M(); throw null; } }"; var comp = CreateCompilationWithMscorlib45(source, references: new[] { lib.ToMetadataReference() }, options: TestOptions.DebugDll); // no ValueTuple reference comp.VerifyDiagnostics( // (7,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (x, y) = new C().M(); Diagnostic(ErrorCode.ERR_NoTypeDef, "new C().M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18) ); } [Fact, WorkItem(17756, "https://github.com/dotnet/roslyn/issues/17756")] public void TestDiscardedAssignmentNotLvalue() { var source = @" class Program { struct S1 { public int field; public int Increment() => field++; } static void Main() { S1 v = default(S1); v.Increment(); (_ = v).Increment(); System.Console.WriteLine(v.field); } } "; string expectedOutput = @"1"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void TupleCastInDeconstruction() { var source = @" class C { static void Main() { var t = (1, 2); var (a, b) = ((byte, byte))t; System.Console.Write($""{a} {b}""); } }"; CompileAndVerify(source, expectedOutput: @"1 2"); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void TupleCastInDeconstruction2() { var source = @" class C { static void Main() { var t = (new C(), new D()); var (a, _) = ((byte, byte))t; System.Console.Write($""{a}""); } public static explicit operator byte(C c) { System.Console.Write(""Convert ""); return 1; } } class D { public static explicit operator byte(D c) { System.Console.Write(""Convert2 ""); return 2; } }"; CompileAndVerify(source, expectedOutput: @"Convert Convert2 1"); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void TupleCastInDeconstruction3() { var source = @" class C { static int A { set { System.Console.Write(""A ""); } } static int B { set { System.Console.Write(""B""); } } static void Main() { (A, B) = ((byte, byte))(new C(), new D()); } public static explicit operator byte(C c) { System.Console.Write(""Convert ""); return 1; } public C() { System.Console.Write(""C ""); } } class D { public static explicit operator byte(D c) { System.Console.Write(""Convert2 ""); return 2; } public D() { System.Console.Write(""D ""); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"C Convert D Convert2 A B").Compilation; var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); Assert.Equal("((byte, byte))(new C(), new D())", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Byte, System.Byte)) (Syntax: '((byte, byt ... ), new D())') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Byte, System.Byte)) (Syntax: '(new C(), new D())') NaturalType: (C, D) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Byte C.op_Explicit(C c)) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'new C()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Byte C.op_Explicit(C c)) Operand: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Byte D.op_Explicit(D c)) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'new D()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Byte D.op_Explicit(D c)) Operand: IObjectCreationOperation (Constructor: D..ctor()) (OperationKind.ObjectCreation, Type: D) (Syntax: 'new D()') Arguments(0) Initializer: null "); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void TupleCastInDeconstruction4() { var source = @" class C { static void Main() { var (a, _) = ((short, short))((int, int))(1L, 2L); System.Console.Write($""{a}""); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1").Compilation; var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().ElementAt(1); Assert.Equal("((int, int))(1L, 2L)", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(1L, 2L)') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1L, 2L)') NaturalType: (System.Int64, System.Int64) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 1) (Syntax: '1L') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 2) (Syntax: '2L') "); Assert.Equal("((short, short))((int, int))(1L, 2L)", node.Parent.ToString()); compilation.VerifyOperationTree(node.Parent, expectedOperationTree: @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int16, System.Int16)) (Syntax: '((short, sh ... t))(1L, 2L)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(1L, 2L)') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1L, 2L)') NaturalType: (System.Int64, System.Int64) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 1) (Syntax: '1L') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 2) (Syntax: '2L') "); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void UserDefinedCastInDeconstruction() { var source = @" class C { static void Main() { var c = new C(); var (a, b) = ((byte, byte))c; System.Console.Write($""{a} {b}""); } public static explicit operator (byte, byte)(C c) { return (3, 4); } }"; CompileAndVerify(source, expectedOutput: @"3 4"); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void DeconstructionLoweredToNothing() { var source = @" class C { static void M() { for (var(_, _) = (1, 2); ; (_, _) = (3, 4)) { } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("C.M", @" { // Code size 2 (0x2) .maxstack 0 IL_0000: br.s IL_0000 }"); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void DeconstructionLoweredToNothing2() { var source = @" class C { static void M() { (_, _) = (1, 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("C.M", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void DeconstructionLoweredToNothing3() { var source = @" class C { static void Main() { foreach (var(_, _) in new[] { (1, 2) }) { System.Console.Write(""once""); } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "once"); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName() { var source = @"class C { static void Main() { int x = 0, y = 1; var t = (x, y); var (a, b) = t; } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName_ConditionalOperator() { var source = @"class C { static void M(int a, int b, bool c) { (var x, var y) = c ? (a, default(object)) : (b, null); (x, y) = c ? (a, default(string)) : (b, default(object)); } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName_ImplicitArray() { var source = @"class C { static void M(int x) { int y; object z; (y, z) = (new [] { (x, default(object)), (2, 3) })[0]; } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")] public void InferredName_Lambda() { // See https://github.com/dotnet/roslyn/issues/32006 // need to relax assertion in GetImplicitTupleLiteralConversion var source = @"class C { static T F<T>(System.Func<object, bool, T> f) { return f(null, false); } static void M() { var (x, y) = F((a, b) => { if (b) return (default(object), a); return (null, null); }); } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName_ConditionalOperator_LongTuple() { var source = @"class C { static void M(object a, object b, bool c) { var (_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) = c ? (1, 2, 3, 4, 5, 6, 7, a, b, 10) : (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName_ConditionalOperator_UseSite() { var source = @"class C { static void M(int a, int b, bool c) { var (x, y) = c ? ((object)1, a) : (b, 2); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; private T2 Item2; public ValueTuple(T1 item1, T2 item2) => throw null; } }"; var expected = new[] { // (12,19): warning CS0649: Field '(T1, T2).Item1' is never assigned to, and will always have its default value // public T1 Item1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Item1").WithArguments("(T1, T2).Item1", "").WithLocation(12, 19), // (13,20): warning CS0169: The field '(T1, T2).Item2' is never used // private T2 Item2; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item2").WithArguments("(T1, T2).Item2").WithLocation(13, 20) }; // C# 7.0 var comp = CreateCompilation( source, assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(expected); // C# 7.1 comp = CreateCompilation( source, assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(expected); } [Fact] public void InferredName_ConditionalOperator_UseSite_AccessingWithinConstructor() { var source = @"class C { static void M(int a, int b, bool c) { var (x, y) = c ? ((object)1, a) : (b, 2); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; private T2 Item2; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } }"; var expected = new[] { // (13,20): warning CS0169: The field '(T1, T2).Item2' is never used // private T2 Item2; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item2").WithArguments("(T1, T2).Item2").WithLocation(13, 20), // (14,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(14, 16), // (14,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(14, 16), // (17,13): error CS0229: Ambiguity between '(T1, T2).Item2' and '(T1, T2).Item2' // Item2 = item2; Diagnostic(ErrorCode.ERR_AmbigMember, "Item2").WithArguments("(T1, T2).Item2", "(T1, T2).Item2").WithLocation(17, 13) }; // C# 7.0 var comp = CreateCompilation( source, assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(expected); // C# 7.1 comp = CreateCompilation( source, assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(expected); } [Fact] public void TestGetDeconstructionInfoOnIncompleteCode() { string source = @" class C { void M() { var (y1, y2) =} void Deconstruct(out int x1, out int x2) { x1 = 1; x2 = 2; } } "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First(); Assert.Equal("var (y1, y2) =", node.ToString()); var info = model.GetDeconstructionInfo(node); Assert.Null(info.Method); Assert.Empty(info.Nested); } [Fact] public void TestDeconstructStructThis() { string source = @" public struct S { int I; public static void Main() { S s = new S(); s.M(); } public void M() { this.I = 42; var (x, (y, z)) = (this, this /* mutating deconstruction */); System.Console.Write($""{x.I} {y} {z}""); } void Deconstruct(out int x1, out int x2) { x1 = I++; x2 = I++; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "42 42 43"); } [Fact] public void TestDeconstructClassThis() { string source = @" public class C { int I; public static void Main() { C c = new C(); c.M(); } public void M() { this.I = 42; var (x, (y, z)) = (this, this /* mutating deconstruction */); System.Console.Write($""{x.I} {y} {z}""); } void Deconstruct(out int x1, out int x2) { x1 = I++; x2 = I++; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "44 42 43"); } [Fact] public void AssigningConditional_OutParams() { string source = @" using System; class C { static void Main() { Test(true, false); Test(false, true); Test(false, false); } static void Test(bool b1, bool b2) { M(out int x, out int y, b1, b2); Console.Write(x); Console.Write(y); } static void M(out int x, out int y, bool b1, bool b2) { (x, y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); } } "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 33 (0x21) .maxstack 2 IL_0000: ldarg.2 IL_0001: brtrue.s IL_0018 IL_0003: ldarg.3 IL_0004: brtrue.s IL_000f IL_0006: ldarg.0 IL_0007: ldc.i4.s 50 IL_0009: stind.i4 IL_000a: ldarg.1 IL_000b: ldc.i4.s 60 IL_000d: stind.i4 IL_000e: ret IL_000f: ldarg.0 IL_0010: ldc.i4.s 30 IL_0012: stind.i4 IL_0013: ldarg.1 IL_0014: ldc.i4.s 40 IL_0016: stind.i4 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.s 10 IL_001b: stind.i4 IL_001c: ldarg.1 IL_001d: ldc.i4.s 20 IL_001f: stind.i4 IL_0020: ret }"); } [Fact] public void AssigningConditional_VarDeconstruction() { string source = @" using System; class C { static void Main() { M(true, false); M(false, true); M(false, false); } static void M(bool b1, bool b2) { var (x, y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); Console.Write(x); Console.Write(y); } } "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 41 (0x29) .maxstack 1 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: brtrue.s IL_0016 IL_0003: ldarg.1 IL_0004: brtrue.s IL_000e IL_0006: ldc.i4.s 50 IL_0008: stloc.0 IL_0009: ldc.i4.s 60 IL_000b: stloc.1 IL_000c: br.s IL_001c IL_000e: ldc.i4.s 30 IL_0010: stloc.0 IL_0011: ldc.i4.s 40 IL_0013: stloc.1 IL_0014: br.s IL_001c IL_0016: ldc.i4.s 10 IL_0018: stloc.0 IL_0019: ldc.i4.s 20 IL_001b: stloc.1 IL_001c: ldloc.0 IL_001d: call ""void System.Console.Write(int)"" IL_0022: ldloc.1 IL_0023: call ""void System.Console.Write(int)"" IL_0028: ret }"); } [Fact] public void AssigningConditional_MixedDeconstruction() { string source = @" using System; class C { static void Main() { M(true, false); M(false, true); M(false, false); } static void M(bool b1, bool b2) { (var x, long y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); Console.Write(x); Console.Write(y); } } "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 50 (0x32) .maxstack 1 .locals init (int V_0, //x long V_1, //y long V_2) IL_0000: ldarg.0 IL_0001: brtrue.s IL_001c IL_0003: ldarg.1 IL_0004: brtrue.s IL_0011 IL_0006: ldc.i4.s 60 IL_0008: conv.i8 IL_0009: stloc.2 IL_000a: ldc.i4.s 50 IL_000c: stloc.0 IL_000d: ldloc.2 IL_000e: stloc.1 IL_000f: br.s IL_0025 IL_0011: ldc.i4.s 40 IL_0013: conv.i8 IL_0014: stloc.2 IL_0015: ldc.i4.s 30 IL_0017: stloc.0 IL_0018: ldloc.2 IL_0019: stloc.1 IL_001a: br.s IL_0025 IL_001c: ldc.i4.s 20 IL_001e: conv.i8 IL_001f: stloc.2 IL_0020: ldc.i4.s 10 IL_0022: stloc.0 IL_0023: ldloc.2 IL_0024: stloc.1 IL_0025: ldloc.0 IL_0026: call ""void System.Console.Write(int)"" IL_002b: ldloc.1 IL_002c: call ""void System.Console.Write(long)"" IL_0031: ret }"); } [Fact] public void AssigningConditional_SideEffects() { string source = @" using System; class C { static void Main() { M(true, false); M(false, true); M(false, false); SideEffect(true); SideEffect(false); } static int left; static int right; static ref int SideEffect(bool isLeft) { Console.WriteLine($""{(isLeft ? ""left"" : ""right"")}: {(isLeft ? left : right)}""); return ref isLeft ? ref left : ref right; } static void M(bool b1, bool b2) { (SideEffect(isLeft: true), SideEffect(isLeft: false)) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); } } "; var expected = @"left: 0 right: 0 left: 10 right: 20 left: 30 right: 40 left: 50 right: 60"; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expected); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (int& V_0, int& V_1) IL_0000: ldc.i4.1 IL_0001: call ""ref int C.SideEffect(bool)"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: call ""ref int C.SideEffect(bool)"" IL_000d: stloc.1 IL_000e: ldarg.0 IL_000f: brtrue.s IL_0026 IL_0011: ldarg.1 IL_0012: brtrue.s IL_001d IL_0014: ldloc.0 IL_0015: ldc.i4.s 50 IL_0017: stind.i4 IL_0018: ldloc.1 IL_0019: ldc.i4.s 60 IL_001b: stind.i4 IL_001c: ret IL_001d: ldloc.0 IL_001e: ldc.i4.s 30 IL_0020: stind.i4 IL_0021: ldloc.1 IL_0022: ldc.i4.s 40 IL_0024: stind.i4 IL_0025: ret IL_0026: ldloc.0 IL_0027: ldc.i4.s 10 IL_0029: stind.i4 IL_002a: ldloc.1 IL_002b: ldc.i4.s 20 IL_002d: stind.i4 IL_002e: ret }"); } [Fact] public void AssigningConditional_SideEffects_RHS() { string source = @" using System; class C { static void Main() { M(true, false); M(false, true); M(false, false); } static T Echo<T>(T v, int i) { Console.WriteLine(i + "": "" + v); return v; } static void M(bool b1, bool b2) { var (x, y) = Echo(b1, 1) ? Echo((10, 20), 2) : Echo(b2, 3) ? Echo((30, 40), 4) : Echo((50, 60), 5); Console.WriteLine(""x: "" + x); Console.WriteLine(""y: "" + y); Console.WriteLine(); } } "; var expectedOutput = @"1: True 2: (10, 20) x: 10 y: 20 1: False 3: True 4: (30, 40) x: 30 y: 40 1: False 3: False 5: (50, 60) x: 50 y: 60 "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); comp.VerifyDiagnostics(); } [Fact] public void AssigningConditional_UnusedDeconstruction() { string source = @" class C { static void M(bool b1, bool b2) { (_, _) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); } } "; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldarg.1 IL_0004: pop IL_0005: ret }"); } [Fact, WorkItem(46562, "https://github.com/dotnet/roslyn/issues/46562")] public void CompoundAssignment() { string source = @" class C { void M() { decimal x = 0; (var y, _) += 0.00m; (int z, _) += z; (var t, _) += (1, 2); } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,17): warning CS0219: The variable 'x' is assigned but its value is never used // decimal x = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 17), // (7,10): error CS8185: A declaration is not allowed in this context. // (var y, _) += 0.00m; Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var y").WithLocation(7, 10), // (7,17): error CS0103: The name '_' does not exist in the current context // (var y, _) += 0.00m; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(7, 17), // (8,10): error CS8185: A declaration is not allowed in this context. // (int z, _) += z; Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int z").WithLocation(8, 10), // (8,10): error CS0165: Use of unassigned local variable 'z' // (int z, _) += z; Diagnostic(ErrorCode.ERR_UseDefViolation, "int z").WithArguments("z").WithLocation(8, 10), // (8,17): error CS0103: The name '_' does not exist in the current context // (int z, _) += z; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(8, 17), // (9,10): error CS8185: A declaration is not allowed in this context. // (var t, _) += (1, 2); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var t").WithLocation(9, 10), // (9,17): error CS0103: The name '_' does not exist in the current context // (var t, _) += (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(9, 17) ); } [Fact, WorkItem(50654, "https://github.com/dotnet/roslyn/issues/50654")] public void Repro50654() { string source = @" class C { static void Main() { (int, (int, (int, int), (int, int)))[] vals = new[] { (1, (2, (3, 4), (5, 6))), (11, (12, (13, 14), (15, 16))) }; foreach (var (a, (b, (c, d), (e, f))) in vals) { System.Console.Write($""{a + b + c + d + e + f} ""); } foreach ((int a, (int b, (int c, int d), (int e, int f))) in vals) { System.Console.Write($""{a + b + c + d + e + f} ""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "21 81 21 81"); } [Fact] public void MixDeclarationAndAssignmentPermutationsOf2() { string source = @" class C { static void Main() { int x1 = 0; (x1, string y1) = new C(); System.Console.WriteLine(x1 + "" "" + y1); int x2; (x2, var y2) = new C(); System.Console.WriteLine(x2 + "" "" + y2); string y3 = """"; (int x3, y3) = new C(); System.Console.WriteLine(x3 + "" "" + y3); string y4; (var x4, y4) = new C(); System.Console.WriteLine(x4 + "" "" + y4); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello 1 hello 1 hello 1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 188 (0xbc) .maxstack 3 .locals init (int V_0, //x1 string V_1, //y1 int V_2, //x2 string V_3, //y2 string V_4, //y3 int V_5, //x3 string V_6, //y4 int V_7, //x4 int V_8, string V_9) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: newobj ""C..ctor()"" IL_0007: ldloca.s V_8 IL_0009: ldloca.s V_9 IL_000b: callvirt ""void C.Deconstruct(out int, out string)"" IL_0010: ldloc.s V_8 IL_0012: stloc.0 IL_0013: ldloc.s V_9 IL_0015: stloc.1 IL_0016: ldloca.s V_0 IL_0018: call ""string int.ToString()"" IL_001d: ldstr "" "" IL_0022: ldloc.1 IL_0023: call ""string string.Concat(string, string, string)"" IL_0028: call ""void System.Console.WriteLine(string)"" IL_002d: newobj ""C..ctor()"" IL_0032: ldloca.s V_8 IL_0034: ldloca.s V_9 IL_0036: callvirt ""void C.Deconstruct(out int, out string)"" IL_003b: ldloc.s V_8 IL_003d: stloc.2 IL_003e: ldloc.s V_9 IL_0040: stloc.3 IL_0041: ldloca.s V_2 IL_0043: call ""string int.ToString()"" IL_0048: ldstr "" "" IL_004d: ldloc.3 IL_004e: call ""string string.Concat(string, string, string)"" IL_0053: call ""void System.Console.WriteLine(string)"" IL_0058: ldstr """" IL_005d: stloc.s V_4 IL_005f: newobj ""C..ctor()"" IL_0064: ldloca.s V_8 IL_0066: ldloca.s V_9 IL_0068: callvirt ""void C.Deconstruct(out int, out string)"" IL_006d: ldloc.s V_8 IL_006f: stloc.s V_5 IL_0071: ldloc.s V_9 IL_0073: stloc.s V_4 IL_0075: ldloca.s V_5 IL_0077: call ""string int.ToString()"" IL_007c: ldstr "" "" IL_0081: ldloc.s V_4 IL_0083: call ""string string.Concat(string, string, string)"" IL_0088: call ""void System.Console.WriteLine(string)"" IL_008d: newobj ""C..ctor()"" IL_0092: ldloca.s V_8 IL_0094: ldloca.s V_9 IL_0096: callvirt ""void C.Deconstruct(out int, out string)"" IL_009b: ldloc.s V_8 IL_009d: stloc.s V_7 IL_009f: ldloc.s V_9 IL_00a1: stloc.s V_6 IL_00a3: ldloca.s V_7 IL_00a5: call ""string int.ToString()"" IL_00aa: ldstr "" "" IL_00af: ldloc.s V_6 IL_00b1: call ""string string.Concat(string, string, string)"" IL_00b6: call ""void System.Console.WriteLine(string)"" IL_00bb: ret }"); } [Fact] public void MixDeclarationAndAssignmentPermutationsOf3() { string source = @" class C { static void Main() { int x1; string y1; (x1, y1, var z1) = new C(); System.Console.WriteLine(x1 + "" "" + y1 + "" "" + z1); int x2; bool z2; (x2, var y2, z2) = new C(); System.Console.WriteLine(x2 + "" "" + y2 + "" "" + z2); string y3; bool z3; (var x3, y3, z3) = new C(); System.Console.WriteLine(x3 + "" "" + y3 + "" "" + z3); bool z4; (var x4, var y4, z4) = new C(); System.Console.WriteLine(x4 + "" "" + y4 + "" "" + z4); string y5; (var x5, y5, var z5) = new C(); System.Console.WriteLine(x5 + "" "" + y5 + "" "" + z5); int x6; (x6, var y6, var z6) = new C(); System.Console.WriteLine(x6 + "" "" + y6 + "" "" + z6); } public void Deconstruct(out int a, out string b, out bool c) { a = 1; b = ""hello""; c = true; } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello True 1 hello True 1 hello True 1 hello True 1 hello True 1 hello True"); comp.VerifyDiagnostics(); } [Fact] public void DontAllowMixedDeclarationAndAssignmentInExpressionContext() { string source = @" class C { static void Main() { int x1 = 0; var z1 = (x1, string y1) = new C(); string y2 = """"; var z2 = (int x2, y2) = new C(); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,23): error CS8185: A declaration is not allowed in this context. // var z1 = (x1, string y1) = new C(); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "string y1").WithLocation(7, 23), // (9,19): error CS8185: A declaration is not allowed in this context. // var z2 = (int x2, y2) = new C(); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x2").WithLocation(9, 19)); } [Fact] public void DontAllowMixedDeclarationAndAssignmentInForeachDeclarationVariable() { string source = @" class C { static void Main() { int x1; foreach((x1, string y1) in new C[0]); string y2; foreach((int x2, y2) in new C[0]); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(6, 13), // (7,17): error CS8186: A foreach loop must declare its iteration variables. // foreach((x1, string y1) in new C[0]); Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(x1, string y1)").WithLocation(7, 17), // (8,16): warning CS0168: The variable 'y2' is declared but never used // string y2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "y2").WithArguments("y2").WithLocation(8, 16), // (9,17): error CS8186: A foreach loop must declare its iteration variables. // foreach((int x2, y2) in new C[0]); Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(int x2, y2)").WithLocation(9, 17)); } [Fact] public void DuplicateDeclarationOfVariableDeclaredInMixedDeclarationAndAssignment() { string source = @" class C { static void Main() { int x1; string y1; (x1, string y1) = new C(); string y2; (int x2, y2) = new C(); int x2; } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (7,16): warning CS0168: The variable 'y1' is declared but never used // string y1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "y1").WithArguments("y1").WithLocation(7, 16), // (8,21): error CS0128: A local variable or function named 'y1' is already defined in this scope // (x1, string y1) = new C(); Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(8, 21), // (11,13): error CS0128: A local variable or function named 'x2' is already defined in this scope // int x2; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(11, 13), // (11,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(11, 13)); } [Fact] public void AssignmentToUndeclaredVariableInMixedDeclarationAndAssignment() { string source = @" class C { static void Main() { (x1, string y1) = new C(); (int x2, y2) = new C(); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (6,10): error CS0103: The name 'x1' does not exist in the current context // (x1, string y1) = new C(); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 10), // (7,18): error CS0103: The name 'y2' does not exist in the current context // (int x2, y2) = new C(); Diagnostic(ErrorCode.ERR_NameNotInContext, "y2").WithArguments("y2").WithLocation(7, 18)); } [Fact] public void MixedDeclarationAndAssignmentInForInitialization() { string source = @" class C { static void Main() { int x1; for((x1, string y1) = new C(); x1 < 2; x1++) System.Console.WriteLine(x1 + "" "" + y1); string y2; for((int x2, y2) = new C(); x2 < 2; x2++) System.Console.WriteLine(x2 + "" "" + y2); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello 1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 109 (0x6d) .maxstack 3 .locals init (int V_0, //x1 string V_1, //y2 string V_2, //y1 int V_3, string V_4, int V_5) //x2 IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_3 IL_0007: ldloca.s V_4 IL_0009: callvirt ""void C.Deconstruct(out int, out string)"" IL_000e: ldloc.3 IL_000f: stloc.0 IL_0010: ldloc.s V_4 IL_0012: stloc.2 IL_0013: br.s IL_0030 IL_0015: ldloca.s V_0 IL_0017: call ""string int.ToString()"" IL_001c: ldstr "" "" IL_0021: ldloc.2 IL_0022: call ""string string.Concat(string, string, string)"" IL_0027: call ""void System.Console.WriteLine(string)"" IL_002c: ldloc.0 IL_002d: ldc.i4.1 IL_002e: add IL_002f: stloc.0 IL_0030: ldloc.0 IL_0031: ldc.i4.2 IL_0032: blt.s IL_0015 IL_0034: newobj ""C..ctor()"" IL_0039: ldloca.s V_3 IL_003b: ldloca.s V_4 IL_003d: callvirt ""void C.Deconstruct(out int, out string)"" IL_0042: ldloc.3 IL_0043: stloc.s V_5 IL_0045: ldloc.s V_4 IL_0047: stloc.1 IL_0048: br.s IL_0067 IL_004a: ldloca.s V_5 IL_004c: call ""string int.ToString()"" IL_0051: ldstr "" "" IL_0056: ldloc.1 IL_0057: call ""string string.Concat(string, string, string)"" IL_005c: call ""void System.Console.WriteLine(string)"" IL_0061: ldloc.s V_5 IL_0063: ldc.i4.1 IL_0064: add IL_0065: stloc.s V_5 IL_0067: ldloc.s V_5 IL_0069: ldc.i4.2 IL_006a: blt.s IL_004a IL_006c: ret }"); } [Fact] public void MixDeclarationAndAssignmentInTupleDeconstructPermutationsOf2() { string source = @" class C { static void Main() { int x1 = 0; (x1, string y1) = (1, ""hello""); System.Console.WriteLine(x1 + "" "" + y1); int x2; (x2, var y2) = (1, ""hello""); System.Console.WriteLine(x2 + "" "" + y2); string y3 = """"; (int x3, y3) = (1, ""hello""); System.Console.WriteLine(x3 + "" "" + y3); string y4; (var x4, y4) = (1, ""hello""); System.Console.WriteLine(x4 + "" "" + y4); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello 1 hello 1 hello 1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 140 (0x8c) .maxstack 3 .locals init (int V_0, //x1 string V_1, //y1 int V_2, //x2 string V_3, //y2 string V_4, //y3 int V_5, //x3 string V_6, //y4 int V_7) //x4 IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldc.i4.1 IL_0003: stloc.0 IL_0004: ldstr ""hello"" IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""string int.ToString()"" IL_0011: ldstr "" "" IL_0016: ldloc.1 IL_0017: call ""string string.Concat(string, string, string)"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ldc.i4.1 IL_0022: stloc.2 IL_0023: ldstr ""hello"" IL_0028: stloc.3 IL_0029: ldloca.s V_2 IL_002b: call ""string int.ToString()"" IL_0030: ldstr "" "" IL_0035: ldloc.3 IL_0036: call ""string string.Concat(string, string, string)"" IL_003b: call ""void System.Console.WriteLine(string)"" IL_0040: ldstr """" IL_0045: stloc.s V_4 IL_0047: ldc.i4.1 IL_0048: stloc.s V_5 IL_004a: ldstr ""hello"" IL_004f: stloc.s V_4 IL_0051: ldloca.s V_5 IL_0053: call ""string int.ToString()"" IL_0058: ldstr "" "" IL_005d: ldloc.s V_4 IL_005f: call ""string string.Concat(string, string, string)"" IL_0064: call ""void System.Console.WriteLine(string)"" IL_0069: ldc.i4.1 IL_006a: stloc.s V_7 IL_006c: ldstr ""hello"" IL_0071: stloc.s V_6 IL_0073: ldloca.s V_7 IL_0075: call ""string int.ToString()"" IL_007a: ldstr "" "" IL_007f: ldloc.s V_6 IL_0081: call ""string string.Concat(string, string, string)"" IL_0086: call ""void System.Console.WriteLine(string)"" IL_008b: ret }"); } [Fact] public void MixedDeclarationAndAssignmentCSharpNine() { string source = @" class Program { static void Main() { int x1; (x1, string y1) = new A(); string y2; (int x2, y2) = new A(); bool z3; (int x3, (string y3, z3)) = new B(); int x4; (x4, var (y4, z4)) = new B(); } } class A { public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } class B { public void Deconstruct(out int a, out (string b, bool c) tuple) { a = 1; tuple = (""hello"", true); } } "; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (7,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (x1, string y1) = new A(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(x1, string y1) = new A()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(7, 9), // (9,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (int x2, y2) = new A(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x2, y2) = new A()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(9, 9), // (11,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (int x3, (string y3, z3)) = new B(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x3, (string y3, z3)) = new B()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(11, 9), // (13,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (x4, var (y4, z4)) = new B(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(x4, var (y4, z4)) = new B()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(13, 9)); } [Fact] public void NestedMixedDeclarationAndAssignmentPermutations() { string source = @" class C { static void Main() { int x1; string y1; (x1, (y1, var z1)) = new C(); System.Console.WriteLine(x1 + "" "" + y1 + "" "" + z1); int x2; bool z2; (x2, (var y2, z2)) = new C(); System.Console.WriteLine(x2 + "" "" + y2 + "" "" + z2); string y3; bool z3; (var x3, (y3, z3)) = new C(); System.Console.WriteLine(x3 + "" "" + y3 + "" "" + z3); bool z4; (var x4, (var y4, z4)) = new C(); System.Console.WriteLine(x4 + "" "" + y4 + "" "" + z4); string y5; (var x5, (y5, var z5)) = new C(); System.Console.WriteLine(x5 + "" "" + y5 + "" "" + z5); int x6; (x6, (var y6, var z6)) = new C(); System.Console.WriteLine(x6 + "" "" + y6 + "" "" + z6); int x7; (x7, var (y7, z7)) = new C(); System.Console.WriteLine(x7 + "" "" + y7 + "" "" + z7); } public void Deconstruct(out int a, out (string a, bool b) b) { a = 1; b = (""hello"", true); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello True 1 hello True 1 hello True 1 hello True 1 hello True 1 hello True 1 hello True"); comp.VerifyDiagnostics(); } [Fact] public void MixedDeclarationAndAssignmentUseBeforeDeclaration() { string source = @" class Program { static void Main() { (x1, string y1) = new A(); int x1; (int x2, y2) = new A(); string y2; (int x3, (string y3, z3)) = new B(); bool z3; (x4, var (y4, z4)) = new B(); int x4; } } class A { public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } class B { public void Deconstruct(out int a, out (string b, bool c) tuple) { a = 1; tuple = (""hello"", true); } } "; CreateCompilation(source, parseOptions: TestOptions.RegularPreview) .VerifyDiagnostics( // (6,10): error CS0841: Cannot use local variable 'x1' before it is declared // (x1, string y1) = new A(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1", isSuppressed: false).WithArguments("x1").WithLocation(6, 10), // (8,18): error CS0841: Cannot use local variable 'y2' before it is declared // (int x2, y2) = new A(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y2", isSuppressed: false).WithArguments("y2").WithLocation(8, 18), // (10,30): error CS0841: Cannot use local variable 'z3' before it is declared // (int x3, (string y3, z3)) = new B(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "z3", isSuppressed: false).WithArguments("z3").WithLocation(10, 30), // (12,10): error CS0841: Cannot use local variable 'x4' before it is declared // (x4, var (y4, z4)) = new B(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4", isSuppressed: false).WithArguments("x4").WithLocation(12, 10)); } [Fact] public void MixedDeclarationAndAssignmentUseDeclaredVariableInAssignment() { string source = @" class Program { static void Main() { (var x1, x1) = new A(); (x2, var x2) = new A(); (var x3, (var y3, x3)) = new B(); (x4, (var y4, var x4)) = new B(); } } class A { public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } class B { public void Deconstruct(out int a, out (string b, bool c) tuple) { a = 1; tuple = (""hello"", true); } } "; CreateCompilation(source, parseOptions: TestOptions.RegularPreview) .VerifyDiagnostics( // (6,18): error CS0841: Cannot use local variable 'x1' before it is declared // (var x1, x1) = new A(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 18), // (7,10): error CS0841: Cannot use local variable 'x2' before it is declared // (x2, var x2) = new A(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(7, 10), // (8,27): error CS0841: Cannot use local variable 'x3' before it is declared // (var x3, (var y3, x3)) = new B(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x3").WithArguments("x3").WithLocation(8, 27), // (9,10): error CS0841: Cannot use local variable 'x4' before it is declared // (x4, (var y4, var x4)) = new B(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 10)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { [CompilerTrait(CompilerFeature.Tuples)] public class CodeGenDeconstructTests : CSharpTestBase { private static readonly MetadataReference[] s_valueTupleRefs = new[] { SystemRuntimeFacadeRef, ValueTupleRef }; const string commonSource = @"public class Pair<T1, T2> { T1 item1; T2 item2; public Pair(T1 item1, T2 item2) { this.item1 = item1; this.item2 = item2; } public void Deconstruct(out T1 item1, out T2 item2) { System.Console.WriteLine($""Deconstructing {ToString()}""); item1 = this.item1; item2 = this.item2; } public override string ToString() { return $""({item1.ToString()}, {item2.ToString()})""; } } public static class Pair { public static Pair<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Pair<T1, T2>(item1, item2); } } public class Integer { public int state; public override string ToString() { return state.ToString(); } public Integer(int i) { state = i; } public static implicit operator LongInteger(Integer i) { System.Console.WriteLine($""Converting {i}""); return new LongInteger(i.state); } } public class LongInteger { long state; public LongInteger(long l) { state = l; } public override string ToString() { return state.ToString(); } }"; [Fact] public void SimpleAssign() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(x, y)", lhs.ToString()); Assert.Equal("(System.Int64 x, System.String y)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int64 x, System.String y)", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); var right = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single(); Assert.Equal(@"new C()", right.ToString()); Assert.Equal("C", model.GetTypeInfo(right).Type.ToTestDisplayString()); Assert.Equal("C", model.GetTypeInfo(right).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(right).Kind); }; var comp = CompileAndVerifyWithMscorlib40(source, expectedOutput: "1 hello", references: s_valueTupleRefs, sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 43 (0x2b) .maxstack 3 .locals init (long V_0, //x string V_1, //y int V_2, string V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_2 IL_0007: ldloca.s V_3 IL_0009: callvirt ""void C.Deconstruct(out int, out string)"" IL_000e: ldloc.2 IL_000f: conv.i8 IL_0010: stloc.0 IL_0011: ldloc.3 IL_0012: stloc.1 IL_0013: ldloca.s V_0 IL_0015: call ""string long.ToString()"" IL_001a: ldstr "" "" IL_001f: ldloc.1 IL_0020: call ""string string.Concat(string, string, string)"" IL_0025: call ""void System.Console.WriteLine(string)"" IL_002a: ret }"); } [Fact] public void ObsoleteDeconstructMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); foreach (var (z1, z2) in new[] { new C() }) { } } [System.Obsolete] public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,18): warning CS0612: 'C.Deconstruct(out int, out string)' is obsolete // (x, y) = new C(); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "new C()").WithArguments("C.Deconstruct(out int, out string)").WithLocation(9, 18), // (10,34): warning CS0612: 'C.Deconstruct(out int, out string)' is obsolete // foreach (var (z1, z2) in new[] { new C() }) { } Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "new[] { new C() }").WithArguments("C.Deconstruct(out int, out string)").WithLocation(10, 34) ); } [Fact] [WorkItem(13632, "https://github.com/dotnet/roslyn/issues/13632")] public void SimpleAssignWithoutConversion() { string source = @" class C { static void Main() { int x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 42 (0x2a) .maxstack 3 .locals init (int V_0, //x string V_1, //y int V_2, string V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_2 IL_0007: ldloca.s V_3 IL_0009: callvirt ""void C.Deconstruct(out int, out string)"" IL_000e: ldloc.2 IL_000f: stloc.0 IL_0010: ldloc.3 IL_0011: stloc.1 IL_0012: ldloca.s V_0 IL_0014: call ""string int.ToString()"" IL_0019: ldstr "" "" IL_001e: ldloc.1 IL_001f: call ""string string.Concat(string, string, string)"" IL_0024: call ""void System.Console.WriteLine(string)"" IL_0029: ret }"); } [Fact] public void DeconstructMethodAmbiguous() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } public void Deconstruct(out int a) { a = 2; } }"; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var deconstruction = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression).AsNode(); Assert.Equal("(x, y) = new C()", deconstruction.ToString()); var deconstructionInfo = model.GetDeconstructionInfo(deconstruction); var firstDeconstructMethod = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C").GetMembers(WellKnownMemberNames.DeconstructMethodName) .OfType<SourceOrdinaryMethodSymbol>().Where(m => m.ParameterCount == 2).Single(); Assert.Equal(firstDeconstructMethod.GetPublicSymbol(), deconstructionInfo.Method); Assert.Equal("void C.Deconstruct(out System.Int32 a, out System.String b)", deconstructionInfo.Method.ToTestDisplayString()); Assert.Null(deconstructionInfo.Conversion); var nested = deconstructionInfo.Nested; Assert.Equal(2, nested.Length); Assert.Null(nested[0].Method); Assert.Equal(ConversionKind.ImplicitNumeric, nested[0].Conversion.Value.Kind); Assert.Empty(nested[0].Nested); Assert.Null(nested[1].Method); Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind); Assert.Empty(nested[1].Nested); var assignment = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression, occurrence: 2).AsNode(); Assert.Equal("a = 1", assignment.ToString()); var defaultInfo = model.GetDeconstructionInfo(assignment); Assert.Null(defaultInfo.Method); Assert.Empty(defaultInfo.Nested); Assert.Equal(ConversionKind.UnsetConversionKind, defaultInfo.Conversion.Value.Kind); } [Fact] [WorkItem(27520, "https://github.com/dotnet/roslyn/issues/27520")] public void GetDeconstructionInfoOnIncompleteCode() { string source = @" class C { static void M(string s) { foreach (char in s) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS1525: Invalid expression term 'char' // foreach (char in s) { } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "char").WithArguments("char").WithLocation(6, 18), // (6,23): error CS0230: Type and identifier are both required in a foreach statement // foreach (char in s) { } Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 23) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var foreachDeconstruction = (ForEachVariableStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.ForEachVariableStatement).AsNode(); Assert.Equal(@"foreach (char in s) { }", foreachDeconstruction.ToString()); var deconstructionInfo = model.GetDeconstructionInfo(foreachDeconstruction); Assert.Equal(Conversion.UnsetConversion, deconstructionInfo.Conversion); Assert.Null(deconstructionInfo.Method); Assert.Empty(deconstructionInfo.Nested); } [Fact] [WorkItem(15634, "https://github.com/dotnet/roslyn/issues/15634")] public void DeconstructMustReturnVoid() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); } public int Deconstruct(out int a, out string b) { a = 1; b = ""hello""; return 42; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS8129: No Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type. // (x, y) = new C(); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 18) ); } [Fact] public void VerifyExecutionOrder_Deconstruct() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; } static void Main() { C c = new C(); (c.getHolderForX().x, c.getHolderForY().y) = c.getDeconstructReceiver(); } public void Deconstruct(out D1 x, out D2 y) { x = new D1(); y = new D2(); Console.WriteLine(""Deconstruct""); } } class D1 { public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } "; string expected = @"getHolderforX getHolderforY getDeconstructReceiver Deconstruct Conversion1 Conversion2 setX setY "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_Deconstruct_Conditional() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; } static void Main() { C c = new C(); bool b = true; (c.getHolderForX().x, c.getHolderForY().y) = b ? c.getDeconstructReceiver() : default; } public void Deconstruct(out D1 x, out D2 y) { x = new D1(); y = new D2(); Console.WriteLine(""Deconstruct""); } } class D1 { public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } "; string expected = @"getHolderforX getHolderforY getDeconstructReceiver Deconstruct Conversion1 Conversion2 setX setY "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_TupleLiteral() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } static void Main() { C c = new C(); (c.getHolderForX().x, c.getHolderForY().y) = (new D1(), new D2()); } } class D1 { public D1() { Console.WriteLine(""Constructor1""); } public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public D2() { Console.WriteLine(""Constructor2""); } public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } "; string expected = @"getHolderforX getHolderforY Constructor1 Conversion1 Constructor2 Conversion2 setX setY "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_TupleLiteral_Conditional() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } static void Main() { C c = new C(); bool b = true; (c.getHolderForX().x, c.getHolderForY().y) = b ? (new D1(), new D2()) : default; } } class D1 { public D1() { Console.WriteLine(""Constructor1""); } public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public D2() { Console.WriteLine(""Constructor2""); } public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } "; string expected = @"getHolderforX getHolderforY Constructor1 Constructor2 Conversion1 Conversion2 setX setY "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_TupleLiteralAndDeconstruction() { string source = @" using System; class C { int w { set { Console.WriteLine($""setW""); } } int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } int z { set { Console.WriteLine($""setZ""); } } C getHolderForW() { Console.WriteLine(""getHolderforW""); return this; } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; } static void Main() { C c = new C(); (c.getHolderForW().w, (c.getHolderForY().y, c.getHolderForZ().z), c.getHolderForX().x) = (new D1(), new D2(), new D3()); } } class D1 { public D1() { Console.WriteLine(""Constructor1""); } public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public D2() { Console.WriteLine(""Constructor2""); } public void Deconstruct(out int x, out int y) { x = 2; y = 3; Console.WriteLine(""deconstruct""); } } class D3 { public D3() { Console.WriteLine(""Constructor3""); } public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; } } "; string expected = @"getHolderforW getHolderforY getHolderforZ getHolderforX Constructor1 Conversion1 Constructor2 Constructor3 Conversion3 deconstruct setW setY setZ setX "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyExecutionOrder_TupleLiteralAndDeconstruction_Conditional() { string source = @" using System; class C { int w { set { Console.WriteLine($""setW""); } } int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } int z { set { Console.WriteLine($""setZ""); } } C getHolderForW() { Console.WriteLine(""getHolderforW""); return this; } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; } static void Main() { C c = new C(); bool b = false; (c.getHolderForW().w, (c.getHolderForY().y, c.getHolderForZ().z), c.getHolderForX().x) = b ? default : (new D1(), new D2(), new D3()); } } class D1 { public D1() { Console.WriteLine(""Constructor1""); } public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public D2() { Console.WriteLine(""Constructor2""); } public void Deconstruct(out int x, out int y) { x = 2; y = 3; Console.WriteLine(""deconstruct""); } } class D3 { public D3() { Console.WriteLine(""Constructor3""); } public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; } } "; string expected = @"getHolderforW getHolderforY getHolderforZ getHolderforX Constructor1 Constructor2 Constructor3 deconstruct Conversion1 Conversion3 setW setY setZ setX "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void DifferentVariableKinds() { string source = @" class C { int[] ArrayIndexer = new int[1]; string property; string Property { set { property = value; } } string AutoProperty { get; set; } static void Main() { C c = new C(); (c.ArrayIndexer[0], c.Property, c.AutoProperty) = new C(); System.Console.WriteLine(c.ArrayIndexer[0] + "" "" + c.property + "" "" + c.AutoProperty); } public void Deconstruct(out int a, out string b, out string c) { a = 1; b = ""hello""; c = ""world""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello world"); comp.VerifyDiagnostics(); } [Fact] public void Dynamic() { string source = @" class C { dynamic Dynamic1; dynamic Dynamic2; static void Main() { C c = new C(); (c.Dynamic1, c.Dynamic2) = c; System.Console.WriteLine(c.Dynamic1 + "" "" + c.Dynamic2); } public void Deconstruct(out int a, out dynamic b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructInterfaceOnStruct() { string source = @" interface IDeconstructable { void Deconstruct(out int a, out string b); } struct C : IDeconstructable { string state; static void Main() { int x; string y; IDeconstructable c = new C() { state = ""initial"" }; System.Console.Write(c); (x, y) = c; System.Console.WriteLine("" "" + c + "" "" + x + "" "" + y); } void IDeconstructable.Deconstruct(out int a, out string b) { a = 1; b = ""hello""; state = ""modified""; } public override string ToString() { return state; } } "; var comp = CompileAndVerify(source, expectedOutput: "initial modified 1 hello", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructMethodHasParams2() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b, params int[] c) // not a Deconstruct operator { a = 1; b = ""ignored""; } public void Deconstruct(out int a, out string b) { a = 2; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "2 hello"); comp.VerifyDiagnostics(); } [Fact] public void OutParamsDisallowed() { string source = @" class C { public void Deconstruct(out int a, out string b, out params int[] c) { a = 1; b = ""ignored""; c = new[] { 2, 2 }; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,58): error CS8328: The parameter modifier 'params' cannot be used with 'out' // public void Deconstruct(out int a, out string b, out params int[] c) Diagnostic(ErrorCode.ERR_BadParameterModifiers, "params").WithArguments("params", "out").WithLocation(4, 58)); } [Fact] public void DeconstructMethodHasArglist2() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } public void Deconstruct(out int a, out string b, __arglist) // not a Deconstruct operator { a = 2; b = ""ignored""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DifferentStaticVariableKinds() { string source = @" class C { static int[] ArrayIndexer = new int[1]; static string property; static string Property { set { property = value; } } static string AutoProperty { get; set; } static void Main() { (C.ArrayIndexer[0], C.Property, C.AutoProperty) = new C(); System.Console.WriteLine(C.ArrayIndexer[0] + "" "" + C.property + "" "" + C.AutoProperty); } public void Deconstruct(out int a, out string b, out string c) { a = 1; b = ""hello""; c = ""world""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello world"); comp.VerifyDiagnostics(); } [Fact] public void DifferentVariableRefKinds() { string source = @" class C { static void Main() { long a = 1; int b; C.M(ref a, out b); System.Console.WriteLine(a + "" "" + b); } static void M(ref long a, out int b) { (a, b) = new C(); } public void Deconstruct(out int x, out byte y) { x = 2; y = (byte)3; } } "; var comp = CompileAndVerify(source, expectedOutput: "2 3"); comp.VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.RefLocalsReturns)] public void RefReturningMethod() { string source = @" class C { static int i = 0; static void Main() { (M(), M()) = new C(); System.Console.WriteLine($""Final i is {i}""); } static ref int M() { System.Console.WriteLine($""M (previous i is {i})""); return ref i; } void Deconstruct(out int x, out int y) { System.Console.WriteLine(""Deconstruct""); x = 42; y = 43; } } "; var expected = @"M (previous i is 0) M (previous i is 0) Deconstruct Final i is 43 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact, CompilerTrait(CompilerFeature.RefLocalsReturns)] public void RefReturningProperty() { string source = @" class C { static int i = 0; static void Main() { (P, P) = new C(); System.Console.WriteLine($""Final i is {i}""); } static ref int P { get { System.Console.WriteLine($""P (previous i is {i})""); return ref i; } } void Deconstruct(out int x, out int y) { System.Console.WriteLine(""Deconstruct""); x = 42; y = 43; } } "; var expected = @"P (previous i is 0) P (previous i is 0) Deconstruct Final i is 43 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.RefLocalsReturns)] public void RefReturningMethodFlow() { string source = @" struct C { static C i; static C P { get { System.Console.WriteLine(""getP""); return i; } set { System.Console.WriteLine(""setP""); i = value; } } static void Main() { (M(), M()) = P; } static ref C M() { System.Console.WriteLine($""M (previous i is {i})""); return ref i; } void Deconstruct(out int x, out int y) { System.Console.WriteLine(""Deconstruct""); x = 42; y = 43; } public static implicit operator C(int x) { System.Console.WriteLine(""conversion""); return new C(); } } "; var expected = @"M (previous i is C) M (previous i is C) getP Deconstruct conversion conversion"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void Indexers() { string source = @" class C { static SomeArray array; static void Main() { int y; (Goo()[Bar()], y) = new C(); System.Console.WriteLine($""Final array values[2] {array.values[2]}""); } static SomeArray Goo() { System.Console.WriteLine($""Goo""); array = new SomeArray(); return array; } static int Bar() { System.Console.WriteLine($""Bar""); return 2; } void Deconstruct(out int x, out int y) { System.Console.WriteLine(""Deconstruct""); x = 101; y = 102; } } class SomeArray { public int[] values; public SomeArray() { values = new [] { 42, 43, 44 }; } public int this[int index] { get { System.Console.WriteLine($""indexGet (with value {values[index]})""); return values[index]; } set { System.Console.WriteLine($""indexSet (with value {value})""); values[index] = value; } } } "; var expected = @"Goo Bar Deconstruct indexSet (with value 101) Final array values[2] 101 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void AssigningTuple() { string source = @" class C { static void Main() { long x; string y; int i = 1; (x, y) = (i, ""hello""); System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var deconstruction = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Single(); var deconstructionInfo = model.GetDeconstructionInfo(deconstruction); Assert.Null(deconstructionInfo.Method); Assert.Null(deconstructionInfo.Conversion); var nested = deconstructionInfo.Nested; Assert.Equal(2, nested.Length); Assert.Null(nested[0].Method); Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind); Assert.Empty(nested[0].Nested); Assert.Null(nested[1].Method); Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind); Assert.Empty(nested[1].Nested); var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(i, ""hello"")", tuple.ToString()); var tupleConversion = model.GetConversion(tuple); Assert.Equal(ConversionKind.ImplicitTupleLiteral, tupleConversion.Kind); Assert.Equal(ConversionKind.ImplicitNumeric, tupleConversion.UnderlyingConversions[0].Kind); } [Fact] public void AssigningTupleWithConversion() { string source = @" class C { static void Main() { long x; string y; (x, y) = M(); System.Console.WriteLine(x + "" "" + y); } static System.ValueTuple<int, string> M() { return (1, ""hello""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact] public void AssigningLongTuple() { string source = @" class C { static void Main() { long x; int y; (x, x, x, x, x, x, x, x, x, y) = (1, 1, 1, 1, 1, 1, 1, 1, 4, 2); System.Console.WriteLine(string.Concat(x, "" "", y)); } } "; var comp = CompileAndVerify(source, expectedOutput: "4 2"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0) //y IL_0000: ldc.i4.4 IL_0001: conv.i8 IL_0002: ldc.i4.2 IL_0003: stloc.0 IL_0004: box ""long"" IL_0009: ldstr "" "" IL_000e: ldloc.0 IL_000f: box ""int"" IL_0014: call ""string string.Concat(object, object, object)"" IL_0019: call ""void System.Console.WriteLine(string)"" IL_001e: ret }"); } [Fact] public void AssigningLongTupleWithNames() { string source = @" class C { static void Main() { long x; int y; (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "9 10"); comp.VerifyDiagnostics( // (9,43): warning CS8123: The tuple element name 'a' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "a: 1").WithArguments("a", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 43), // (9,49): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 49), // (9,55): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 55), // (9,61): warning CS8123: The tuple element name 'd' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "d: 4").WithArguments("d", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 61), // (9,67): warning CS8123: The tuple element name 'e' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "e: 5").WithArguments("e", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 67), // (9,73): warning CS8123: The tuple element name 'f' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "f: 6").WithArguments("f", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 73), // (9,79): warning CS8123: The tuple element name 'g' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "g: 7").WithArguments("g", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 79), // (9,85): warning CS8123: The tuple element name 'h' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "h: 8").WithArguments("h", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 85), // (9,91): warning CS8123: The tuple element name 'i' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "i: 9").WithArguments("i", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 91), // (9,97): warning CS8123: The tuple element name 'j' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'. // (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "j: 10").WithArguments("j", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 97) ); } [Fact] public void AssigningLongTuple2() { string source = @" class C { static void Main() { long x; int y; (x, x, x, x, x, x, x, x, x, y) = (1, 1, 1, 1, 1, 1, 1, 1, 4, (byte)2); System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "4 2"); comp.VerifyDiagnostics(); } [Fact] public void AssigningTypelessTuple() { string source = @" class C { static void Main() { string x = ""goodbye""; string y; (x, y) = (null, ""hello""); System.Console.WriteLine($""{x}{y}""); } } "; var comp = CompileAndVerify(source, expectedOutput: "hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 19 (0x13) .maxstack 2 .locals init (string V_0) //y IL_0000: ldnull IL_0001: ldstr ""hello"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""string string.Concat(string, string)"" IL_000d: call ""void System.Console.WriteLine(string)"" IL_0012: ret } "); } [Fact] public void ValueTupleReturnIsNotEmittedIfUnused() { string source = @" class C { public static void Main() { int x, y; (x, y) = new C(); } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 15 (0xf) .maxstack 3 .locals init (int V_0, int V_1) IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_0 IL_0007: ldloca.s V_1 IL_0009: callvirt ""void C.Deconstruct(out int, out int)"" IL_000e: ret }"); } [Fact] public void ValueTupleReturnIsEmittedIfUsed() { string source = @" class C { public static void Main() { int x, y; var z = ((x, y) = new C()); z.ToString(); } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().ElementAt(2); Assert.Equal("(System.Int32 x, System.Int32 y) z", model.GetDeclaredSymbol(x).ToTestDisplayString()); }; var comp = CompileAndVerify(source, sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 37 (0x25) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0, //z int V_1, int V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_1 IL_0007: ldloca.s V_2 IL_0009: callvirt ""void C.Deconstruct(out int, out int)"" IL_000e: ldloc.1 IL_000f: ldloc.2 IL_0010: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0015: stloc.0 IL_0016: ldloca.s V_0 IL_0018: constrained. ""System.ValueTuple<int, int>"" IL_001e: callvirt ""string object.ToString()"" IL_0023: pop IL_0024: ret }"); } [Fact] public void ValueTupleReturnIsEmittedIfUsed_WithCSharp7_1() { string source = @" class C { public static void Main() { int x, y; var z = ((x, y) = new C()); z.ToString(); } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().ElementAt(2); Assert.Equal("(System.Int32 x, System.Int32 y) z", model.GetDeclaredSymbol(x).ToTestDisplayString()); }; var comp = CompileAndVerify(source, sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics(); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleNotRequiredIfReturnIsNotUsed() { string source = @" class C { public static void Main() { int x, y; (x, y) = new C(); System.Console.Write($""assignment: {x} {y}. ""); foreach (var (a, b) in new[] { new C() }) { System.Console.Write($""foreach: {a} {b}.""); } } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "assignment: 1 2. foreach: 1 2."); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var xy = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal("(x, y)", xy.ToString()); var tuple1 = model.GetTypeInfo(xy).Type; Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tuple1.ToTestDisplayString()); var ab = nodes.OfType<DeclarationExpressionSyntax>().Single(); var tuple2 = model.GetTypeInfo(ab).Type; Assert.Equal("(System.Int32 a, System.Int32 b)[missing]", tuple2.ToTestDisplayString()); Assert.Equal("(System.Int32 a, System.Int32 b)[missing]", model.GetTypeInfo(ab).ConvertedType.ToTestDisplayString()); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleNotRequiredIfReturnIsNotUsed2() { string source = @" class C { public static void Main() { int x, y; for((x, y) = new C(1); ; (x, y) = new C(2)) { } } public C(int c) { } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var tuple1 = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(x, y) = new C(1)", tuple1.Parent.ToString()); var tupleType1 = model.GetTypeInfo(tuple1).Type; Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tupleType1.ToTestDisplayString()); var tuple2 = nodes.OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(x, y) = new C(2)", tuple2.Parent.ToString()); var tupleType2 = model.GetTypeInfo(tuple1).Type; Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tupleType2.ToTestDisplayString()); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleNotRequiredIfReturnIsNotUsed3() { string source = @" class C { public static void Main() { int x, y; (x, y) = new C(); } public C() { } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } namespace System { [Obsolete] public struct ValueTuple<T1, T2> { [Obsolete] public T1 Item1; [Obsolete] public T2 Item2; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyEmitDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var tuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(x, y) = new C()", tuple.Parent.ToString()); var tupleType = model.GetTypeInfo(tuple).Type; Assert.Equal("(System.Int32 x, System.Int32 y)", tupleType.ToTestDisplayString()); var underlying = ((INamedTypeSymbol)tupleType).TupleUnderlyingType; Assert.Equal("(System.Int32, System.Int32)", underlying.ToTestDisplayString()); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleRequiredWhenRightHandSideIsTuple() { string source = @" class C { public static void Main() { int x, y; (x, y) = (1, 2); } } "; var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (7,18): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1, 2)").WithArguments("System.ValueTuple`2").WithLocation(7, 18) ); } [Fact] [WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")] public void ValueTupleRequiredWhenRightHandSideIsTupleButNoReferenceEmitted() { string source = @" class C { public static void Main() { int x, y; (x, y) = (1, 2); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); Action<PEAssembly> assemblyValidator = assembly => { var reader = assembly.GetMetadataReader(); var names = reader.GetAssemblyRefNames().Select(name => reader.GetString(name)); Assert.Empty(names.Where(name => name.Contains("ValueTuple"))); }; CompileAndVerifyCommon(comp, assemblyValidator: assemblyValidator); } [Fact] public void ValueTupleReturnMissingMemberWithCSharp7() { string source = @" class C { public void M() { int x, y; var nested = ((x, y) = (1, 2)); System.Console.Write(nested.x); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyDiagnostics( // (8,37): error CS8305: Tuple element name 'x' is inferred. Please use language version 7.1 or greater to access an element by its inferred name. // System.Console.Write(nested.x); Diagnostic(ErrorCode.ERR_TupleInferredNamesNotAvailable, "x").WithArguments("x", "7.1").WithLocation(8, 37) ); } [Fact] public void ValueTupleReturnWithInferredNamesWithCSharp7_1() { string source = @" class C { public void M() { int x, y, Item1, Rest; var a = ((x, y) = (1, 2)); var b = ((x, x) = (1, 2)); var c = ((_, x) = (1, 2)); var d = ((Item1, Rest) = (1, 2)); var nested = ((x, Item1, y, (_, x, x), (x, y)) = (1, 2, 3, (4, 5, 6), (7, 8))); (int, int) f = ((x, y) = (1, 2)); } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var declarations = nodes.OfType<VariableDeclaratorSyntax>(); Assert.Equal("(System.Int32 x, System.Int32 y) a", model.GetDeclaredSymbol(declarations.ElementAt(4)).ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32) b", model.GetDeclaredSymbol(declarations.ElementAt(5)).ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32 x) c", model.GetDeclaredSymbol(declarations.ElementAt(6)).ToTestDisplayString()); var x = (ILocalSymbol)model.GetDeclaredSymbol(declarations.ElementAt(7)); Assert.Equal("(System.Int32, System.Int32) d", x.ToTestDisplayString()); Assert.True(x.Type.GetSymbol().TupleElementNames.IsDefault); Assert.Equal("(System.Int32 x, System.Int32, System.Int32 y, (System.Int32, System.Int32, System.Int32), (System.Int32 x, System.Int32 y)) nested", model.GetDeclaredSymbol(declarations.ElementAt(8)).ToTestDisplayString()); }; var comp = CompileAndVerify(source, sourceSymbolValidator: validator, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyDiagnostics(); } [Fact] public void DeconstructionDeclarationCanOnlyBeParsedAsStatement() { string source = @" class C { public static void Main() { var z = ((var x, int y) = new C()); } public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,19): error CS8185: A declaration is not allowed in this context. // var z = ((var x, int y) = new C()); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x").WithLocation(6, 19) ); } [ConditionalFact(typeof(DesktopOnly))] public void Constraints_01() { string source = @" using System; class C { public void M() { (int x, var (err1, y)) = (0, new C()); // ok, no return value used (ArgIterator err2, var err3) = M2(); // ok, no return value foreach ((ArgIterator err4, var err5) in new[] { M2() }) // ok, no return value { } } public static (ArgIterator, ArgIterator) M2() { return (default(ArgIterator), default(ArgIterator)); } public void Deconstruct(out ArgIterator a, out int b) { a = default(ArgIterator); b = 2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (19,29): error CS1601: Cannot make reference to variable of type 'ArgIterator' // public void Deconstruct(out ArgIterator a, out int b) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out ArgIterator a").WithArguments("System.ArgIterator").WithLocation(19, 29), // (14,46): error CS0306: The type 'ArgIterator' may not be used as a type argument // public static (ArgIterator, ArgIterator) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("System.ArgIterator").WithLocation(14, 46), // (14,46): error CS0306: The type 'ArgIterator' may not be used as a type argument // public static (ArgIterator, ArgIterator) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("System.ArgIterator").WithLocation(14, 46), // (16,17): error CS0306: The type 'ArgIterator' may not be used as a type argument // return (default(ArgIterator), default(ArgIterator)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(ArgIterator)").WithArguments("System.ArgIterator").WithLocation(16, 17), // (16,39): error CS0306: The type 'ArgIterator' may not be used as a type argument // return (default(ArgIterator), default(ArgIterator)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(ArgIterator)").WithArguments("System.ArgIterator").WithLocation(16, 39) ); } [Fact] public void Constraints_02() { string source = @" unsafe class C { public void M() { (int x, var (err1, y)) = (0, new C()); // ok, no return value (var err2, var err3) = M2(); // ok, no return value foreach ((var err4, var err5) in new[] { M2() }) // ok, no return value { } } public static (int*, int*) M2() { return (default(int*), default(int*)); } public void Deconstruct(out int* a, out int b) { a = default(int*); b = 2; } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (13,32): error CS0306: The type 'int*' may not be used as a type argument // public static (int*, int*) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(13, 32), // (13,32): error CS0306: The type 'int*' may not be used as a type argument // public static (int*, int*) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(13, 32), // (15,17): error CS0306: The type 'int*' may not be used as a type argument // return (default(int*), default(int*)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(int*)").WithArguments("int*").WithLocation(15, 17), // (15,32): error CS0306: The type 'int*' may not be used as a type argument // return (default(int*), default(int*)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(int*)").WithArguments("int*").WithLocation(15, 32) ); } [Fact] public void Constraints_03() { string source = @" unsafe class C { public void M() { int ok; int* err1, err2; var t = ((ok, (err1, ok)) = (0, new C())); var t2 = ((err1, err2) = M2()); } public static (int*, int*) M2() { throw null; } public void Deconstruct(out int* a, out int b) { a = default(int*); b = 2; } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (12,32): error CS0306: The type 'int*' may not be used as a type argument // public static (int*, int*) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(12, 32), // (12,32): error CS0306: The type 'int*' may not be used as a type argument // public static (int*, int*) M2() Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(12, 32), // (8,24): error CS0306: The type 'int*' may not be used as a type argument // var t = ((ok, (err1, ok)) = (0, new C())); Diagnostic(ErrorCode.ERR_BadTypeArgument, "err1").WithArguments("int*").WithLocation(8, 24), // (9,20): error CS0306: The type 'int*' may not be used as a type argument // var t2 = ((err1, err2) = M2()); Diagnostic(ErrorCode.ERR_BadTypeArgument, "err1").WithArguments("int*").WithLocation(9, 20), // (9,26): error CS0306: The type 'int*' may not be used as a type argument // var t2 = ((err1, err2) = M2()); Diagnostic(ErrorCode.ERR_BadTypeArgument, "err2").WithArguments("int*").WithLocation(9, 26) ); } [Fact] public void DeconstructionWithTupleNamesCannotBeParsed() { string source = @" class C { public static void Main() { (Alice: var x, Bob: int y) = (1, 2); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,10): error CS8187: Tuple element names are not permitted on the left of a deconstruction. // (Alice: var x, Bob: int y) = (1, 2); Diagnostic(ErrorCode.ERR_TupleElementNamesInDeconstruction, "Alice:").WithLocation(6, 10), // (6,24): error CS8187: Tuple element names are not permitted on the left of a deconstruction. // (Alice: var x, Bob: int y) = (1, 2); Diagnostic(ErrorCode.ERR_TupleElementNamesInDeconstruction, "Bob:").WithLocation(6, 24) ); } [Fact] public void ValueTupleReturnIsEmittedIfUsedInLambda() { string source = @" class C { static void F(System.Action a) { } static void F<T>(System.Func<T> f) { System.Console.Write(f().ToString()); } static void Main() { int x, y; F(() => (x, y) = (1, 2)); } } "; var comp = CompileAndVerify(source, expectedOutput: "(1, 2)"); comp.VerifyDiagnostics(); } [Fact] public void AssigningIntoProperties() { string source = @" class C { static int field; static long x { set { System.Console.WriteLine($""setX {value}""); } } static string y { get; set; } static ref int z { get { return ref field; } } static void Main() { (x, y, z) = new C(); System.Console.WriteLine(y); System.Console.WriteLine($""field: {field}""); } public void Deconstruct(out int a, out string b, out int c) { a = 1; b = ""hello""; c = 2; } } "; string expected = @"setX 1 hello field: 2 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void AssigningTupleIntoProperties() { string source = @" class C { static int field; static long x { set { System.Console.WriteLine($""setX {value}""); } } static string y { get; set; } static ref int z { get { return ref field; } } static void Main() { (x, y, z) = (1, ""hello"", 2); System.Console.WriteLine(y); System.Console.WriteLine($""field: {field}""); } } "; string expected = @"setX 1 hello field: 2 "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] [WorkItem(18554, "https://github.com/dotnet/roslyn/issues/18554")] public void AssigningIntoIndexers() { string source = @" using System; class C { int field; ref int this[int x, int y, int z, int opt = 1] { get { Console.WriteLine($""this.get""); return ref field; } } int this[int x, long y, int z, int opt = 1] { set { Console.WriteLine($""this.set({value})""); } } int M(int i) { Console.WriteLine($""M({i})""); return 0; } void Test() { (this[z: M(1), x: M(2), y: 10], this[z: M(3), x: M(4), y: 10L]) = this; Console.WriteLine($""field: {field}""); } static void Main() { new C().Test(); } void Deconstruct(out int a, out int b) { Console.WriteLine(nameof(Deconstruct)); a = 1; b = 2; } } "; var expectedOutput = @"M(1) M(2) this.get M(3) M(4) Deconstruct this.set(2) field: 1 "; var comp = CompileAndVerify(source, expectedOutput: expectedOutput); comp.VerifyDiagnostics(); } [Fact] [WorkItem(18554, "https://github.com/dotnet/roslyn/issues/18554")] public void AssigningTupleIntoIndexers() { string source = @" using System; class C { int field; ref int this[int x, int y, int z, int opt = 1] { get { Console.WriteLine($""this.get""); return ref field; } } int this[int x, long y, int z, int opt = 1] { set { Console.WriteLine($""this.set({value})""); } } int M(int i) { Console.WriteLine($""M({i})""); return 0; } void Test() { (this[z: M(1), x: M(2), y: 10], this[z: M(3), x: M(4), y: 10L]) = (1, 2); Console.WriteLine($""field: {field}""); } static void Main() { new C().Test(); } } "; var expectedOutput = @"M(1) M(2) this.get M(3) M(4) this.set(2) field: 1 "; var comp = CompileAndVerify(source, expectedOutput: expectedOutput); comp.VerifyDiagnostics(); } [Fact] public void AssigningIntoIndexerWithOptionalValueParameter() { var ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) .method public hidebysig specialname instance void set_Item ( int32 i, [opt] int32 'value' ) cil managed { .param [2] = int32(1) .maxstack 8 IL_0000: ldstr ""this.set({0})"" IL_0005: ldarg.2 IL_0006: box[mscorlib]System.Int32 IL_000b: call string[mscorlib] System.String::Format(string, object) IL_0010: call void [mscorlib]System.Console::WriteLine(string) IL_0015: ret } // end of method C::set_Item .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor .property instance int32 Item( int32 i ) { .set instance void C::set_Item(int32, int32) } } // end of class C "; var source = @" class Program { static void Main() { var c = new C(); (c[1], c[2]) = (1, 2); } } "; string expectedOutput = @"this.set(1) this.set(2) "; var comp = CreateCompilationWithILAndMscorlib40(source, ilSource, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void Swap() { string source = @" class C { static int x = 2; static int y = 4; static void Main() { Swap(); System.Console.WriteLine(x + "" "" + y); } static void Swap() { (x, y) = (y, x); } } "; var comp = CompileAndVerify(source, expectedOutput: "4 2"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Swap", @" { // Code size 23 (0x17) .maxstack 2 .locals init (int V_0) IL_0000: ldsfld ""int C.y"" IL_0005: ldsfld ""int C.x"" IL_000a: stloc.0 IL_000b: stsfld ""int C.x"" IL_0010: ldloc.0 IL_0011: stsfld ""int C.y"" IL_0016: ret } "); } [Fact] public void CircularFlow() { string source = @" class C { static void Main() { (object i, object ii) x = (1, 2); object y; (x.ii, y) = x; System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "(1, 1) 2"); comp.VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.RefLocalsReturns)] public void CircularFlow2() { string source = @" class C { static void Main() { (object i, object ii) x = (1,2); object y; ref var a = ref x; (a.ii, y) = x; System.Console.WriteLine(x + "" "" + y); } } "; var comp = CompileAndVerify(source, expectedOutput: "(1, 1) 2", parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); } [Fact] public void DeconstructUsingBaseDeconstructMethod() { string source = @" class Base { public void Deconstruct(out int a, out int b) { a = 1; b = 2; } } class C : Base { static void Main() { int x, y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int c) { c = 42; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2", parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); } [Fact] public void NestedDeconstructUsingSystemTupleExtensionMethod() { string source = @" using System; class C { static void Main() { int x; string y, z; (x, (y, z)) = Tuple.Create(1, Tuple.Create(""hello"", ""world"")); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello world", parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var deconstruction = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression).AsNode(); Assert.Equal(@"(x, (y, z)) = Tuple.Create(1, Tuple.Create(""hello"", ""world""))", deconstruction.ToString()); var deconstructionInfo = model.GetDeconstructionInfo(deconstruction); Assert.Equal("void System.TupleExtensions.Deconstruct<System.Int32, System.Tuple<System.String, System.String>>(" + "this System.Tuple<System.Int32, System.Tuple<System.String, System.String>> value, " + "out System.Int32 item1, out System.Tuple<System.String, System.String> item2)", deconstructionInfo.Method.ToTestDisplayString()); Assert.Null(deconstructionInfo.Conversion); var nested = deconstructionInfo.Nested; Assert.Equal(2, nested.Length); Assert.Null(nested[0].Method); Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind); Assert.Empty(nested[0].Nested); Assert.Equal("void System.TupleExtensions.Deconstruct<System.String, System.String>(" + "this System.Tuple<System.String, System.String> value, " + "out System.String item1, out System.String item2)", nested[1].Method.ToTestDisplayString()); Assert.Null(nested[1].Conversion); var nested2 = nested[1].Nested; Assert.Equal(2, nested.Length); Assert.Null(nested2[0].Method); Assert.Equal(ConversionKind.Identity, nested2[0].Conversion.Value.Kind); Assert.Empty(nested2[0].Nested); Assert.Null(nested2[1].Method); Assert.Equal(ConversionKind.Identity, nested2[1].Conversion.Value.Kind); Assert.Empty(nested2[1].Nested); } [Fact] public void DeconstructUsingValueTupleExtensionMethod() { string source = @" class C { static void Main() { int x; string y, z; (x, y, z) = (1, 2); } } public static class Extensions { public static void Deconstruct(this (int, int) self, out int x, out string y, out string z) { throw null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,25): error CS0029: Cannot implicitly convert type 'int' to 'string' // (x, y, z) = (1, 2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "2").WithArguments("int", "string").WithLocation(8, 25), // (8,9): error CS8132: Cannot deconstruct a tuple of '2' elements into '3' variables. // (x, y, z) = (1, 2); Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, "(x, y, z) = (1, 2)").WithArguments("2", "3").WithLocation(8, 9) ); } [Fact] public void OverrideDeconstruct() { string source = @" class Base { public virtual void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } class C : Base { static void Main() { int x; string y; (x, y) = new C(); } public override void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; System.Console.WriteLine(""override""); } } "; var comp = CompileAndVerify(source, expectedOutput: "override", parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); } [Fact] public void DeconstructRefTuple() { string template = @" using System; class C { static void Main() { int VARIABLES; // int x1, x2, ... (VARIABLES) = (TUPLE).ToTuple(); // (x1, x2, ...) = (1, 2, ...).ToTuple(); System.Console.WriteLine(OUTPUT); } } "; for (int i = 2; i <= 21; i++) { var tuple = String.Join(", ", Enumerable.Range(1, i).Select(n => n.ToString())); var variables = String.Join(", ", Enumerable.Range(1, i).Select(n => $"x{n}")); var output = String.Join(@" + "" "" + ", Enumerable.Range(1, i).Select(n => $"x{n}")); var expected = String.Join(" ", Enumerable.Range(1, i).Select(n => n)); var source = template.Replace("VARIABLES", variables).Replace("TUPLE", tuple).Replace("OUTPUT", output); var comp = CompileAndVerify(source, expectedOutput: expected, parseOptions: TestOptions.Regular.WithRefsFeature()); comp.VerifyDiagnostics(); } } [Fact] public void DeconstructExtensionMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } } static class D { public static void Deconstruct(this C value, out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact] public void DeconstructRefExtensionMethod() { // https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-01-24.md string source = @" struct C { static void Main() { long x; string y; var c = new C(); (x, y) = c; System.Console.WriteLine(x + "" "" + y); } } static class D { public static void Deconstruct(this ref C value, out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source).VerifyDiagnostics( // (10,9): error CS1510: A ref or out value must be an assignable variable // (x, y) = c; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x, y) = c").WithLocation(10, 9) ); } [Fact] public void DeconstructInExtensionMethod() { string source = @" struct C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + "" "" + y); } } static class D { public static void Deconstruct(this in C value, out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact] public void UnderspecifiedDeconstructGenericExtensionMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); } } static class Extension { public static void Deconstruct<T>(this C value, out int a, out T b) { a = 2; b = default(T); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS0411: The type arguments for method 'Extension.Deconstruct<T>(C, out int, out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // (x, y) = new C(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new C()").WithArguments("Extension.Deconstruct<T>(C, out int, out T)").WithLocation(8, 18), // (8,18): error CS8129: No Deconstruct instance or extension method was found for type 'C', with 2 out parameters. // (x, y) = new C(); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 18) ); } [Fact] public void UnspecifiedGenericMethodIsNotCandidate() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C(); } } static class Extension { public static void Deconstruct<T>(this C value, out int a, out T b) { a = 2; b = default(T); } public static void Deconstruct(this C value, out int a, out string b) { a = 2; b = ""hello""; System.Console.Write(""Deconstructed""); } }"; var comp = CompileAndVerify(source, expectedOutput: "Deconstructed"); comp.VerifyDiagnostics(); } [Fact] public void DeconstructGenericExtensionMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C1<string>(); } } public class C1<T> { } static class Extension { public static void Deconstruct<T>(this C1<T> value, out int a, out T b) { a = 2; b = default(T); System.Console.WriteLine(""Deconstructed""); } } "; var comp = CompileAndVerify(source, expectedOutput: "Deconstructed"); comp.VerifyDiagnostics(); } [Fact] public void DeconstructGenericMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C1(); } } class C1 { public void Deconstruct<T>(out int a, out T b) { a = 2; b = default(T); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,18): error CS0411: The type arguments for method 'C1.Deconstruct<T>(out int, out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // (x, y) = new C1(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new C1()").WithArguments("C1.Deconstruct<T>(out int, out T)").WithLocation(9, 18), // (9,18): error CS8129: No Deconstruct instance or extension method was found for type 'C1', with 2 out parameters and a void return type. // (x, y) = new C1(); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C1()").WithArguments("C1", "2").WithLocation(9, 18) ); } [Fact] public void AmbiguousDeconstructGenericMethod() { string source = @" class C { static void Main() { long x; string y; (x, y) = new C1(); System.Console.Write($""{x} {y}""); } } class C1 { public void Deconstruct<T>(out int a, out T b) { a = 2; b = default(T); } public void Deconstruct(out int a, out string b) { a = 2; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "2 hello"); comp.VerifyDiagnostics(); } [Fact] public void NestedTupleAssignment() { string source = @" class C { static void Main() { long x; string y, z; (x, (y, z)) = ((int)1, (""a"", ""b"")); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(x, (y, z))", lhs.ToString()); Assert.Equal("(System.Int64 x, (System.String y, System.String z))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int64 x, (System.String y, System.String z))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: "1 a b", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void NestedTypelessTupleAssignment() { string source = @" class C { static void Main() { string x, y, z; (x, (y, z)) = (null, (null, null)); System.Console.WriteLine(""nothing"" + x + y + z); } } "; var comp = CompileAndVerify(source, expectedOutput: "nothing"); comp.VerifyDiagnostics(); } [Fact] public void NestedDeconstructAssignment() { string source = @" class C { static void Main() { int x; string y, z; (x, (y, z)) = new D1(); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } class D1 { public void Deconstruct(out int item1, out D2 item2) { item1 = 1; item2 = new D2(); } } class D2 { public void Deconstruct(out string item1, out string item2) { item1 = ""a""; item2 = ""b""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 a b"); comp.VerifyDiagnostics(); } [Fact] public void NestedMixedAssignment1() { string source = @" class C { static void Main() { int x, y, z; (x, (y, z)) = (1, new D1()); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } class D1 { public void Deconstruct(out int item1, out int item2) { item1 = 2; item2 = 3; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 3"); comp.VerifyDiagnostics(); } [Fact] public void NestedMixedAssignment2() { string source = @" class C { static void Main() { int x; string y, z; (x, (y, z)) = new D1(); System.Console.WriteLine(x + "" "" + y + "" "" + z); } } class D1 { public void Deconstruct(out int item1, out (string, string) item2) { item1 = 1; item2 = (""a"", ""b""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 a b"); comp.VerifyDiagnostics(); } [Fact] public void VerifyNestedExecutionOrder() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } int z { set { Console.WriteLine($""setZ""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; } C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; } static void Main() { C c = new C(); (c.getHolderForX().x, (c.getHolderForY().y, c.getHolderForZ().z)) = c.getDeconstructReceiver(); } public void Deconstruct(out D1 x, out C1 t) { x = new D1(); t = new C1(); Console.WriteLine(""Deconstruct1""); } } class C1 { public void Deconstruct(out D2 y, out D3 z) { y = new D2(); z = new D3(); Console.WriteLine(""Deconstruct2""); } } class D1 { public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } class D3 { public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; } } "; string expected = @"getHolderforX getHolderforY getHolderforZ getDeconstructReceiver Deconstruct1 Deconstruct2 Conversion1 Conversion2 Conversion3 setX setY setZ "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyNestedExecutionOrder_Conditional() { string source = @" using System; class C { int x { set { Console.WriteLine($""setX""); } } int y { set { Console.WriteLine($""setY""); } } int z { set { Console.WriteLine($""setZ""); } } C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; } C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; } C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; } C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; } static void Main() { C c = new C(); bool b = false; (c.getHolderForX().x, (c.getHolderForY().y, c.getHolderForZ().z)) = b ? default : c.getDeconstructReceiver(); } public void Deconstruct(out D1 x, out C1 t) { x = new D1(); t = new C1(); Console.WriteLine(""Deconstruct1""); } } class C1 { public void Deconstruct(out D2 y, out D3 z) { y = new D2(); z = new D3(); Console.WriteLine(""Deconstruct2""); } } class D1 { public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; } } class D2 { public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; } } class D3 { public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; } } "; string expected = @"getHolderforX getHolderforY getHolderforZ getDeconstructReceiver Deconstruct1 Deconstruct2 Conversion1 Conversion2 Conversion3 setX setY setZ "; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void VerifyNestedExecutionOrder2() { string source = @" using System; class C { static LongInteger x1 { set { Console.WriteLine($""setX1 {value}""); } } static LongInteger x2 { set { Console.WriteLine($""setX2 {value}""); } } static LongInteger x3 { set { Console.WriteLine($""setX3 {value}""); } } static LongInteger x4 { set { Console.WriteLine($""setX4 {value}""); } } static LongInteger x5 { set { Console.WriteLine($""setX5 {value}""); } } static LongInteger x6 { set { Console.WriteLine($""setX6 {value}""); } } static LongInteger x7 { set { Console.WriteLine($""setX7 {value}""); } } static void Main() { ((x1, (x2, x3)), ((x4, x5), (x6, x7))) = Pair.Create(Pair.Create(new Integer(1), Pair.Create(new Integer(2), new Integer(3))), Pair.Create(Pair.Create(new Integer(4), new Integer(5)), Pair.Create(new Integer(6), new Integer(7)))); } } " + commonSource; string expected = @"Deconstructing ((1, (2, 3)), ((4, 5), (6, 7))) Deconstructing (1, (2, 3)) Deconstructing (2, 3) Deconstructing ((4, 5), (6, 7)) Deconstructing (4, 5) Deconstructing (6, 7) Converting 1 Converting 2 Converting 3 Converting 4 Converting 5 Converting 6 Converting 7 setX1 1 setX2 2 setX3 3 setX4 4 setX5 5 setX6 6 setX7 7"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void MixOfAssignments() { string source = @" class C { static void Main() { long x; string y; C a, b, c; c = new C(); (x, y) = a = b = c; System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/12400")] [WorkItem(12400, "https://github.com/dotnet/roslyn/issues/12400")] public void AssignWithPostfixOperator() { string source = @" class C { int state = 1; static void Main() { long x; string y; C c = new C(); (x, y) = c++; System.Console.WriteLine(x + "" "" + y); } public void Deconstruct(out int a, out string b) { a = state; b = ""hello""; } public static C operator ++(C c1) { return new C() { state = 2 }; } } "; // https://github.com/dotnet/roslyn/issues/12400 // we expect "2 hello" instead, which means the evaluation order is wrong var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(13631, "https://github.com/dotnet/roslyn/issues/13631")] public void DeconstructionDeclaration() { string source = @" class C { static void Main() { var (x1, x2) = (1, ""hello""); System.Console.WriteLine(x1 + "" "" + x2); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 32 (0x20) .maxstack 3 .locals init (int V_0, //x1 string V_1) //x2 IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldstr ""hello"" IL_0007: stloc.1 IL_0008: ldloca.s V_0 IL_000a: call ""string int.ToString()"" IL_000f: ldstr "" "" IL_0014: ldloc.1 IL_0015: call ""string string.Concat(string, string, string)"" IL_001a: call ""void System.Console.WriteLine(string)"" IL_001f: ret }"); } [Fact] public void NestedVarDeconstructionDeclaration() { string source = @" class C { static void Main() { var (x1, (x2, x3)) = (1, (2, ""hello"")); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().First(); Assert.Equal(@"var (x1, (x2, x3))", lhs.ToString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhs).Symbol); var lhsNested = tree.GetRoot().DescendantNodes().OfType<ParenthesizedVariableDesignationSyntax>().ElementAt(1); Assert.Equal(@"(x2, x3)", lhsNested.ToString()); Assert.Null(model.GetTypeInfo(lhsNested).Type); Assert.Null(model.GetSymbolInfo(lhsNested).Symbol); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void NestedVarDeconstructionDeclaration_WithCSharp7_1() { string source = @" class C { static void Main() { (int x1, var (x2, (x3, x4)), var x5) = (1, (2, (3, ""hello"")), 5); System.Console.WriteLine($""{x1} {x2} {x3} {x4} {x5}""); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(int x1, var (x2, (x3, x4)), var x5)", lhs.ToString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, (System.Int32 x3, System.String x4)), System.Int32 x5)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhs).Symbol); var x234 = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1); Assert.Equal(@"var (x2, (x3, x4))", x234.ToString()); Assert.Equal("(System.Int32 x2, (System.Int32 x3, System.String x4))", model.GetTypeInfo(x234).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x234).Symbol); var x34 = tree.GetRoot().DescendantNodes().OfType<ParenthesizedVariableDesignationSyntax>().ElementAt(1); Assert.Equal(@"(x3, x4)", x34.ToString()); Assert.Null(model.GetTypeInfo(x34).Type); Assert.Null(model.GetSymbolInfo(x34).Symbol); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); var x4 = GetDeconstructionVariable(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForDeconstructionLocal(model, x4, x4Ref); var x5 = GetDeconstructionVariable(tree, "x5"); var x5Ref = GetReference(tree, "x5"); VerifyModelForDeconstructionLocal(model, x5, x5Ref); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 hello 5", sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics(); } [Fact] public void NestedVarDeconstructionAssignment_WithCSharp7_1() { string source = @" class C { static void Main() { int x1, x2, x3; (x1, (x2, x3)) = (1, (2, 3)); System.Console.WriteLine($""{x1} {x2} {x3}""); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x123 = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(x1, (x2, x3))", x123.ToString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.Int32 x3))", model.GetTypeInfo(x123).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x123).Symbol); var x23 = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(x2, x3)", x23.ToString()); Assert.Equal("(System.Int32 x2, System.Int32 x3)", model.GetTypeInfo(x23).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x23).Symbol); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 3", sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics(); } [Fact] public void NestedVarDeconstructionDeclaration2() { string source = @" class C { static void Main() { (var x1, var (x2, x3)) = (1, (2, ""hello"")); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal("(var x1, var (x2, x3))", lhs.ToString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhs).Symbol); var lhsNested = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1); Assert.Equal("var (x2, x3)", lhsNested.ToString()); Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).ConvertedType.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhsNested).Symbol); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void NestedVarDeconstructionDeclarationWithCSharp7_1() { string source = @" class C { static void Main() { (var x1, byte _, var (x2, x3)) = (1, 2, (3, ""hello"")); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal("(var x1, byte _, var (x2, x3))", lhs.ToString()); Assert.Equal("(System.Int32 x1, System.Byte, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x1, System.Byte, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhs).Symbol); var lhsNested = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(2); Assert.Equal("var (x2, x3)", lhsNested.ToString()); Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(lhsNested).Symbol); }; var comp = CompileAndVerify(source, sourceSymbolValidator: validator, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyDiagnostics(); } [Fact] public void NestedDeconstructionDeclaration() { string source = @" class C { static void Main() { (int x1, (int x2, string x3)) = (1, (2, ""hello"")); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); }; var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void VarMethodExists() { string source = @" class C { static void Main() { int x1 = 1; int x2 = 1; var (x1, x2); } static void var(int a, int b) { System.Console.WriteLine(""var""); } } "; var comp = CompileAndVerify(source, expectedOutput: "var"); comp.VerifyDiagnostics(); } [Fact] public void TypeMergingSuccess1() { string source = @" class C { static void Main() { (var (x1, x2), string x3) = ((1, 2), null); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; var comp = CompileAndVerify(source, expectedOutput: " 1 2"); comp.VerifyDiagnostics(); } [Fact] public void TypeMergingSuccess2() { string source = @" class C { static void Main() { (string x1, byte x2, var x3) = (null, 2, 3); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(string x1, byte x2, var x3)", lhs.ToString()); Assert.Equal("(System.String x1, System.Byte x2, System.Int32 x3)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); var literal = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(null, 2, 3)", literal.ToString()); Assert.Null(model.GetTypeInfo(literal).Type); Assert.Equal("(System.String, System.Byte, System.Int32)", model.GetTypeInfo(literal).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(literal).Kind); }; var comp = CompileAndVerify(source, expectedOutput: " 2 3", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void TypeMergingSuccess3() { string source = @" class C { static void Main() { (string x1, var x2) = (null, (1, 2)); System.Console.WriteLine(x1 + "" "" + x2); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(string x1, var x2)", lhs.ToString()); Assert.Equal("(System.String x1, (System.Int32, System.Int32) x2)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); var literal = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(null, (1, 2))", literal.ToString()); Assert.Null(model.GetTypeInfo(literal).Type); Assert.Equal("(System.String, (System.Int32, System.Int32))", model.GetTypeInfo(literal).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(literal).Kind); var nestedLiteral = literal.Arguments[1].Expression; Assert.Equal(@"(1, 2)", nestedLiteral.ToString()); Assert.Equal("(System.Int32, System.Int32)", model.GetTypeInfo(nestedLiteral).Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", model.GetTypeInfo(nestedLiteral).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(nestedLiteral).Kind); }; var comp = CompileAndVerify(source, expectedOutput: " (1, 2)", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void TypeMergingSuccess4() { string source = @" class C { static void Main() { ((string x1, byte x2, var x3), int x4) = (M(), 4); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4); } static (string, byte, int) M() { return (null, 2, 3); } } "; var comp = CompileAndVerify(source, expectedOutput: " 2 3 4"); comp.VerifyDiagnostics(); } [Fact] public void VarVarDeclaration() { string source = @" class C { static void Main() { (var (x1, x2), var x3) = Pair.Create(Pair.Create(1, ""hello""), 2); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } " + commonSource; string expected = @"Deconstructing ((1, hello), 2) Deconstructing (1, hello) 1 hello 2"; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); }; var comp = CompileAndVerify(source, expectedOutput: expected, parseOptions: TestOptions.Regular, sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } private static void VerifyModelForDeconstructionLocal(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForDeconstruction(model, decl, LocalDeclarationKind.DeconstructionVariable, references); } private static void VerifyModelForLocal(SemanticModel model, SingleVariableDesignationSyntax decl, LocalDeclarationKind kind, params IdentifierNameSyntax[] references) { VerifyModelForDeconstruction(model, decl, kind, references); } private static void VerifyModelForDeconstructionForeach(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForDeconstruction(model, decl, LocalDeclarationKind.ForEachIterationVariable, references); } private static void VerifyModelForDeconstruction(SemanticModel model, SingleVariableDesignationSyntax decl, LocalDeclarationKind kind, params IdentifierNameSyntax[] references) { var symbol = model.GetDeclaredSymbol(decl); Assert.Equal(decl.Identifier.ValueText, symbol.Name); Assert.Equal(kind, symbol.GetSymbol<LocalSymbol>().DeclarationKind); Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)decl)); Assert.Same(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier.ValueText).Single()); Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier.ValueText)); var local = symbol.GetSymbol<SourceLocalSymbol>(); var typeSyntax = GetTypeSyntax(decl); if (local.IsVar && local.Type.IsErrorType()) { Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol); } else { if (typeSyntax != null) { Assert.Equal(local.Type.GetPublicSymbol(), model.GetSymbolInfo(typeSyntax).Symbol); } } foreach (var reference in references) { Assert.Same(symbol, model.GetSymbolInfo(reference).Symbol); Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: decl.Identifier.ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier.ValueText)); Assert.Equal(local.Type.GetPublicSymbol(), model.GetTypeInfo(reference).Type); } } private static void VerifyModelForDeconstructionField(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references) { var field = (IFieldSymbol)model.GetDeclaredSymbol(decl); Assert.Equal(decl.Identifier.ValueText, field.Name); Assert.Equal(SymbolKind.Field, field.Kind); Assert.Same(field, model.GetDeclaredSymbol((SyntaxNode)decl)); Assert.Same(field, model.LookupSymbols(decl.SpanStart, name: decl.Identifier.ValueText).Single()); Assert.Equal(Accessibility.Private, field.DeclaredAccessibility); Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier.ValueText)); foreach (var reference in references) { Assert.Same(field, model.GetSymbolInfo(reference).Symbol); Assert.Same(field, model.LookupSymbols(reference.SpanStart, name: decl.Identifier.ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier.ValueText)); Assert.Equal(field.Type, model.GetTypeInfo(reference).Type); } } private static TypeSyntax GetTypeSyntax(SingleVariableDesignationSyntax decl) { return (decl.Parent as DeclarationExpressionSyntax)?.Type; } private static SingleVariableDesignationSyntax GetDeconstructionVariable(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == name).Single(); } private static IEnumerable<DiscardDesignationSyntax> GetDiscardDesignations(SyntaxTree tree) { return tree.GetRoot().DescendantNodes().OfType<DiscardDesignationSyntax>(); } private static IEnumerable<IdentifierNameSyntax> GetDiscardIdentifiers(SyntaxTree tree) { return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(i => i.Identifier.ContextualKind() == SyntaxKind.UnderscoreToken); } private static IdentifierNameSyntax GetReference(SyntaxTree tree, string name) { return GetReferences(tree, name).Single(); } private static IdentifierNameSyntax[] GetReferences(SyntaxTree tree, string name, int count) { var nameRef = GetReferences(tree, name).ToArray(); Assert.Equal(count, nameRef.Length); return nameRef; } private static IEnumerable<IdentifierNameSyntax> GetReferences(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == name); } [Fact] public void DeclarationWithActualVarType() { string source = @" class C { static void Main() { (var x1, int x2) = (new var(), 2); System.Console.WriteLine(x1 + "" "" + x2); } } class var { public override string ToString() { return ""var""; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("var", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); // extra checks on x2 var x2Type = GetTypeSyntax(x2); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: "var 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void DeclarationWithImplicitVarType() { string source = @" class C { static void Main() { (var x1, var x2) = (1, 2); var (x3, x4) = (3, 4); System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionLocal(model, x3, x3Ref); var x4 = GetDeconstructionVariable(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForDeconstructionLocal(model, x4, x4Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x1Type)); var x34Var = (DeclarationExpressionSyntax)x3.Parent.Parent; Assert.Equal("var", x34Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x34Var.Type).Symbol); // The var in `var (x3, x4)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void DeclarationWithAliasedVarType() { string source = @" using var = D; class C { static void Main() { (var x1, int x2) = (new var(), 2); System.Console.WriteLine(x1 + "" "" + x2); } } class D { public override string ToString() { return ""var""; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("D", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); var x1Alias = model.GetAliasInfo(x1Type); Assert.Equal(SymbolKind.NamedType, x1Alias.Target.Kind); Assert.Equal("D", x1Alias.Target.ToDisplayString()); // extra checks on x2 var x2Type = GetTypeSyntax(x2); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x2Type)); }; var comp = CompileAndVerify(source, expectedOutput: "var 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForWithImplicitVarType() { string source = @" class C { static void Main() { for (var (x1, x2) = (1, 2); x1 < 2; (x1, x2) = (x1 + 1, x2 + 1)) { System.Console.WriteLine(x1 + "" "" + x2); } } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 4); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReferences(tree, "x2", 3); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForWithVarDeconstructInitializersCanParse() { string source = @" using System; class C { static void Main() { int x3; for (var (x1, x2) = (1, 2), x3 = 3; true; ) { Console.WriteLine(x1); Console.WriteLine(x2); Console.WriteLine(x3); break; } } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); }; var comp = CompileAndVerify(source, expectedOutput: @"1 2 3", sourceSymbolValidator: validator); comp.VerifyDiagnostics( // this is permitted now, as it is just an assignment expression ); } [Fact] public void ForWithActualVarType() { string source = @" class C { static void Main() { for ((int x1, var x2) = (1, new var()); x1 < 2; x1++) { System.Console.WriteLine(x1 + "" "" + x2); } } } class var { public override string ToString() { return ""var""; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 3); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); // extra checks on x2 var x2Type = GetTypeSyntax(x2); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind); Assert.Equal("var", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: "1 var", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForWithTypes() { string source = @" class C { static void Main() { for ((int x1, var x2) = (1, 2); x1 < 2; x1++) { System.Console.WriteLine(x1 + "" "" + x2); } } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 3); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); // extra checks on x1 var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); // extra checks on x2 var x2Type = GetTypeSyntax(x2); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForEachIEnumerableDeclarationWithImplicitVarType() { string source = @" using System.Collections.Generic; class C { static void Main() { foreach (var (x1, x2) in M()) { Print(x1, x2); } } static IEnumerable<(int, int)> M() { yield return (1, 2); } static void Print(object a, object b) { System.Console.WriteLine(a + "" "" + b); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Equal("(System.Int32 x1, System.Int32 x2)", model.GetTypeInfo(x12Var).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol // verify deconstruction info var deconstructionForeach = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single(); var deconstructionInfo = model.GetDeconstructionInfo(deconstructionForeach); Assert.Null(deconstructionInfo.Method); Assert.Null(deconstructionInfo.Conversion); var nested = deconstructionInfo.Nested; Assert.Equal(2, nested.Length); Assert.Null(nested[0].Method); Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind); Assert.Empty(nested[0].Nested); Assert.Null(nested[1].Method); Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind); Assert.Empty(nested[1].Nested); }; var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); var comp7_1 = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1); comp7_1.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 70 (0x46) .maxstack 2 .locals init (System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>> V_0, int V_1, //x1 int V_2) //x2 IL_0000: call ""System.Collections.Generic.IEnumerable<System.ValueTuple<int, int>> C.M()"" IL_0005: callvirt ""System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>> System.Collections.Generic.IEnumerable<System.ValueTuple<int, int>>.GetEnumerator()"" IL_000a: stloc.0 .try { IL_000b: br.s IL_0031 IL_000d: ldloc.0 IL_000e: callvirt ""System.ValueTuple<int, int> System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>>.Current.get"" IL_0013: dup IL_0014: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0019: stloc.1 IL_001a: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_001f: stloc.2 IL_0020: ldloc.1 IL_0021: box ""int"" IL_0026: ldloc.2 IL_0027: box ""int"" IL_002c: call ""void C.Print(object, object)"" IL_0031: ldloc.0 IL_0032: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_0037: brtrue.s IL_000d IL_0039: leave.s IL_0045 } finally { IL_003b: ldloc.0 IL_003c: brfalse.s IL_0044 IL_003e: ldloc.0 IL_003f: callvirt ""void System.IDisposable.Dispose()"" IL_0044: endfinally } IL_0045: ret }"); } [Fact] public void ForEachSZArrayDeclarationWithImplicitVarType() { string source = @" class C { static void Main() { foreach (var (x1, x2) in M()) { System.Console.Write(x1 + "" "" + x2 + "" - ""); } } static (int, int)[] M() { return new[] { (1, 2), (3, 4) }; } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); var symbol = model.GetDeclaredSymbol(x1); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 -", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 75 (0x4b) .maxstack 4 .locals init (System.ValueTuple<int, int>[] V_0, int V_1, int V_2, //x1 int V_3) //x2 IL_0000: call ""System.ValueTuple<int, int>[] C.M()"" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 IL_0008: br.s IL_0044 IL_000a: ldloc.0 IL_000b: ldloc.1 IL_000c: ldelem ""System.ValueTuple<int, int>"" IL_0011: dup IL_0012: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0017: stloc.2 IL_0018: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_001d: stloc.3 IL_001e: ldloca.s V_2 IL_0020: call ""string int.ToString()"" IL_0025: ldstr "" "" IL_002a: ldloca.s V_3 IL_002c: call ""string int.ToString()"" IL_0031: ldstr "" - "" IL_0036: call ""string string.Concat(string, string, string, string)"" IL_003b: call ""void System.Console.Write(string)"" IL_0040: ldloc.1 IL_0041: ldc.i4.1 IL_0042: add IL_0043: stloc.1 IL_0044: ldloc.1 IL_0045: ldloc.0 IL_0046: ldlen IL_0047: conv.i4 IL_0048: blt.s IL_000a IL_004a: ret }"); } [Fact] public void ForEachMDArrayDeclarationWithImplicitVarType() { string source = @" class C { static void Main() { foreach (var (x1, x2) in M()) { Print(x1, x2); } } static (int, int)[,] M() { return new (int, int)[2, 2] { { (1, 2), (3, 4) }, { (5, 6), (7, 8) } }; } static void Print(object a, object b) { System.Console.Write(a + "" "" + b + "" - ""); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 - 5 6 - 7 8 -", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 106 (0x6a) .maxstack 3 .locals init (System.ValueTuple<int, int>[,] V_0, int V_1, int V_2, int V_3, int V_4, int V_5, //x1 int V_6) //x2 IL_0000: call ""System.ValueTuple<int, int>[,] C.M()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: callvirt ""int System.Array.GetUpperBound(int)"" IL_000d: stloc.1 IL_000e: ldloc.0 IL_000f: ldc.i4.1 IL_0010: callvirt ""int System.Array.GetUpperBound(int)"" IL_0015: stloc.2 IL_0016: ldloc.0 IL_0017: ldc.i4.0 IL_0018: callvirt ""int System.Array.GetLowerBound(int)"" IL_001d: stloc.3 IL_001e: br.s IL_0065 IL_0020: ldloc.0 IL_0021: ldc.i4.1 IL_0022: callvirt ""int System.Array.GetLowerBound(int)"" IL_0027: stloc.s V_4 IL_0029: br.s IL_005c IL_002b: ldloc.0 IL_002c: ldloc.3 IL_002d: ldloc.s V_4 IL_002f: call ""(int, int)[*,*].Get"" IL_0034: dup IL_0035: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003a: stloc.s V_5 IL_003c: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0041: stloc.s V_6 IL_0043: ldloc.s V_5 IL_0045: box ""int"" IL_004a: ldloc.s V_6 IL_004c: box ""int"" IL_0051: call ""void C.Print(object, object)"" IL_0056: ldloc.s V_4 IL_0058: ldc.i4.1 IL_0059: add IL_005a: stloc.s V_4 IL_005c: ldloc.s V_4 IL_005e: ldloc.2 IL_005f: ble.s IL_002b IL_0061: ldloc.3 IL_0062: ldc.i4.1 IL_0063: add IL_0064: stloc.3 IL_0065: ldloc.3 IL_0066: ldloc.1 IL_0067: ble.s IL_0020 IL_0069: ret }"); } [Fact] public void ForEachStringDeclarationWithImplicitVarType() { string source = @" class C { static void Main() { foreach (var (x1, x2) in M()) { Print(x1, x2); } } static string M() { return ""123""; } static void Print(object a, object b) { System.Console.Write(a + "" "" + b + "" - ""); } } static class Extension { public static void Deconstruct(this char value, out int item1, out int item2) { item1 = item2 = System.Int32.Parse(value.ToString()); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); // extra check on var var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x12Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 1 - 2 2 - 3 3 - ", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 60 (0x3c) .maxstack 3 .locals init (string V_0, int V_1, int V_2, //x2 int V_3, int V_4) IL_0000: call ""string C.M()"" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 IL_0008: br.s IL_0032 IL_000a: ldloc.0 IL_000b: ldloc.1 IL_000c: callvirt ""char string.this[int].get"" IL_0011: ldloca.s V_3 IL_0013: ldloca.s V_4 IL_0015: call ""void Extension.Deconstruct(char, out int, out int)"" IL_001a: ldloc.3 IL_001b: ldloc.s V_4 IL_001d: stloc.2 IL_001e: box ""int"" IL_0023: ldloc.2 IL_0024: box ""int"" IL_0029: call ""void C.Print(object, object)"" IL_002e: ldloc.1 IL_002f: ldc.i4.1 IL_0030: add IL_0031: stloc.1 IL_0032: ldloc.1 IL_0033: ldloc.0 IL_0034: callvirt ""int string.Length.get"" IL_0039: blt.s IL_000a IL_003b: ret }"); } [Fact] [WorkItem(22495, "https://github.com/dotnet/roslyn/issues/22495")] public void ForEachCollectionSymbol() { string source = @" using System.Collections.Generic; class Deconstructable { void M(IEnumerable<Deconstructable> x) { foreach (var (y1, y2) in x) { } } void Deconstruct(out int i, out int j) { i = 0; j = 0; } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var collection = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single().Expression; Assert.Equal("x", collection.ToString()); var symbol = model.GetSymbolInfo(collection).Symbol; Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("x", symbol.Name); Assert.Equal("System.Collections.Generic.IEnumerable<Deconstructable> x", symbol.ToTestDisplayString()); } [Fact] public void ForEachIEnumerableDeclarationWithNesting() { string source = @" using System.Collections.Generic; class C { static void Main() { foreach ((int x1, var (x2, x3), (int x4, int x5)) in M()) { System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - ""); } } static IEnumerable<(int, (int, int), (int, int))> M() { yield return (1, (2, 3), (4, 5)); yield return (6, (7, 8), (9, 10)); } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionForeach(model, x3, x3Ref); var x4 = GetDeconstructionVariable(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForDeconstructionForeach(model, x4, x4Ref); var x5 = GetDeconstructionVariable(tree, "x5"); var x5Ref = GetReference(tree, "x5"); VerifyModelForDeconstructionForeach(model, x5, x5Ref); // extra check on var var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent; Assert.Equal("var", x23Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol }; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -", sourceSymbolValidator: validator); comp.VerifyDiagnostics(); } [Fact] public void ForEachSZArrayDeclarationWithNesting() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3), (int x4, int x5)) in M()) { System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - ""); } } static (int, (int, int), (int, int))[] M() { return new[] { (1, (2, 3), (4, 5)), (6, (7, 8), (9, 10)) }; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -"); comp.VerifyDiagnostics(); } [Fact] public void ForEachMDArrayDeclarationWithNesting() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3), (int x4, int x5)) in M()) { System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - ""); } } static (int, (int, int), (int, int))[,] M() { return new(int, (int, int), (int, int))[1, 2] { { (1, (2, 3), (4, 5)), (6, (7, 8), (9, 10)) } }; } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -"); comp.VerifyDiagnostics(); } [Fact] public void ForEachStringDeclarationWithNesting() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3)) in M()) { System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" - ""); } } static string M() { return ""12""; } } static class Extension { public static void Deconstruct(this char value, out int item1, out (int, int) item2) { item1 = System.Int32.Parse(value.ToString()); item2 = (item1, item1); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 1 1 - 2 2 2 - "); comp.VerifyDiagnostics(); } [Fact] public void DeconstructExtensionOnInterface() { string source = @" public interface Interface { } class C : Interface { static void Main() { var (x, y) = new C(); System.Console.Write($""{x} {y}""); } } static class Extension { public static void Deconstruct(this Interface value, out int item1, out string item2) { item1 = 42; item2 = ""hello""; } } "; var comp = CompileAndVerify(source, expectedOutput: "42 hello"); comp.VerifyDiagnostics(); } [Fact] public void ForEachIEnumerableDeclarationWithDeconstruct() { string source = @" using System.Collections.Generic; class C { static void Main() { foreach ((long x1, var (x2, x3)) in M()) { Print(x1, x2, x3); } } static IEnumerable<Pair<int, Pair<int, int>>> M() { yield return Pair.Create(1, Pair.Create(2, 3)); yield return Pair.Create(4, Pair.Create(5, 6)); } static void Print(object a, object b, object c) { System.Console.WriteLine(a + "" "" + b + "" "" + c); } } " + commonSource; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionForeach(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionForeach(model, x2, x2Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeconstructionForeach(model, x3, x3Ref); // extra check on var var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent; Assert.Equal("var", x23Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol }; string expected = @"Deconstructing (1, (2, 3)) Deconstructing (2, 3) 1 2 3 Deconstructing (4, (5, 6)) Deconstructing (5, 6) 4 5 6"; var comp = CompileAndVerify(source, expectedOutput: expected, sourceSymbolValidator: validator); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 90 (0x5a) .maxstack 3 .locals init (System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>> V_0, int V_1, //x2 int V_2, //x3 int V_3, Pair<int, int> V_4, int V_5, int V_6) IL_0000: call ""System.Collections.Generic.IEnumerable<Pair<int, Pair<int, int>>> C.M()"" IL_0005: callvirt ""System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>> System.Collections.Generic.IEnumerable<Pair<int, Pair<int, int>>>.GetEnumerator()"" IL_000a: stloc.0 .try { IL_000b: br.s IL_0045 IL_000d: ldloc.0 IL_000e: callvirt ""Pair<int, Pair<int, int>> System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>>.Current.get"" IL_0013: ldloca.s V_3 IL_0015: ldloca.s V_4 IL_0017: callvirt ""void Pair<int, Pair<int, int>>.Deconstruct(out int, out Pair<int, int>)"" IL_001c: ldloc.s V_4 IL_001e: ldloca.s V_5 IL_0020: ldloca.s V_6 IL_0022: callvirt ""void Pair<int, int>.Deconstruct(out int, out int)"" IL_0027: ldloc.3 IL_0028: conv.i8 IL_0029: ldloc.s V_5 IL_002b: stloc.1 IL_002c: ldloc.s V_6 IL_002e: stloc.2 IL_002f: box ""long"" IL_0034: ldloc.1 IL_0035: box ""int"" IL_003a: ldloc.2 IL_003b: box ""int"" IL_0040: call ""void C.Print(object, object, object)"" IL_0045: ldloc.0 IL_0046: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_004b: brtrue.s IL_000d IL_004d: leave.s IL_0059 } finally { IL_004f: ldloc.0 IL_0050: brfalse.s IL_0058 IL_0052: ldloc.0 IL_0053: callvirt ""void System.IDisposable.Dispose()"" IL_0058: endfinally } IL_0059: ret } "); } [Fact] public void ForEachSZArrayDeclarationWithDeconstruct() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3)) in M()) { System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } static Pair<int, Pair<int, int>>[] M() { return new[] { Pair.Create(1, Pair.Create(2, 3)), Pair.Create(4, Pair.Create(5, 6)) }; } } " + commonSource; string expected = @"Deconstructing (1, (2, 3)) Deconstructing (2, 3) 1 2 3 Deconstructing (4, (5, 6)) Deconstructing (5, 6) 4 5 6"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void ForEachMDArrayDeclarationWithDeconstruct() { string source = @" class C { static void Main() { foreach ((int x1, var (x2, x3)) in M()) { System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3); } } static Pair<int, Pair<int, int>>[,] M() { return new Pair<int, Pair<int, int>> [1, 2] { { Pair.Create(1, Pair.Create(2, 3)), Pair.Create(4, Pair.Create(5, 6)) } }; } } " + commonSource; string expected = @"Deconstructing (1, (2, 3)) Deconstructing (2, 3) 1 2 3 Deconstructing (4, (5, 6)) Deconstructing (5, 6) 4 5 6"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [Fact] public void ForEachWithExpressionBody() { string source = @" class C { static void Main() { foreach (var (x1, x2) in new[] { (1, 2), (3, 4) }) System.Console.Write(x1 + "" "" + x2 + "" - ""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 -"); comp.VerifyDiagnostics(); } [Fact] public void ForEachCreatesNewVariables() { string source = @" class C { static void Main() { var lambdas = new System.Action[2]; int index = 0; foreach (var (x1, x2) in M()) { lambdas[index] = () => { System.Console.Write(x1 + "" ""); }; index++; } lambdas[0](); lambdas[1](); } static (int, int)[] M() { return new[] { (0, 0), (10, 10) }; } } "; var comp = CompileAndVerify(source, expectedOutput: "0 10 "); comp.VerifyDiagnostics(); } [Fact] public void TupleDeconstructionIntoDynamicArrayIndexer() { string source = @" class C { static void Main() { dynamic x = new string[] { """", """" }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic x) { (x[0], x[1]) = (""hello"", ""world""); } } "; var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void IntTupleDeconstructionIntoDynamicArrayIndexer() { string source = @" class C { static void Main() { dynamic x = new int[] { 1, 2 }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic x) { (x[0], x[1]) = (3, 4); } } "; var comp = CompileAndVerify(source, expectedOutput: "3 4", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructionIntoDynamicArrayIndexer() { string source = @" class C { static void Main() { dynamic x = new string[] { """", """" }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic x) { (x[0], x[1]) = new C(); } public void Deconstruct(out string a, out string b) { a = ""hello""; b = ""world""; } } "; var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void TupleDeconstructionIntoDynamicArray() { string source = @" class C { static void Main() { dynamic[] x = new string[] { """", """" }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic[] x) { (x[0], x[1]) = (""hello"", ""world""); } } "; var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructionIntoDynamicArray() { string source = @" class C { static void Main() { dynamic[] x = new string[] { """", """" }; M(x); System.Console.WriteLine($""{x[0]} {x[1]}""); } static void M(dynamic[] x) { (x[0], x[1]) = new C(); } public void Deconstruct(out string a, out string b) { a = ""hello""; b = ""world""; } } "; var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void DeconstructionIntoDynamicMember() { string source = @" class C { static void Main() { dynamic x = System.ValueTuple.Create(1, 2); (x.Item1, x.Item2) = new C(); System.Console.WriteLine($""{x.Item1} {x.Item2}""); } public void Deconstruct(out int a, out int b) { a = 3; b = 4; } } "; var comp = CompileAndVerify(source, expectedOutput: "3 4", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void FieldAndLocalWithSameName() { string source = @" class C { public int x = 3; static void Main() { new C().M(); } void M() { var (x, y) = (1, 2); System.Console.Write($""{x} {y} {this.x}""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 2 3"); comp.VerifyDiagnostics(); } [Fact] public void NoGlobalDeconstructionUnlessScript() { string source = @" class C { var (x, y) = (1, 2); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,11): error CS1001: Identifier expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(4, 11), // (4,14): error CS1001: Identifier expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 14), // (4,16): error CS1002: ; expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_SemicolonExpected, "=").WithLocation(4, 16), // (4,16): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(4, 16), // (4,19): error CS1031: Type expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_TypeExpected, "1").WithLocation(4, 19), // (4,19): error CS8124: Tuple must contain at least two elements. // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_TupleTooFewElements, "1").WithLocation(4, 19), // (4,19): error CS1026: ) expected // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_CloseParenExpected, "1").WithLocation(4, 19), // (4,19): error CS1519: Invalid token '1' in class, record, struct, or interface member declaration // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "1").WithArguments("1").WithLocation(4, 19), // (4,5): error CS1520: Method must have a return type // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_MemberNeedsType, "var").WithLocation(4, 5), // (4,5): error CS0501: 'C.C(x, y)' must declare a body because it is not marked abstract, extern, or partial // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "var").WithArguments("C.C(x, y)").WithLocation(4, 5), // (4,10): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?) // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x").WithLocation(4, 10), // (4,13): error CS0246: The type or namespace name 'y' could not be found (are you missing a using directive or an assembly reference?) // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "y").WithArguments("y").WithLocation(4, 13) ); var nodes = comp.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf(); Assert.False(nodes.Any(n => n.Kind() == SyntaxKind.SimpleAssignmentExpression)); } [Fact] public void SimpleDeconstructionInScript() { var source = @" using alias = System.Int32; (string x, alias y) = (""hello"", 42); System.Console.Write($""{x} {y}""); "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); var xRef = GetReference(tree, "x"); Assert.Equal("System.String Script.x", xSymbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x, xRef); var y = GetDeconstructionVariable(tree, "y"); var ySymbol = model.GetDeclaredSymbol(y); var yRef = GetReference(tree, "y"); Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, y, yRef); // extra checks on x var xType = GetTypeSyntax(x); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(xType).Symbol.Kind); Assert.Equal("string", model.GetSymbolInfo(xType).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(xType)); // extra checks on y var yType = GetTypeSyntax(y); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(yType).Symbol.Kind); Assert.Equal("int", model.GetSymbolInfo(yType).Symbol.ToDisplayString()); Assert.Equal("alias=System.Int32", model.GetAliasInfo(yType).ToTestDisplayString()); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42", sourceSymbolValidator: validator); verifier.VerifyIL("<<Initialize>>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 129 (0x81) .maxstack 3 .locals init (int V_0, object V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""int <<Initialize>>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldarg.0 IL_0008: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_000d: ldstr ""hello"" IL_0012: stfld ""string x"" IL_0017: ldarg.0 IL_0018: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_001d: ldc.i4.s 42 IL_001f: stfld ""int y"" IL_0024: ldstr ""{0} {1}"" IL_0029: ldarg.0 IL_002a: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_002f: ldfld ""string x"" IL_0034: ldarg.0 IL_0035: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_003a: ldfld ""int y"" IL_003f: box ""int"" IL_0044: call ""string string.Format(string, object, object)"" IL_0049: call ""void System.Console.Write(string)"" IL_004e: nop IL_004f: ldnull IL_0050: stloc.1 IL_0051: leave.s IL_006b } catch System.Exception { IL_0053: stloc.2 IL_0054: ldarg.0 IL_0055: ldc.i4.s -2 IL_0057: stfld ""int <<Initialize>>d__0.<>1__state"" IL_005c: ldarg.0 IL_005d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0062: ldloc.2 IL_0063: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)"" IL_0068: nop IL_0069: leave.s IL_0080 } IL_006b: ldarg.0 IL_006c: ldc.i4.s -2 IL_006e: stfld ""int <<Initialize>>d__0.<>1__state"" IL_0073: ldarg.0 IL_0074: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0079: ldloc.1 IL_007a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)"" IL_007f: nop IL_0080: ret }"); } [Fact] public void GlobalDeconstructionOutsideScript() { var source = @" (string x, int y) = (""hello"", 42); System.Console.Write(x); System.Console.Write(y); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var nodes = comp.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf(); Assert.True(nodes.Any(n => n.Kind() == SyntaxKind.SimpleAssignmentExpression)); CompileAndVerify(comp, expectedOutput: "hello42"); } [Fact] public void NestedDeconstructionInScript() { var source = @" (string x, (int y, int z)) = (""hello"", (42, 43)); System.Console.Write($""{x} {y} {z}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 43"); } [Fact] public void VarDeconstructionInScript() { var source = @" (var x, var y) = (""hello"", 42); System.Console.Write($""{x} {y}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42"); } [Fact] public void NestedVarDeconstructionInScript() { var source = @" (var x1, var (x2, x3)) = (""hello"", (42, 43)); System.Console.Write($""{x1} {x2} {x3}""); "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.String Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); var x2Ref = GetReference(tree, "x2"); Assert.Equal("System.Int32 Script.x2", x2Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x2, x2Ref); // extra checks on x1's var var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("string", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x1Type)); // extra check on x2 and x3's var var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent; Assert.Equal("var", x23Var.Type.ToString()); Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 43", sourceSymbolValidator: validator); } [Fact] public void EvaluationOrderForDeconstructionInScript() { var source = @" (int, int) M(out int x) { x = 1; return (2, 3); } var (x2, x3) = M(out var x1); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "1 2 3"); verifier.VerifyIL("<<Initialize>>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 178 (0xb2) .maxstack 4 .locals init (int V_0, object V_1, System.ValueTuple<int, int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int <<Initialize>>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldarg.0 IL_0008: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_000d: ldarg.0 IL_000e: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_0013: ldflda ""int x1"" IL_0018: call ""System.ValueTuple<int, int> M(out int)"" IL_001d: stloc.2 IL_001e: ldarg.0 IL_001f: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_0024: ldloc.2 IL_0025: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_002a: stfld ""int x2"" IL_002f: ldarg.0 IL_0030: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_0035: ldloc.2 IL_0036: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_003b: stfld ""int x3"" IL_0040: ldstr ""{0} {1} {2}"" IL_0045: ldarg.0 IL_0046: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_004b: ldfld ""int x1"" IL_0050: box ""int"" IL_0055: ldarg.0 IL_0056: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_005b: ldfld ""int x2"" IL_0060: box ""int"" IL_0065: ldarg.0 IL_0066: ldfld ""Script <<Initialize>>d__0.<>4__this"" IL_006b: ldfld ""int x3"" IL_0070: box ""int"" IL_0075: call ""string string.Format(string, object, object, object)"" IL_007a: call ""void System.Console.Write(string)"" IL_007f: nop IL_0080: ldnull IL_0081: stloc.1 IL_0082: leave.s IL_009c } catch System.Exception { IL_0084: stloc.3 IL_0085: ldarg.0 IL_0086: ldc.i4.s -2 IL_0088: stfld ""int <<Initialize>>d__0.<>1__state"" IL_008d: ldarg.0 IL_008e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_0093: ldloc.3 IL_0094: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)"" IL_0099: nop IL_009a: leave.s IL_00b1 } IL_009c: ldarg.0 IL_009d: ldc.i4.s -2 IL_009f: stfld ""int <<Initialize>>d__0.<>1__state"" IL_00a4: ldarg.0 IL_00a5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder"" IL_00aa: ldloc.1 IL_00ab: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)"" IL_00b0: nop IL_00b1: ret } "); } [Fact] public void DeconstructionForEachInScript() { var source = @" foreach ((string x1, var (x2, x3)) in new[] { (""hello"", (42, ""world"")) }) { System.Console.Write($""{x1} {x2} {x3}""); } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); Assert.Equal("System.String x1", x1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, x1Symbol.Kind); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); Assert.Equal("System.Int32 x2", x2Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, x2Symbol.Kind); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 world", sourceSymbolValidator: validator); } [Fact] public void DeconstructionInForLoopInScript() { var source = @" for ((string x1, var (x2, x3)) = (""hello"", (42, ""world"")); ; ) { System.Console.Write($""{x1} {x2} {x3}""); break; } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); Assert.Equal("System.String x1", x1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, x1Symbol.Kind); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); Assert.Equal("System.Int32 x2", x2Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, x2Symbol.Kind); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 world", sourceSymbolValidator: validator); } [Fact] public void DeconstructionInCSharp6Script() { var source = @" var (x, y) = (1, 2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp6), options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (2,5): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(x, y)").WithArguments("tuples", "7.0").WithLocation(2, 5), // (2,14): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7 or greater. // var (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2)").WithArguments("tuples", "7.0").WithLocation(2, 14) ); } [Fact] public void InvalidDeconstructionInScript() { var source = @" int (x, y) = (1, 2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (2,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // int (x, y) = (1, 2); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x, y)").WithLocation(2, 5) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString()); var xType = ((IFieldSymbol)xSymbol).Type; Assert.False(xType.IsErrorType()); Assert.Equal("System.Int32", xType.ToTestDisplayString()); var y = GetDeconstructionVariable(tree, "y"); var ySymbol = model.GetDeclaredSymbol(y); Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString()); var yType = ((IFieldSymbol)ySymbol).Type; Assert.False(yType.IsErrorType()); Assert.Equal("System.Int32", yType.ToTestDisplayString()); } [Fact] public void InvalidDeconstructionInScript_2() { var source = @" (int (x, y), int z) = ((1, 2), 3); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (2,6): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // (int (x, y), int z) = ((1, 2), 3); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x, y)").WithLocation(2, 6) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString()); var xType = ((IFieldSymbol)xSymbol).Type; Assert.False(xType.IsErrorType()); Assert.Equal("System.Int32", xType.ToTestDisplayString()); var y = GetDeconstructionVariable(tree, "y"); var ySymbol = model.GetDeclaredSymbol(y); Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString()); var yType = ((IFieldSymbol)ySymbol).Type; Assert.False(yType.IsErrorType()); Assert.Equal("System.Int32", yType.ToTestDisplayString()); } [Fact] public void NameConflictInDeconstructionInScript() { var source = @" int x1; var (x1, x2) = (1, 2); System.Console.Write(x1); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (3,6): error CS0102: The type 'Script' already contains a definition for 'x1' // var (x1, x2) = (1, 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x1").WithArguments("Script", "x1").WithLocation(3, 6), // (4,22): error CS0229: Ambiguity between 'x1' and 'x1' // System.Console.Write(x1); Diagnostic(ErrorCode.ERR_AmbigMember, "x1").WithArguments("x1", "x1").WithLocation(4, 22) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var firstX1 = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "x1").Single(); var firstX1Symbol = model.GetDeclaredSymbol(firstX1); Assert.Equal("System.Int32 Script.x1", firstX1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, firstX1Symbol.Kind); var secondX1 = GetDeconstructionVariable(tree, "x1"); var secondX1Symbol = model.GetDeclaredSymbol(secondX1); Assert.Equal("System.Int32 Script.x1", secondX1Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, secondX1Symbol.Kind); Assert.NotEqual(firstX1Symbol, secondX1Symbol); } [Fact] public void NameConflictInDeconstructionInScript2() { var source = @" var (x, y) = (1, 2); var (z, y) = (1, 2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (3,9): error CS0102: The type 'Script' already contains a definition for 'y' // var (z, y) = (1, 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "y").WithArguments("Script", "y").WithLocation(3, 9) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var firstY = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "y").First(); var firstYSymbol = model.GetDeclaredSymbol(firstY); Assert.Equal("System.Int32 Script.y", firstYSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, firstYSymbol.Kind); var secondY = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "y").ElementAt(1); var secondYSymbol = model.GetDeclaredSymbol(secondY); Assert.Equal("System.Int32 Script.y", secondYSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, secondYSymbol.Kind); Assert.NotEqual(firstYSymbol, secondYSymbol); } [Fact] public void NameConflictInDeconstructionInScript3() { var source = @" var (x, (y, x)) = (1, (2, ""hello"")); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (2,13): error CS0102: The type 'Script' already contains a definition for 'x' // var (x, (y, x)) = (1, (2, "hello")); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x").WithArguments("Script", "x").WithLocation(2, 13) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var firstX = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "x").First(); var firstXSymbol = model.GetDeclaredSymbol(firstX); Assert.Equal("System.Int32 Script.x", firstXSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, firstXSymbol.Kind); var secondX = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "x").ElementAt(1); var secondXSymbol = model.GetDeclaredSymbol(secondX); Assert.Equal("System.String Script.x", secondXSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, secondXSymbol.Kind); Assert.NotEqual(firstXSymbol, secondXSymbol); } [Fact] public void UnassignedUsedInDeconstructionInScript() { var source = @" System.Console.Write(x); var (x, y) = (1, 2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "0"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); var xRef = GetReference(tree, "x"); Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x, xRef); var xType = ((IFieldSymbol)xSymbol).Type; Assert.False(xType.IsErrorType()); Assert.Equal("System.Int32", xType.ToTestDisplayString()); } [Fact] public void FailedInferenceInDeconstructionInScript() { var source = @" var (x, y) = (1, null); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.GetDeclarationDiagnostics().Verify( // (2,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (1, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(2, 6), // (2,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (1, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(2, 9) ); comp.VerifyDiagnostics( // (2,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (1, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(2, 6), // (2,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (1, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(2, 9) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xSymbol = model.GetDeclaredSymbol(x); Assert.Equal("var Script.x", xSymbol.ToTestDisplayString()); var xType = xSymbol.GetSymbol<FieldSymbol>().TypeWithAnnotations; Assert.True(xType.Type.IsErrorType()); Assert.Equal("var", xType.ToTestDisplayString()); var xTypeISymbol = xType.Type.GetPublicSymbol(); Assert.Equal(SymbolKind.ErrorType, xTypeISymbol.Kind); var y = GetDeconstructionVariable(tree, "y"); var ySymbol = model.GetDeclaredSymbol(y); Assert.Equal("var Script.y", ySymbol.ToTestDisplayString()); var yType = ((IFieldSymbol)ySymbol).Type; Assert.True(yType.IsErrorType()); Assert.Equal("var", yType.ToTestDisplayString()); } [Fact] public void FailedCircularInferenceInDeconstructionInScript() { var source = @" var (x1, x2) = (x2, x1); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.GetDeclarationDiagnostics().Verify( // (2,10): error CS7019: Type of 'x2' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (x1, x2) = (x2, x1); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x2").WithArguments("x2").WithLocation(2, 10), // (2,6): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (x1, x2) = (x2, x1); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 6) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("var Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x1Type = ((IFieldSymbol)x1Symbol).Type; Assert.True(x1Type.IsErrorType()); Assert.Equal("var", x1Type.Name); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); var x2Ref = GetReference(tree, "x2"); Assert.Equal("var Script.x2", x2Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x2, x2Ref); var x2Type = ((IFieldSymbol)x2Symbol).Type; Assert.True(x2Type.IsErrorType()); Assert.Equal("var", x2Type.Name); } [Fact] public void FailedCircularInferenceInDeconstructionInScript2() { var source = @" var (x1, x2) = (y1, y2); var (y1, y2) = (x1, x2); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.GetDeclarationDiagnostics().Verify( // (3,6): error CS7019: Type of 'y1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (y1, y2) = (x1, x2); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "y1").WithArguments("y1").WithLocation(3, 6), // (2,6): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (x1, x2) = (y1, y2); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 6), // (2,10): error CS7019: Type of 'x2' cannot be inferred since its initializer directly or indirectly refers to the definition. // var (x1, x2) = (y1, y2); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x2").WithArguments("x2").WithLocation(2, 10) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("var Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x1Type = ((IFieldSymbol)x1Symbol).Type; Assert.True(x1Type.IsErrorType()); Assert.Equal("var", x1Type.Name); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Symbol = model.GetDeclaredSymbol(x2); var x2Ref = GetReference(tree, "x2"); Assert.Equal("var Script.x2", x2Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x2, x2Ref); var x2Type = ((IFieldSymbol)x2Symbol).Type; Assert.True(x2Type.IsErrorType()); Assert.Equal("var", x2Type.Name); } [Fact] public void VarAliasInVarDeconstructionInScript() { var source = @" using var = System.Byte; var (x1, (x2, x3)) = (1, (2, 3)); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (3,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // var (x1, (x2, x3)) = (1, (2, 3)); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x1, (x2, x3))").WithLocation(3, 5) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.Byte Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Symbol = model.GetDeclaredSymbol(x3); var x3Ref = GetReference(tree, "x3"); Assert.Equal("System.Byte Script.x3", x3Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x3, x3Ref); // extra check on var var x123Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x123Var.Type.ToString()); Assert.Null(model.GetTypeInfo(x123Var.Type).Type); Assert.Null(model.GetSymbolInfo(x123Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol } [Fact] public void VarTypeInVarDeconstructionInScript() { var source = @" class var { public static implicit operator var(int i) { return null; } } var (x1, (x2, x3)) = (1, (2, 3)); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics( // (6,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'. // var (x1, (x2, x3)) = (1, (2, 3)); Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x1, (x2, x3))").WithLocation(6, 5) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("Script.var Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Symbol = model.GetDeclaredSymbol(x3); var x3Ref = GetReference(tree, "x3"); Assert.Equal("Script.var Script.x3", x3Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x3, x3Ref); // extra check on var var x123Var = (DeclarationExpressionSyntax)x1.Parent.Parent; Assert.Equal("var", x123Var.Type.ToString()); Assert.Null(model.GetTypeInfo(x123Var.Type).Type); Assert.Null(model.GetSymbolInfo(x123Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol } [Fact] public void VarAliasInTypedDeconstructionInScript() { var source = @" using var = System.Byte; (var x1, (var x2, var x3)) = (1, (2, 3)); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1 2 3"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.Byte Script.x1", x1Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x1, x1Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Symbol = model.GetDeclaredSymbol(x3); var x3Ref = GetReference(tree, "x3"); Assert.Equal("System.Byte Script.x3", x3Symbol.ToTestDisplayString()); VerifyModelForDeconstructionField(model, x3, x3Ref); // extra checks on x1's var var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("byte", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); var x1Alias = model.GetAliasInfo(x1Type); Assert.Equal(SymbolKind.NamedType, x1Alias.Target.Kind); Assert.Equal("byte", x1Alias.Target.ToDisplayString()); // extra checks on x3's var var x3Type = GetTypeSyntax(x3); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x3Type).Symbol.Kind); Assert.Equal("byte", model.GetSymbolInfo(x3Type).Symbol.ToDisplayString()); var x3Alias = model.GetAliasInfo(x3Type); Assert.Equal(SymbolKind.NamedType, x3Alias.Target.Kind); Assert.Equal("byte", x3Alias.Target.ToDisplayString()); } [Fact] public void VarTypeInTypedDeconstructionInScript() { var source = @" class var { public static implicit operator var(int i) { return new var(); } public override string ToString() { return ""var""; } } (var x1, (var x2, var x3)) = (1, (2, 3)); System.Console.Write($""{x1} {x2} {x3}""); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "var var var"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Symbol = model.GetDeclaredSymbol(x1); var x1Ref = GetReference(tree, "x1"); Assert.Equal("Script.var Script.x1", x1Symbol.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x1).Symbol); VerifyModelForDeconstructionField(model, x1, x1Ref); var x3 = GetDeconstructionVariable(tree, "x3"); var x3Symbol = model.GetDeclaredSymbol(x3); var x3Ref = GetReference(tree, "x3"); Assert.Equal("Script.var Script.x3", x3Symbol.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(x3).Symbol); VerifyModelForDeconstructionField(model, x3, x3Ref); // extra checks on x1's var var x1Type = GetTypeSyntax(x1); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind); Assert.Equal("var", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x1Type)); // extra checks on x3's var var x3Type = GetTypeSyntax(x3); Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x3Type).Symbol.Kind); Assert.Equal("var", model.GetSymbolInfo(x3Type).Symbol.ToDisplayString()); Assert.Null(model.GetAliasInfo(x3Type)); } [Fact] public void SimpleDiscardWithConversion() { var source = @" class C { static void Main() { (int _, var x) = (new C(1), 1); (var _, var y) = (new C(2), 2); var (_, z) = (new C(3), 3); System.Console.Write($""Output {x} {y} {z}.""); } int _i; public C(int i) { _i = i; } public static implicit operator int(C c) { System.Console.Write($""Converted {c._i}. ""); return 0; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Converted 1. Output 1 2 3."); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("int _", declaration1.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); var discard2 = GetDiscardDesignations(tree).ElementAt(1); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Null(model.GetSymbolInfo(discard2).Symbol); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("var _", declaration2.ToString()); Assert.Equal("C", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); var discard3 = GetDiscardDesignations(tree).ElementAt(2); var declaration3 = (DeclarationExpressionSyntax)discard3.Parent.Parent; Assert.Equal("var (_, z)", declaration3.ToString()); Assert.Equal("(C, System.Int32 z)", model.GetTypeInfo(declaration3).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration3).Symbol); } [Fact] public void CannotDeconstructIntoDiscardOfWrongType() { var source = @" class C { static void Main() { (int _, string _) = (""hello"", 42); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,30): error CS0029: Cannot implicitly convert type 'string' to 'int' // (int _, string _) = ("hello", 42); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""hello""").WithArguments("string", "int").WithLocation(6, 30), // (6,39): error CS0029: Cannot implicitly convert type 'int' to 'string' // (int _, string _) = ("hello", 42); Diagnostic(ErrorCode.ERR_NoImplicitConv, "42").WithArguments("int", "string").WithLocation(6, 39) ); } [Fact] public void DiscardFromDeconstructMethod() { var source = @" class C { static void Main() { (var _, string y) = new C(); System.Console.Write(y); } void Deconstruct(out int x, out string y) { x = 42; y = ""hello""; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "hello"); } [Fact] public void ShortDiscardInDeclaration() { var source = @" class C { static void Main() { (_, var x) = (1, 2); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard = GetDiscardIdentifiers(tree).First(); var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol; Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal("System.Int32", model.GetTypeInfo(discard).Type.ToTestDisplayString()); var isymbol = (ISymbol)symbol; Assert.Equal(SymbolKind.Discard, isymbol.Kind); } [Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")] public void SameTypeDiscardsAreEqual01() { var source = @" class C { static void Main() { (_, _) = (1, 2); _ = 3; M(out _); } static void M(out int x) => x = 1; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discards = GetDiscardIdentifiers(tree).ToArray(); Assert.Equal(4, discards.Length); var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol; Assert.Equal(symbol0, symbol0); var set = new HashSet<ISymbol>(); foreach (var discard in discards) { var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol; set.Add(symbol); Assert.Equal(SymbolKind.Discard, symbol.Kind); Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal(symbol0, symbol); Assert.Equal(symbol, symbol); Assert.Equal(symbol.GetHashCode(), symbol0.GetHashCode()); // Test to show that reference-unequal discards are equal by type. IDiscardSymbol symbolClone = new DiscardSymbol(TypeWithAnnotations.Create(symbol.Type.GetSymbol())).GetPublicSymbol(); Assert.NotSame(symbol, symbolClone); Assert.Equal(SymbolKind.Discard, symbolClone.Kind); Assert.Equal("int _", symbolClone.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal(symbol.Type, symbolClone.Type); Assert.Equal(symbol0, symbolClone); Assert.Equal(symbol, symbolClone); Assert.Same(symbol.Type, symbolClone.Type); // original symbol for System.Int32 has identity. Assert.Equal(symbol.GetHashCode(), symbolClone.GetHashCode()); } Assert.Equal(1, set.Count); } [Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")] public void SameTypeDiscardsAreEqual02() { var source = @"using System.Collections.Generic; class C { static void Main() { (_, _) = (new List<int>(), new List<int>()); _ = new List<int>(); M(out _); } static void M(out List<int> x) => x = new List<int>(); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discards = GetDiscardIdentifiers(tree).ToArray(); Assert.Equal(4, discards.Length); var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol; Assert.Equal(symbol0, symbol0); var set = new HashSet<ISymbol>(); foreach (var discard in discards) { var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol; set.Add(symbol); Assert.Equal(SymbolKind.Discard, symbol.Kind); Assert.Equal("List<int> _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal(symbol0, symbol); Assert.Equal(symbol0.Type, symbol.Type); Assert.Equal(symbol, symbol); Assert.Equal(symbol.GetHashCode(), symbol0.GetHashCode()); if (discard != discards[0]) { // Although it is not part of the compiler's contract, at the moment distinct constructions are distinct Assert.NotSame(symbol.Type, symbol0.Type); Assert.NotSame(symbol, symbol0); } } Assert.Equal(1, set.Count); } [Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")] public void DifferentTypeDiscardsAreNotEqual() { var source = @" class C { static void Main() { (_, _) = (1.0, 2); _ = 3; M(out _); } static void M(out int x) => x = 1; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discards = GetDiscardIdentifiers(tree).ToArray(); Assert.Equal(4, discards.Length); var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol; var set = new HashSet<ISymbol>(); foreach (var discard in discards) { var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol; Assert.Equal(SymbolKind.Discard, symbol.Kind); set.Add(symbol); if (discard == discards[0]) { Assert.Equal("double _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal(symbol0, symbol); Assert.Equal(symbol0.GetHashCode(), symbol.GetHashCode()); } else { Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.NotEqual(symbol0, symbol); } } Assert.Equal(2, set.Count); } [Fact] public void EscapedUnderscoreInDeclaration() { var source = @" class C { static void Main() { (@_, var x) = (1, 2); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,10): error CS0103: The name '_' does not exist in the current context // (@_, var x) = (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "@_").WithArguments("_").WithLocation(6, 10) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); Assert.Empty(GetDiscardIdentifiers(tree)); } [Fact] public void EscapedUnderscoreInDeclarationCSharp9() { var source = @" class C { static void Main() { (@_, var x) = (1, 2); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (@_, var x) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(@_, var x) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(6, 9), // (6,10): error CS0103: The name '_' does not exist in the current context // (@_, var x) = (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "@_").WithArguments("_").WithLocation(6, 10) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); Assert.Empty(GetDiscardIdentifiers(tree)); } [Fact] public void UnderscoreLocalInDeconstructDeclaration() { var source = @" class C { static void Main() { int _; (_, var x) = (1, 2); System.Console.Write(_); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1") .VerifyIL("C.Main", @" { // Code size 13 (0xd) .maxstack 1 .locals init (int V_0, //_ int V_1) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: call ""void System.Console.Write(int)"" IL_000b: nop IL_000c: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard = GetDiscardIdentifiers(tree).First(); Assert.Equal("(_, var x)", discard.Parent.Parent.ToString()); var symbol = (ILocalSymbol)model.GetSymbolInfo(discard).Symbol; Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal("System.Int32", model.GetTypeInfo(discard).Type.ToTestDisplayString()); } [Fact] public void ShortDiscardInDeconstructAssignment() { var source = @" class C { static void Main() { int x; (_, _, x) = (1, 2, 3); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void DiscardInDeconstructAssignment() { var source = @" class C { static void Main() { int x; (_, x) = (1L, 2); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardIdentifiers(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Equal("long _", model.GetSymbolInfo(discard1).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); var tuple1 = (TupleExpressionSyntax)discard1.Parent.Parent; Assert.Equal("(_, x)", tuple1.ToString()); Assert.Equal("(System.Int64, System.Int32 x)", model.GetTypeInfo(tuple1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(tuple1).Symbol); } [Fact] public void DiscardInDeconstructDeclaration() { var source = @" class C { static void Main() { var (_, x) = (1, 2); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); var tuple1 = (DeclarationExpressionSyntax)discard1.Parent.Parent; Assert.Equal("var (_, x)", tuple1.ToString()); Assert.Equal("(System.Int32, System.Int32 x)", model.GetTypeInfo(tuple1).Type.ToTestDisplayString()); } [Fact] public void UnderscoreLocalInDeconstructAssignment() { var source = @" class C { static void Main() { int x, _; (_, x) = (1, 2); System.Console.Write($""{_} {x}""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1 2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard = GetDiscardIdentifiers(tree).First(); Assert.Equal("(_, x)", discard.Parent.Parent.ToString()); var symbol = (ILocalSymbol)model.GetSymbolInfo(discard).Symbol; Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } [Fact] public void DiscardInForeach() { var source = @" class C { static void Main() { foreach (var (_, x) in new[] { (1, ""hello"") }) { System.Console.Write(""1 ""); } foreach ((_, (var y, int z)) in new[] { (1, (""hello"", 2)) }) { System.Console.Write(""2""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1 2"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); DiscardDesignationSyntax discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetTypeInfo(discard1).Type); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent.Parent; Assert.Equal("var (_, x)", declaration1.ToString()); Assert.Null(model.GetTypeInfo(discard1).Type); Assert.Equal("(System.Int32, System.String x)", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); IdentifierNameSyntax discard2 = GetDiscardIdentifiers(tree).First(); Assert.Equal("(_, (var y, int z))", discard2.Parent.Parent.ToString()); Assert.Equal("int _", model.GetSymbolInfo(discard2).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Equal("System.Int32", model.GetTypeInfo(discard2).Type.ToTestDisplayString()); var yz = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(2); Assert.Equal("(var y, int z)", yz.ToString()); Assert.Equal("(System.String y, System.Int32 z)", model.GetTypeInfo(yz).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(yz).Symbol); var y = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1); Assert.Equal("var y", y.ToString()); Assert.Equal("System.String", model.GetTypeInfo(y).Type.ToTestDisplayString()); Assert.Equal("System.String y", model.GetSymbolInfo(y).Symbol.ToTestDisplayString()); } [Fact] public void TwoDiscardsInForeach() { var source = @" class C { static void Main() { foreach ((_, _) in new[] { (1, ""hello"") }) { System.Console.Write(""2""); } } } "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var refs = GetReferences(tree, "_"); Assert.Equal(2, refs.Count()); model.GetTypeInfo(refs.ElementAt(0)); // Assert.Equal("int", model.GetTypeInfo(refs.ElementAt(0)).Type.ToDisplayString()); model.GetTypeInfo(refs.ElementAt(1)); // Assert.Equal("string", model.GetTypeInfo(refs.ElementAt(1)).Type.ToDisplayString()); var tuple = (TupleExpressionSyntax)refs.ElementAt(0).Parent.Parent; Assert.Equal("(_, _)", tuple.ToString()); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(tuple).Type.ToTestDisplayString()); }; var comp = CompileAndVerify(source, expectedOutput: @"2", sourceSymbolValidator: validator); comp.VerifyDiagnostics( // this is permitted now, as it is just an assignment expression ); } [Fact] public void UnderscoreLocalDisallowedInForEach() { var source = @" class C { static void Main() { { foreach ((var x, _) in new[] { (1, ""hello"") }) { System.Console.Write(""2 ""); } } { int _; foreach ((var y, _) in new[] { (1, ""hello"") }) { System.Console.Write(""4""); } // error } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (11,30): error CS0029: Cannot implicitly convert type 'string' to 'int' // foreach ((var y, _) in new[] { (1, "hello") }) { System.Console.Write("4"); } // error Diagnostic(ErrorCode.ERR_NoImplicitConv, "_").WithArguments("string", "int").WithLocation(11, 30), // (11,22): error CS8186: A foreach loop must declare its iteration variables. // foreach ((var y, _) in new[] { (1, "hello") }) { System.Console.Write("4"); } // error Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(var y, _)").WithLocation(11, 22), // (10,17): warning CS0168: The variable '_' is declared but never used // int _; Diagnostic(ErrorCode.WRN_UnreferencedVar, "_").WithArguments("_").WithLocation(10, 17) ); } [Fact] public void TwoDiscardsInDeconstructAssignment() { var source = @" class C { static void Main() { (_, _) = (new C(), new C()); } public C() { System.Console.Write(""C""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "CC"); } [Fact] public void VerifyDiscardIL() { var source = @" class C { C() { System.Console.Write(""ctor""); } static int Main() { var (x, _, _) = (1, new C(), 2); return x; } } "; var comp = CompileAndVerify(source, expectedOutput: "ctor"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main()", @" { // Code size 8 (0x8) .maxstack 1 IL_0000: newobj ""C..ctor()"" IL_0005: pop IL_0006: ldc.i4.1 IL_0007: ret }"); } [Fact] public void SingleDiscardInAssignment() { var source = @" class C { static void Main() { _ = M(); } public static int M() { System.Console.Write(""M""); return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "M"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardIdentifiers(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Equal("System.Int32", model.GetTypeInfo(discard1).Type.ToTestDisplayString()); } [Fact] public void SingleDiscardInAssignmentInCSharp6() { var source = @" class C { static void Error() { _ = 1; } static void Ok() { int _; _ = 1; System.Console.Write(_); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (6,9): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater. // _ = 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(6, 9) ); } [Fact] public void VariousDiscardsInCSharp6() { var source = @" class C { static void M1(out int x) { (_, var _, int _) = (1, 2, 3); var (_, _) = (1, 2); bool b = 3 is int _; switch (3) { case int _: break; } M1(out var _); M1(out int _); M1(out _); x = 2; } static void M2() { const int _ = 3; switch (3) { case _: // not a discard break; } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (6,9): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // (_, var _, int _) = (1, 2, 3); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(_, var _, int _)").WithArguments("tuples", "7.0").WithLocation(6, 9), // (6,10): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater. // (_, var _, int _) = (1, 2, 3); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(6, 10), // (6,29): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // (_, var _, int _) = (1, 2, 3); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2, 3)").WithArguments("tuples", "7.0").WithLocation(6, 29), // (7,13): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // var (_, _) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(_, _)").WithArguments("tuples", "7.0").WithLocation(7, 13), // (7,22): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // var (_, _) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2)").WithArguments("tuples", "7.0").WithLocation(7, 22), // (8,18): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // bool b = 3 is int _; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "3 is int _").WithArguments("pattern matching", "7.0").WithLocation(8, 18), // (11,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case int _: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case int _:").WithArguments("pattern matching", "7.0").WithLocation(11, 13), // (14,20): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // M1(out var _); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("out variable declaration", "7.0").WithLocation(14, 20), // (15,20): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // M1(out int _); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("out variable declaration", "7.0").WithLocation(15, 20), // (16,16): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater. // M1(out _); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(16, 16), // (24,18): warning CS8512: The name '_' refers to the constant, not the discard pattern. Use 'var _' to discard the value, or '@_' to refer to a constant by that name. // case _: // not a discard Diagnostic(ErrorCode.WRN_CaseConstantNamedUnderscore, "_").WithLocation(24, 18) ); } [Fact] public void SingleDiscardInAsyncAssignment() { var source = @" class C { async void M() { System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); // warning _ = System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); // fire-and-forget await System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); } } "; var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (6,9): warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call. // System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); Diagnostic(ErrorCode.WRN_UnobservedAwaitableExpression, "System.Threading.Tasks.Task.Delay(new System.TimeSpan(0))").WithLocation(6, 9) ); } [Fact] public void SingleDiscardInUntypedAssignment() { var source = @" class C { static void Main() { _ = null; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,9): error CS8183: Cannot infer the type of implicitly-typed discard. // _ = null; Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(6, 9) ); } [Fact] public void UnderscoreLocalInAssignment() { var source = @" class C { static void Main() { int _; _ = M(); System.Console.Write(_); } public static int M() { return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1"); } [Fact] public void DeclareAndUseLocalInDeconstruction() { var source = @" class C { static void Main() { (var x, x) = (1, 2); (y, var y) = (1, 2); } } "; var compCSharp9 = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compCSharp9.VerifyDiagnostics( // (6,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (var x, x) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(var x, x) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(6, 9), // (6,17): error CS0841: Cannot use local variable 'x' before it is declared // (var x, x) = (1, 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 17), // (7,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (y, var y) = (1, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(y, var y) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(7, 9), // (7,10): error CS0841: Cannot use local variable 'y' before it is declared // (y, var y) = (1, 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(7, 10) ); var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (6,17): error CS0841: Cannot use local variable 'x' before it is declared // (var x, x) = (1, 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 17), // (7,10): error CS0841: Cannot use local variable 'y' before it is declared // (y, var y) = (1, 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(7, 10) ); } [Fact] public void OutVarAndUsageInDeconstructAssignment() { var source = @" class C { static void Main() { (M(out var x).P, x) = (1, x); System.Console.Write(x); } static C M(out int i) { i = 42; return new C(); } int P { set { System.Console.Write($""Written {value}. ""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,26): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (M(out var x).P, x) = (1, x); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(6, 26) ); CompileAndVerify(comp, expectedOutput: "Written 1. 42"); } [Fact] public void OutDiscardInDeconstructAssignment() { var source = @" class C { static void Main() { int _; (M(out var _).P, _) = (1, 2); System.Console.Write(_); } static C M(out int i) { i = 42; return new C(); } int P { set { System.Console.Write($""Written {value}. ""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Written 1. 2"); } [Fact] public void OutDiscardInDeconstructTarget() { var source = @" class C { static void Main() { (x, _) = (M(out var x), 2); System.Console.Write(x); } static int M(out int i) { i = 42; return 3; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,10): error CS0841: Cannot use local variable 'x' before it is declared // (x, _) = (M(out var x), 2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 10) ); } [Fact] public void SimpleDiscardDeconstructInScript() { var source = @" using alias = System.Int32; (string _, alias _) = (""hello"", 42); "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("string _", declaration1.ToString()); Assert.Null(model.GetDeclaredSymbol(declaration1)); Assert.Null(model.GetDeclaredSymbol(discard1)); var discard2 = GetDiscardDesignations(tree).ElementAt(1); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("alias _", declaration2.ToString()); Assert.Null(model.GetDeclaredSymbol(declaration2)); Assert.Null(model.GetDeclaredSymbol(discard2)); var tuple = (TupleExpressionSyntax)declaration1.Parent.Parent; Assert.Equal("(string _, alias _)", tuple.ToString()); Assert.Equal("(System.String, System.Int32)", model.GetTypeInfo(tuple).Type.ToTestDisplayString()); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, sourceSymbolValidator: validator); } [Fact] public void SimpleDiscardDeconstructInScript2() { var source = @" public class C { public C() { System.Console.Write(""ctor""); } public void Deconstruct(out string x, out string y) { x = y = null; } } (string _, string _) = new C(); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "ctor"); } [Fact] public void SingleDiscardInAssignmentInScript() { var source = @" int M() { System.Console.Write(""M""); return 1; } _ = M(); "; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "M"); } [Fact] public void NestedVarDiscardDeconstructionInScript() { var source = @" (var _, var (_, x3)) = (""hello"", (42, 43)); System.Console.Write($""{x3}""); "; Action<ModuleSymbol> validator = (ModuleSymbol module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var discard2 = GetDiscardDesignations(tree).ElementAt(1); var nestedDeclaration = (DeclarationExpressionSyntax)discard2.Parent.Parent; Assert.Equal("var (_, x3)", nestedDeclaration.ToString()); Assert.Null(model.GetDeclaredSymbol(nestedDeclaration)); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Equal("(System.Int32, System.Int32 x3)", model.GetTypeInfo(nestedDeclaration).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(nestedDeclaration).Symbol); var tuple = (TupleExpressionSyntax)discard2.Parent.Parent.Parent.Parent; Assert.Equal("(var _, var (_, x3))", tuple.ToString()); Assert.Equal("(System.String, (System.Int32, System.Int32 x3))", model.GetTypeInfo(tuple).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(tuple).Symbol); }; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "43", sourceSymbolValidator: validator); } [Fact] public void VariousDiscardsInForeach() { var source = @" class C { static void Main() { foreach ((var _, int _, _, var (_, _), int x) in new[] { (1L, 2, 3, (""hello"", 5), 6) }) { System.Console.Write(x); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "6"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.True(model.GetSymbolInfo(discard1).IsEmpty); Assert.Null(model.GetTypeInfo(discard1).Type); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("var _", declaration1.ToString()); Assert.Equal("System.Int64", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); var discard2 = GetDiscardDesignations(tree).ElementAt(1); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.True(model.GetSymbolInfo(discard2).IsEmpty); Assert.Null(model.GetTypeInfo(discard2).Type); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("int _", declaration2.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); var discard3 = GetDiscardIdentifiers(tree).First(); Assert.Equal("_", discard3.Parent.ToString()); Assert.Null(model.GetDeclaredSymbol(discard3)); Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString()); Assert.Equal("int _", model.GetSymbolInfo(discard3).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol; Assert.Equal("System.Int32", discard3Symbol.Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString()); var discard4 = GetDiscardDesignations(tree).ElementAt(2); Assert.Null(model.GetDeclaredSymbol(discard4)); Assert.True(model.GetSymbolInfo(discard4).IsEmpty); Assert.Null(model.GetTypeInfo(discard4).Type); var nestedDeclaration = (DeclarationExpressionSyntax)discard4.Parent.Parent; Assert.Equal("var (_, _)", nestedDeclaration.ToString()); Assert.Equal("(System.String, System.Int32)", model.GetTypeInfo(nestedDeclaration).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(nestedDeclaration).Symbol); } [Fact] public void UnderscoreInCSharp6Foreach() { var source = @" class C { static void Main() { foreach (var _ in M()) { System.Console.Write(_); } } static System.Collections.Generic.IEnumerable<int> M() { System.Console.Write(""M ""); yield return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "M 1"); } [Fact] public void ShortDiscardDisallowedInForeach() { var source = @" class C { static void Main() { foreach (_ in M()) { } } static System.Collections.Generic.IEnumerable<int> M() { yield return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,18): error CS8186: A foreach loop must declare its iteration variables. // foreach (_ in M()) Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "_").WithLocation(6, 18) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var discard = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().First(); var symbol = (DiscardSymbol)model.GetSymbolInfo(discard).Symbol.GetSymbol(); Assert.True(symbol.TypeWithAnnotations.Type.IsErrorType()); } [Fact] public void ExistingUnderscoreLocalInLegacyForeach() { var source = @" class C { static void Main() { int _; foreach (var _ in new[] { 1 }) { } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,22): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var _ in new[] { 1 }) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "_").WithArguments("_").WithLocation(7, 22), // (6,13): warning CS0168: The variable '_' is declared but never used // int _; Diagnostic(ErrorCode.WRN_UnreferencedVar, "_").WithArguments("_").WithLocation(6, 13) ); } [Fact] public void MixedDeconstruction_01() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); var x = (int x1, int x2) = t; System.Console.WriteLine(x1); System.Console.WriteLine(x2); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (7,18): error CS8185: A declaration is not allowed in this context. // var x = (int x1, int x2) = t; Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(7, 18) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2, x2Ref); } [Fact] public void MixedDeconstruction_02() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); int z; (int x1, z) = t; System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "1") .VerifyIL("Program.Main", @" { // Code size 32 (0x20) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0, //t int V_1, //z int V_2) //x1 IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: ldloc.0 IL_000b: dup IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0011: stloc.2 IL_0012: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0017: stloc.1 IL_0018: ldloc.2 IL_0019: call ""void System.Console.WriteLine(int)"" IL_001e: nop IL_001f: ret }"); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); } [Fact] public void MixedDeconstruction_03() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); int z; for ((int x1, z) = t; ; ) { System.Console.WriteLine(x1); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "1") .VerifyIL("Program.Main", @" { // Code size 39 (0x27) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0, //t int V_1, //z int V_2) //x1 IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: ldloc.0 IL_000b: dup IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0011: stloc.2 IL_0012: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0017: stloc.1 IL_0018: br.s IL_0024 IL_001a: nop IL_001b: ldloc.2 IL_001c: call ""void System.Console.WriteLine(int)"" IL_0021: nop IL_0022: br.s IL_0026 IL_0024: br.s IL_001a IL_0026: ret }"); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); var symbolInfo = model.GetSymbolInfo(x1Ref); Assert.Equal(symbolInfo.Symbol, model.GetDeclaredSymbol(x1)); Assert.Equal(SpecialType.System_Int32, symbolInfo.Symbol.GetTypeOrReturnType().SpecialType); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(int x1, z)", lhs.ToString()); Assert.Equal("(System.Int32 x1, System.Int32 z)", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x1, System.Int32 z)", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); } [Fact] public void MixedDeconstruction_03CSharp9() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); int z; for ((int x1, z) = t; ; ) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (8,14): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // for ((int x1, z) = t; ; ) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x1, z) = t").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(8, 14)); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1, x1Ref); } [Fact] public void MixedDeconstruction_04() { string source = @" class Program { static void Main(string[] args) { var t = (1, 2); for (; ; (int x1, int x2) = t) { System.Console.WriteLine(x1); System.Console.WriteLine(x2); } } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8185: A declaration is not allowed in this context. // for (; ; (int x1, int x2) = t) Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(7, 19), // (9,38): error CS0103: The name 'x1' does not exist in the current context // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(9, 38), // (10,38): error CS0103: The name 'x2' does not exist in the current context // System.Console.WriteLine(x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(10, 38) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeconstructionLocal(model, x1); var symbolInfo = model.GetSymbolInfo(x1Ref); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeconstructionLocal(model, x2); symbolInfo = model.GetSymbolInfo(x2Ref); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); } [Fact] public void MixedDeconstruction_05() { string source = @" class Program { static void Main(string[] args) { foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) }) { System.Console.WriteLine(x1); System.Console.WriteLine(x2); } } static int _M; static ref int M(out int x) { x = 2; return ref _M; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,34): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) }) Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "args is var x2").WithLocation(6, 34), // (6,34): error CS0029: Cannot implicitly convert type 'int' to 'bool' // foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) }) Diagnostic(ErrorCode.ERR_NoImplicitConv, "args is var x2").WithArguments("int", "bool").WithLocation(6, 34), // (6,18): error CS8186: A foreach loop must declare its iteration variables. // foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) }) Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(M(out var x1), args is var x2, _)").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString()); model = compilation.GetSemanticModel(tree); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); Assert.Equal("string[]", model.GetTypeInfo(x2Ref).Type.ToDisplayString()); VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref); VerifyModelForLocal(model, x2, LocalDeclarationKind.PatternVariable, x2Ref); } [Fact] public void ForeachIntoExpression() { string source = @" class Program { static void Main(string[] args) { foreach (M(out var x1) in new[] { 1, 2, 3 }) { System.Console.WriteLine(x1); } } static int _M; static ref int M(out int x) { x = 2; return ref _M; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,32): error CS0230: Type and identifier are both required in a foreach statement // foreach (M(out var x1) in new[] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 32) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString()); VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref); } [Fact] public void MixedDeconstruction_06() { string source = @" class Program { static void Main(string[] args) { foreach (M1(M2(out var x1, args is var x2), x1, x2) in new[] {1, 2, 3}) { System.Console.WriteLine(x1); System.Console.WriteLine(x2); } } static int _M; static ref int M1(int m2, int x, string[] y) { return ref _M; } static int M2(out int x, bool b) => x = 2; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,61): error CS0230: Type and identifier are both required in a foreach statement // foreach (M1(M2(out var x1, args is var x2), x1, x2) in new[] {1, 2, 3}) Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 61) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReferences(tree, "x1"); Assert.Equal("int", model.GetTypeInfo(x1Ref.First()).Type.ToDisplayString()); model = compilation.GetSemanticModel(tree); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReferences(tree, "x2"); Assert.Equal("string[]", model.GetTypeInfo(x2Ref.First()).Type.ToDisplayString()); VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref.ToArray()); VerifyModelForLocal(model, x2, LocalDeclarationKind.PatternVariable, x2Ref.ToArray()); } [Fact] public void MixedDeconstruction_07() { string source = @" class Program { static void Main(string[] args) { var t = (1, ("""", true)); string y; for ((int x, (y, var z)) = t; ; ) { System.Console.Write(x); System.Console.Write(z); break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation, expectedOutput: "1True") .VerifyIL("Program.Main", @" { // Code size 73 (0x49) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<string, bool>> V_0, //t string V_1, //y int V_2, //x bool V_3, //z System.ValueTuple<string, bool> V_4) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldstr """" IL_0009: ldc.i4.1 IL_000a: newobj ""System.ValueTuple<string, bool>..ctor(string, bool)"" IL_000f: call ""System.ValueTuple<int, System.ValueTuple<string, bool>>..ctor(int, System.ValueTuple<string, bool>)"" IL_0014: ldloc.0 IL_0015: dup IL_0016: ldfld ""System.ValueTuple<string, bool> System.ValueTuple<int, System.ValueTuple<string, bool>>.Item2"" IL_001b: stloc.s V_4 IL_001d: ldfld ""int System.ValueTuple<int, System.ValueTuple<string, bool>>.Item1"" IL_0022: stloc.2 IL_0023: ldloc.s V_4 IL_0025: ldfld ""string System.ValueTuple<string, bool>.Item1"" IL_002a: stloc.1 IL_002b: ldloc.s V_4 IL_002d: ldfld ""bool System.ValueTuple<string, bool>.Item2"" IL_0032: stloc.3 IL_0033: br.s IL_0046 IL_0035: nop IL_0036: ldloc.2 IL_0037: call ""void System.Console.Write(int)"" IL_003c: nop IL_003d: ldloc.3 IL_003e: call ""void System.Console.Write(bool)"" IL_0043: nop IL_0044: br.s IL_0048 IL_0046: br.s IL_0035 IL_0048: ret }"); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x = GetDeconstructionVariable(tree, "x"); var xRef = GetReference(tree, "x"); VerifyModelForDeconstructionLocal(model, x, xRef); var xSymbolInfo = model.GetSymbolInfo(xRef); Assert.Equal(xSymbolInfo.Symbol, model.GetDeclaredSymbol(x)); Assert.Equal(SpecialType.System_Int32, xSymbolInfo.Symbol.GetTypeOrReturnType().SpecialType); var z = GetDeconstructionVariable(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForDeconstructionLocal(model, z, zRef); var zSymbolInfo = model.GetSymbolInfo(zRef); Assert.Equal(zSymbolInfo.Symbol, model.GetDeclaredSymbol(z)); Assert.Equal(SpecialType.System_Boolean, zSymbolInfo.Symbol.GetTypeOrReturnType().SpecialType); var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(2); Assert.Equal(@"(int x, (y, var z))", lhs.ToString()); Assert.Equal("(System.Int32 x, (System.String y, System.Boolean z))", model.GetTypeInfo(lhs).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 x, (System.String y, System.Boolean z))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString()); } [Fact] public void IncompleteDeclarationIsSeenAsTupleLiteral() { string source = @" class C { static void Main() { (int x1, string x2); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,10): error CS8185: A declaration is not allowed in this context. // (int x1, string x2); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 10), // (6,18): error CS8185: A declaration is not allowed in this context. // (int x1, string x2); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "string x2").WithLocation(6, 18), // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (int x1, string x2); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x1, string x2)").WithLocation(6, 9), // (6,10): error CS0165: Use of unassigned local variable 'x1' // (int x1, string x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 10), // (6,18): error CS0165: Use of unassigned local variable 'x2' // (int x1, string x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "string x2").WithArguments("x2").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var x1 = GetDeconstructionVariable(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString()); var x2 = GetDeconstructionVariable(tree, "x2"); var x2Ref = GetReference(tree, "x2"); Assert.Equal("string", model.GetTypeInfo(x2Ref).Type.ToDisplayString()); VerifyModelForDeconstruction(model, x1, LocalDeclarationKind.DeclarationExpressionVariable, x1Ref); VerifyModelForDeconstruction(model, x2, LocalDeclarationKind.DeclarationExpressionVariable, x2Ref); } [Fact] [WorkItem(15893, "https://github.com/dotnet/roslyn/issues/15893")] public void DeconstructionOfOnlyOneElement() { string source = @" class C { static void Main() { var (p2) = (1, 2); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,16): error CS1003: Syntax error, ',' expected // var (p2) = (1, 2); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(",", ")").WithLocation(6, 16), // (6,16): error CS1001: Identifier expected // var (p2) = (1, 2); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(6, 16) ); } [Fact] [WorkItem(14876, "https://github.com/dotnet/roslyn/issues/14876")] public void TupleTypeInDeconstruction() { string source = @" class C { static void Main() { (int x, (string, long) y) = M(); System.Console.Write($""{x} {y}""); } static (int, (string, long)) M() { return (5, (""Goo"", 34983490)); } } "; var comp = CompileAndVerify(source, expectedOutput: "5 (Goo, 34983490)"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(12468, "https://github.com/dotnet/roslyn/issues/12468")] public void RefReturningVarInvocation() { string source = @" class C { static int i; static void Main() { int x = 0, y = 0; (var(x, y)) = 42; // parsed as invocation System.Console.Write(i); } static ref int var(int a, int b) { return ref i; } } "; var comp = CompileAndVerify(source, expectedOutput: "42", verify: Verification.Passes); comp.VerifyDiagnostics(); } [Fact] void InvokeVarForLvalueInParens() { var source = @" class Program { public static void Main() { (var(x, y)) = 10; System.Console.WriteLine(z); } static int x = 1, y = 2, z = 3; static ref int var(int x, int y) { return ref z; } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); // PEVerify fails with ref return https://github.com/dotnet/roslyn/issues/12285 CompileAndVerify(compilation, expectedOutput: "10", verify: Verification.Fails); } [Fact] [WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")] public void DefAssignmentsStruct001() { string source = @" using System.Collections.Generic; public class MyClass { public static void Main() { ((int, int), string)[] arr = new((int, int), string)[1]; Test5(arr); } public static void Test4(IEnumerable<(KeyValuePair<int, int>, string)> en) { foreach ((KeyValuePair<int, int> kv, string s) in en) { var a = kv.Key; // false error CS0170: Use of possibly unassigned field } } public static void Test5(IEnumerable<((int, int), string)> en) { foreach (((int, int k) t, string s) in en) { var a = t.k; // false error CS0170: Use of possibly unassigned field System.Console.WriteLine(a); } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "0"); } [Fact] [WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")] public void DefAssignmentsStruct002() { string source = @" public class MyClass { public static void Main() { var data = new int[10]; var arr = new int[2]; foreach (arr[out int size] in data) {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,36): error CS0230: Type and identifier are both required in a foreach statement // foreach (arr[out int size] in data) {} Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(9, 36) ); } [Fact] [WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")] public void DefAssignmentsStruct003() { string source = @" public class MyClass { public static void Main() { var data = new (int, int)[10]; var arr = new int[2]; foreach ((arr[out int size], int b) in data) {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,27): error CS1615: Argument 1 may not be passed with the 'out' keyword // foreach ((arr[out int size], int b) in data) {} Diagnostic(ErrorCode.ERR_BadArgExtraRef, "int size").WithArguments("1", "out").WithLocation(9, 27), // (9,18): error CS8186: A foreach loop must declare its iteration variables. // foreach ((arr[out int size], int b) in data) {} Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(arr[out int size], int b)").WithLocation(9, 18) ); } [Fact] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_01() { string source = @" class C { static event System.Action E; static void Main() { (E, _) = (null, 1); System.Console.WriteLine(E == null); (E, _) = (Handler, 1); E(); } static void Handler() { System.Console.WriteLine(""Handler""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"True Handler"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_02() { string source = @" struct S { event System.Action E; class C { static void Main() { var s = new S(); (s.E, _) = (null, 1); System.Console.WriteLine(s.E == null); (s.E, _) = (Handler, 1); s.E(); } static void Handler() { System.Console.WriteLine(""Handler""); } } } "; var comp = CompileAndVerify(source, expectedOutput: @"True Handler"); comp.VerifyDiagnostics(); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.WinRTNeedsWindowsDesktop)] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_03() { string source1 = @" public interface EventInterface { event System.Action E; } "; var comp1 = CreateEmptyCompilation(source1, WinRtRefs, TestOptions.ReleaseWinMD, TestOptions.Regular); string source2 = @" class C : EventInterface { public event System.Action E; static void Main() { var c = new C(); c.Test(); } void Test() { (E, _) = (null, 1); System.Console.WriteLine(E == null); (E, _) = (Handler, 1); E(); } static void Handler() { System.Console.WriteLine(""Handler""); } } "; var comp2 = CompileAndVerify(source2, targetFramework: TargetFramework.Empty, expectedOutput: @"True Handler", references: WinRtRefs.Concat(new[] { ValueTupleRef, comp1.ToMetadataReference() })); comp2.VerifyDiagnostics(); Assert.True(comp2.Compilation.GetMember<IEventSymbol>("C.E").IsWindowsRuntimeEvent); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.WinRTNeedsWindowsDesktop)] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_04() { string source1 = @" public interface EventInterface { event System.Action E; } "; var comp1 = CreateEmptyCompilation(source1, WinRtRefs, TestOptions.ReleaseWinMD, TestOptions.Regular); string source2 = @" struct S : EventInterface { public event System.Action E; class C { S s = new S(); static void Main() { var c = new C(); (GetC(c).s.E, _) = (null, GetInt(1)); System.Console.WriteLine(c.s.E == null); (GetC(c).s.E, _) = (Handler, GetInt(2)); c.s.E(); } static int GetInt(int i) { System.Console.WriteLine(i); return i; } static C GetC(C c) { System.Console.WriteLine(""GetC""); return c; } static void Handler() { System.Console.WriteLine(""Handler""); } } } "; var comp2 = CompileAndVerify(source2, targetFramework: TargetFramework.Empty, expectedOutput: @"GetC 1 True GetC 2 Handler", references: WinRtRefs.Concat(new[] { ValueTupleRef, comp1.ToMetadataReference() })); comp2.VerifyDiagnostics(); Assert.True(comp2.Compilation.GetMember<IEventSymbol>("S.E").IsWindowsRuntimeEvent); } [Fact] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_05() { string source = @" class C { public static event System.Action E; } class Program { static void Main() { (C.E, _) = (null, 1); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,12): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // (C.E, _) = (null, 1); Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(11, 12) ); } [Fact] [WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")] public void Events_06() { string source = @" class C { static event System.Action E { add {} remove {} } static void Main() { (E, _) = (null, 1); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (12,10): error CS0079: The event 'C.E' can only appear on the left hand side of += or -= // (E, _) = (null, 1); Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "E").WithArguments("C.E").WithLocation(12, 10) ); } [Fact] public void SimpleAssignInConstructor() { string source = @" public class C { public long x; public string y; public C(int a, string b) => (x, y) = (a, b); public static void Main() { var c = new C(1, ""hello""); System.Console.WriteLine(c.x + "" "" + c.y); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C..ctor(int, string)", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (long V_0, string V_1) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.1 IL_0007: conv.i8 IL_0008: stloc.0 IL_0009: ldarg.2 IL_000a: stloc.1 IL_000b: ldarg.0 IL_000c: ldloc.0 IL_000d: stfld ""long C.x"" IL_0012: ldarg.0 IL_0013: ldloc.1 IL_0014: stfld ""string C.y"" IL_0019: ret }"); } [Fact] public void DeconstructAssignInConstructor() { string source = @" public class C { public long x; public string y; public C(C oldC) => (x, y) = oldC; public C() { } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } public static void Main() { var oldC = new C() { x = 1, y = ""hello"" }; var newC = new C(oldC); System.Console.WriteLine(newC.x + "" "" + newC.y); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C..ctor(C)", @" { // Code size 34 (0x22) .maxstack 3 .locals init (int V_0, string V_1, long V_2) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.1 IL_0007: ldloca.s V_0 IL_0009: ldloca.s V_1 IL_000b: callvirt ""void C.Deconstruct(out int, out string)"" IL_0010: ldloc.0 IL_0011: conv.i8 IL_0012: stloc.2 IL_0013: ldarg.0 IL_0014: ldloc.2 IL_0015: stfld ""long C.x"" IL_001a: ldarg.0 IL_001b: ldloc.1 IL_001c: stfld ""string C.y"" IL_0021: ret }"); } [Fact] public void AssignInConstructorWithProperties() { string source = @" public class C { public long X { get; set; } public string Y { get; } private int z; public ref int Z { get { return ref z; } } public C(int a, string b, ref int c) => (X, Y, Z) = (a, b, c); public static void Main() { int number = 2; var c = new C(1, ""hello"", ref number); System.Console.WriteLine($""{c.X} {c.Y} {c.Z}""); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 hello 2"); comp.VerifyDiagnostics(); comp.VerifyIL("C..ctor(int, string, ref int)", @" { // Code size 39 (0x27) .maxstack 4 .locals init (long V_0, string V_1, int V_2, long V_3) IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: call ""ref int C.Z.get"" IL_000c: ldarg.1 IL_000d: conv.i8 IL_000e: stloc.0 IL_000f: ldarg.2 IL_0010: stloc.1 IL_0011: ldarg.3 IL_0012: ldind.i4 IL_0013: stloc.2 IL_0014: ldarg.0 IL_0015: ldloc.0 IL_0016: dup IL_0017: stloc.3 IL_0018: call ""void C.X.set"" IL_001d: ldarg.0 IL_001e: ldloc.1 IL_001f: stfld ""string C.<Y>k__BackingField"" IL_0024: ldloc.2 IL_0025: stind.i4 IL_0026: ret }"); } [Fact] public void VerifyDeconstructionInAsync() { var source = @" using System.Threading.Tasks; class C { static void Main() { System.Console.Write(C.M().Result); } static async Task<int> M() { await Task.Delay(0); var (x, y) = (1, 2); return x + y; } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void DeconstructionWarnsForSelfAssignment() { var source = @" class C { object x = 1; static object y = 2; void M() { ((x, x), this.x, C.y) = ((x, (1, 2)), x, y); } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,11): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ((x, x), this.x, C.y) = ((x, (1, 2)), x, y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(8, 11), // (8,18): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ((x, x), this.x, C.y) = ((x, (1, 2)), x, y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "this.x").WithLocation(8, 18), // (8,26): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ((x, x), this.x, C.y) = ((x, (1, 2)), x, y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "C.y").WithLocation(8, 26) ); } [Fact] public void DeconstructionWarnsForSelfAssignment2() { var source = @" class C { object x = 1; static object y = 2; void M() { object z = 3; (x, (y, z)) = (x, (y, z)); } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (9,10): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, (y, z)) = (x, (y, z)); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x"), // (9,14): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, (y, z)) = (x, (y, z)); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "y").WithLocation(9, 14), // (9,17): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, (y, z)) = (x, (y, z)); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "z").WithLocation(9, 17) ); } [Fact] public void DeconstructionWarnsForSelfAssignment_WithUserDefinedConversionOnElement() { var source = @" class C { object x = 1; static C y = null; void M() { (x, y) = (x, (C)(D)y); } public static implicit operator C(D d) => null; } class D { public static implicit operator D(C c) => null; } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,10): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, y) = (x, (C)(D)y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(8, 10) ); } [Fact] public void DeconstructionWarnsForSelfAssignment_WithNestedConversions() { var source = @" class C { object x = 1; int y = 2; byte b = 3; void M() { // The conversions on the right-hand-side: // - a deconstruction conversion // - an implicit tuple literal conversion on the entire right-hand-side // - another implicit tuple literal conversion on the nested tuple // - a conversion on element `b` (_, (x, y)) = (1, (x, b)); } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (14,14): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (_, (x, y)) = (1, (x, b)); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(14, 14) ); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DeconstructionWarnsForSelfAssignment_WithExplicitTupleConversion() { var source = @" class C { int y = 2; byte b = 3; void M() { // The conversions on the right-hand-side: // - a deconstruction conversion on the entire right-hand-side // - an identity conversion as its operand // - an explicit tuple literal conversion as its operand (y, _) = ((int, int))(y, b); } } "; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( ); var tree = comp.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); Assert.Equal("((int, int))(y, b)", node.ToString()); comp.VerifyOperationTree(node, expectedOperationTree: @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(y, b)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32 y, System.Int32 b)) (Syntax: '(y, b)') NaturalType: (System.Int32 y, System.Byte b) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Int32 C.y (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'y') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Byte C.b (OperationKind.FieldReference, Type: System.Byte) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'b') "); } [Fact] public void DeconstructionWarnsForSelfAssignment_WithDeconstruct() { var source = @" class C { object x = 1; static object y = 2; void M() { object z = 3; (x, (y, z)) = (x, y); } } static class Extensions { public static void Deconstruct(this object input, out object output1, out object output2) { output1 = input; output2 = input; } }"; var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (9,10): warning CS1717: Assignment made to same variable; did you mean to assign something else? // (x, (y, z)) = (x, y); Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(9, 10) ); } [Fact] public void TestDeconstructOnErrorType() { var source = @" class C { Error M() { int x, y; (x, y) = M(); throw null; } }"; var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); // no ValueTuple reference comp.VerifyDiagnostics( // (4,5): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // Error M() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 5) ); } [Fact] public void TestDeconstructOnErrorTypeFromImageReference() { var missing_cs = "public class Missing { }"; var missing = CreateCompilationWithMscorlib45(missing_cs, options: TestOptions.DebugDll, assemblyName: "missing"); var lib_cs = "public class C { public Missing M() { throw null; } }"; var lib = CreateCompilationWithMscorlib45(lib_cs, references: new[] { missing.EmitToImageReference() }, options: TestOptions.DebugDll); var source = @" class D { void M() { int x, y; (x, y) = new C().M(); throw null; } }"; var comp = CreateCompilationWithMscorlib45(source, references: new[] { lib.EmitToImageReference() }, options: TestOptions.DebugDll); // no ValueTuple reference comp.VerifyDiagnostics( // (7,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (x, y) = new C().M(); Diagnostic(ErrorCode.ERR_NoTypeDef, "new C().M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18) ); } [Fact] public void TestDeconstructOnErrorTypeFromCompilationReference() { var missing_cs = "public class Missing { }"; var missing = CreateCompilationWithMscorlib45(missing_cs, options: TestOptions.DebugDll, assemblyName: "missing"); var lib_cs = "public class C { public Missing M() { throw null; } }"; var lib = CreateCompilationWithMscorlib45(lib_cs, references: new[] { missing.ToMetadataReference() }, options: TestOptions.DebugDll); var source = @" class D { void M() { int x, y; (x, y) = new C().M(); throw null; } }"; var comp = CreateCompilationWithMscorlib45(source, references: new[] { lib.ToMetadataReference() }, options: TestOptions.DebugDll); // no ValueTuple reference comp.VerifyDiagnostics( // (7,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (x, y) = new C().M(); Diagnostic(ErrorCode.ERR_NoTypeDef, "new C().M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18) ); } [Fact, WorkItem(17756, "https://github.com/dotnet/roslyn/issues/17756")] public void TestDiscardedAssignmentNotLvalue() { var source = @" class Program { struct S1 { public int field; public int Increment() => field++; } static void Main() { S1 v = default(S1); v.Increment(); (_ = v).Increment(); System.Console.WriteLine(v.field); } } "; string expectedOutput = @"1"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void TupleCastInDeconstruction() { var source = @" class C { static void Main() { var t = (1, 2); var (a, b) = ((byte, byte))t; System.Console.Write($""{a} {b}""); } }"; CompileAndVerify(source, expectedOutput: @"1 2"); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void TupleCastInDeconstruction2() { var source = @" class C { static void Main() { var t = (new C(), new D()); var (a, _) = ((byte, byte))t; System.Console.Write($""{a}""); } public static explicit operator byte(C c) { System.Console.Write(""Convert ""); return 1; } } class D { public static explicit operator byte(D c) { System.Console.Write(""Convert2 ""); return 2; } }"; CompileAndVerify(source, expectedOutput: @"Convert Convert2 1"); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void TupleCastInDeconstruction3() { var source = @" class C { static int A { set { System.Console.Write(""A ""); } } static int B { set { System.Console.Write(""B""); } } static void Main() { (A, B) = ((byte, byte))(new C(), new D()); } public static explicit operator byte(C c) { System.Console.Write(""Convert ""); return 1; } public C() { System.Console.Write(""C ""); } } class D { public static explicit operator byte(D c) { System.Console.Write(""Convert2 ""); return 2; } public D() { System.Console.Write(""D ""); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"C Convert D Convert2 A B").Compilation; var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); Assert.Equal("((byte, byte))(new C(), new D())", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Byte, System.Byte)) (Syntax: '((byte, byt ... ), new D())') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Byte, System.Byte)) (Syntax: '(new C(), new D())') NaturalType: (C, D) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Byte C.op_Explicit(C c)) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'new C()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Byte C.op_Explicit(C c)) Operand: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Byte D.op_Explicit(D c)) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'new D()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Byte D.op_Explicit(D c)) Operand: IObjectCreationOperation (Constructor: D..ctor()) (OperationKind.ObjectCreation, Type: D) (Syntax: 'new D()') Arguments(0) Initializer: null "); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void TupleCastInDeconstruction4() { var source = @" class C { static void Main() { var (a, _) = ((short, short))((int, int))(1L, 2L); System.Console.Write($""{a}""); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1").Compilation; var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().ElementAt(1); Assert.Equal("((int, int))(1L, 2L)", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(1L, 2L)') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1L, 2L)') NaturalType: (System.Int64, System.Int64) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 1) (Syntax: '1L') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 2) (Syntax: '2L') "); Assert.Equal("((short, short))((int, int))(1L, 2L)", node.Parent.ToString()); compilation.VerifyOperationTree(node.Parent, expectedOperationTree: @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int16, System.Int16)) (Syntax: '((short, sh ... t))(1L, 2L)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(1L, 2L)') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1L, 2L)') NaturalType: (System.Int64, System.Int64) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 1) (Syntax: '1L') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 2) (Syntax: '2L') "); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void UserDefinedCastInDeconstruction() { var source = @" class C { static void Main() { var c = new C(); var (a, b) = ((byte, byte))c; System.Console.Write($""{a} {b}""); } public static explicit operator (byte, byte)(C c) { return (3, 4); } }"; CompileAndVerify(source, expectedOutput: @"3 4"); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void DeconstructionLoweredToNothing() { var source = @" class C { static void M() { for (var(_, _) = (1, 2); ; (_, _) = (3, 4)) { } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("C.M", @" { // Code size 2 (0x2) .maxstack 0 IL_0000: br.s IL_0000 }"); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void DeconstructionLoweredToNothing2() { var source = @" class C { static void M() { (_, _) = (1, 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("C.M", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")] public void DeconstructionLoweredToNothing3() { var source = @" class C { static void Main() { foreach (var(_, _) in new[] { (1, 2) }) { System.Console.Write(""once""); } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "once"); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName() { var source = @"class C { static void Main() { int x = 0, y = 1; var t = (x, y); var (a, b) = t; } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName_ConditionalOperator() { var source = @"class C { static void M(int a, int b, bool c) { (var x, var y) = c ? (a, default(object)) : (b, null); (x, y) = c ? (a, default(string)) : (b, default(object)); } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName_ImplicitArray() { var source = @"class C { static void M(int x) { int y; object z; (y, z) = (new [] { (x, default(object)), (2, 3) })[0]; } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")] public void InferredName_Lambda() { // See https://github.com/dotnet/roslyn/issues/32006 // need to relax assertion in GetImplicitTupleLiteralConversion var source = @"class C { static T F<T>(System.Func<object, bool, T> f) { return f(null, false); } static void M() { var (x, y) = F((a, b) => { if (b) return (default(object), a); return (null, null); }); } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName_ConditionalOperator_LongTuple() { var source = @"class C { static void M(object a, object b, bool c) { var (_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) = c ? (1, 2, 3, 4, 5, 6, 7, a, b, 10) : (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } }"; // C# 7.0 var comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(); // C# 7.1 comp = CreateCompilation( source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(); } [WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")] [Fact] public void InferredName_ConditionalOperator_UseSite() { var source = @"class C { static void M(int a, int b, bool c) { var (x, y) = c ? ((object)1, a) : (b, 2); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; private T2 Item2; public ValueTuple(T1 item1, T2 item2) => throw null; } }"; var expected = new[] { // (12,19): warning CS0649: Field '(T1, T2).Item1' is never assigned to, and will always have its default value // public T1 Item1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Item1").WithArguments("(T1, T2).Item1", "").WithLocation(12, 19), // (13,20): warning CS0169: The field '(T1, T2).Item2' is never used // private T2 Item2; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item2").WithArguments("(T1, T2).Item2").WithLocation(13, 20) }; // C# 7.0 var comp = CreateCompilation( source, assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(expected); // C# 7.1 comp = CreateCompilation( source, assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(expected); } [Fact] public void InferredName_ConditionalOperator_UseSite_AccessingWithinConstructor() { var source = @"class C { static void M(int a, int b, bool c) { var (x, y) = c ? ((object)1, a) : (b, 2); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; private T2 Item2; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } }"; var expected = new[] { // (13,20): warning CS0169: The field '(T1, T2).Item2' is never used // private T2 Item2; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item2").WithArguments("(T1, T2).Item2").WithLocation(13, 20), // (14,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(14, 16), // (14,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(14, 16), // (17,13): error CS0229: Ambiguity between '(T1, T2).Item2' and '(T1, T2).Item2' // Item2 = item2; Diagnostic(ErrorCode.ERR_AmbigMember, "Item2").WithArguments("(T1, T2).Item2", "(T1, T2).Item2").WithLocation(17, 13) }; // C# 7.0 var comp = CreateCompilation( source, assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp.VerifyEmitDiagnostics(expected); // C# 7.1 comp = CreateCompilation( source, assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); comp.VerifyEmitDiagnostics(expected); } [Fact] public void TestGetDeconstructionInfoOnIncompleteCode() { string source = @" class C { void M() { var (y1, y2) =} void Deconstruct(out int x1, out int x2) { x1 = 1; x2 = 2; } } "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First(); Assert.Equal("var (y1, y2) =", node.ToString()); var info = model.GetDeconstructionInfo(node); Assert.Null(info.Method); Assert.Empty(info.Nested); } [Fact] public void TestDeconstructStructThis() { string source = @" public struct S { int I; public static void Main() { S s = new S(); s.M(); } public void M() { this.I = 42; var (x, (y, z)) = (this, this /* mutating deconstruction */); System.Console.Write($""{x.I} {y} {z}""); } void Deconstruct(out int x1, out int x2) { x1 = I++; x2 = I++; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "42 42 43"); } [Fact] public void TestDeconstructClassThis() { string source = @" public class C { int I; public static void Main() { C c = new C(); c.M(); } public void M() { this.I = 42; var (x, (y, z)) = (this, this /* mutating deconstruction */); System.Console.Write($""{x.I} {y} {z}""); } void Deconstruct(out int x1, out int x2) { x1 = I++; x2 = I++; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "44 42 43"); } [Fact] public void AssigningConditional_OutParams() { string source = @" using System; class C { static void Main() { Test(true, false); Test(false, true); Test(false, false); } static void Test(bool b1, bool b2) { M(out int x, out int y, b1, b2); Console.Write(x); Console.Write(y); } static void M(out int x, out int y, bool b1, bool b2) { (x, y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); } } "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 33 (0x21) .maxstack 2 IL_0000: ldarg.2 IL_0001: brtrue.s IL_0018 IL_0003: ldarg.3 IL_0004: brtrue.s IL_000f IL_0006: ldarg.0 IL_0007: ldc.i4.s 50 IL_0009: stind.i4 IL_000a: ldarg.1 IL_000b: ldc.i4.s 60 IL_000d: stind.i4 IL_000e: ret IL_000f: ldarg.0 IL_0010: ldc.i4.s 30 IL_0012: stind.i4 IL_0013: ldarg.1 IL_0014: ldc.i4.s 40 IL_0016: stind.i4 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.s 10 IL_001b: stind.i4 IL_001c: ldarg.1 IL_001d: ldc.i4.s 20 IL_001f: stind.i4 IL_0020: ret }"); } [Fact] public void AssigningConditional_VarDeconstruction() { string source = @" using System; class C { static void Main() { M(true, false); M(false, true); M(false, false); } static void M(bool b1, bool b2) { var (x, y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); Console.Write(x); Console.Write(y); } } "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 41 (0x29) .maxstack 1 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: brtrue.s IL_0016 IL_0003: ldarg.1 IL_0004: brtrue.s IL_000e IL_0006: ldc.i4.s 50 IL_0008: stloc.0 IL_0009: ldc.i4.s 60 IL_000b: stloc.1 IL_000c: br.s IL_001c IL_000e: ldc.i4.s 30 IL_0010: stloc.0 IL_0011: ldc.i4.s 40 IL_0013: stloc.1 IL_0014: br.s IL_001c IL_0016: ldc.i4.s 10 IL_0018: stloc.0 IL_0019: ldc.i4.s 20 IL_001b: stloc.1 IL_001c: ldloc.0 IL_001d: call ""void System.Console.Write(int)"" IL_0022: ldloc.1 IL_0023: call ""void System.Console.Write(int)"" IL_0028: ret }"); } [Fact] public void AssigningConditional_MixedDeconstruction() { string source = @" using System; class C { static void Main() { M(true, false); M(false, true); M(false, false); } static void M(bool b1, bool b2) { (var x, long y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); Console.Write(x); Console.Write(y); } } "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 50 (0x32) .maxstack 1 .locals init (int V_0, //x long V_1, //y long V_2) IL_0000: ldarg.0 IL_0001: brtrue.s IL_001c IL_0003: ldarg.1 IL_0004: brtrue.s IL_0011 IL_0006: ldc.i4.s 60 IL_0008: conv.i8 IL_0009: stloc.2 IL_000a: ldc.i4.s 50 IL_000c: stloc.0 IL_000d: ldloc.2 IL_000e: stloc.1 IL_000f: br.s IL_0025 IL_0011: ldc.i4.s 40 IL_0013: conv.i8 IL_0014: stloc.2 IL_0015: ldc.i4.s 30 IL_0017: stloc.0 IL_0018: ldloc.2 IL_0019: stloc.1 IL_001a: br.s IL_0025 IL_001c: ldc.i4.s 20 IL_001e: conv.i8 IL_001f: stloc.2 IL_0020: ldc.i4.s 10 IL_0022: stloc.0 IL_0023: ldloc.2 IL_0024: stloc.1 IL_0025: ldloc.0 IL_0026: call ""void System.Console.Write(int)"" IL_002b: ldloc.1 IL_002c: call ""void System.Console.Write(long)"" IL_0031: ret }"); } [Fact] public void AssigningConditional_SideEffects() { string source = @" using System; class C { static void Main() { M(true, false); M(false, true); M(false, false); SideEffect(true); SideEffect(false); } static int left; static int right; static ref int SideEffect(bool isLeft) { Console.WriteLine($""{(isLeft ? ""left"" : ""right"")}: {(isLeft ? left : right)}""); return ref isLeft ? ref left : ref right; } static void M(bool b1, bool b2) { (SideEffect(isLeft: true), SideEffect(isLeft: false)) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); } } "; var expected = @"left: 0 right: 0 left: 10 right: 20 left: 30 right: 40 left: 50 right: 60"; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expected); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (int& V_0, int& V_1) IL_0000: ldc.i4.1 IL_0001: call ""ref int C.SideEffect(bool)"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: call ""ref int C.SideEffect(bool)"" IL_000d: stloc.1 IL_000e: ldarg.0 IL_000f: brtrue.s IL_0026 IL_0011: ldarg.1 IL_0012: brtrue.s IL_001d IL_0014: ldloc.0 IL_0015: ldc.i4.s 50 IL_0017: stind.i4 IL_0018: ldloc.1 IL_0019: ldc.i4.s 60 IL_001b: stind.i4 IL_001c: ret IL_001d: ldloc.0 IL_001e: ldc.i4.s 30 IL_0020: stind.i4 IL_0021: ldloc.1 IL_0022: ldc.i4.s 40 IL_0024: stind.i4 IL_0025: ret IL_0026: ldloc.0 IL_0027: ldc.i4.s 10 IL_0029: stind.i4 IL_002a: ldloc.1 IL_002b: ldc.i4.s 20 IL_002d: stind.i4 IL_002e: ret }"); } [Fact] public void AssigningConditional_SideEffects_RHS() { string source = @" using System; class C { static void Main() { M(true, false); M(false, true); M(false, false); } static T Echo<T>(T v, int i) { Console.WriteLine(i + "": "" + v); return v; } static void M(bool b1, bool b2) { var (x, y) = Echo(b1, 1) ? Echo((10, 20), 2) : Echo(b2, 3) ? Echo((30, 40), 4) : Echo((50, 60), 5); Console.WriteLine(""x: "" + x); Console.WriteLine(""y: "" + y); Console.WriteLine(); } } "; var expectedOutput = @"1: True 2: (10, 20) x: 10 y: 20 1: False 3: True 4: (30, 40) x: 30 y: 40 1: False 3: False 5: (50, 60) x: 50 y: 60 "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); comp.VerifyDiagnostics(); } [Fact] public void AssigningConditional_UnusedDeconstruction() { string source = @" class C { static void M(bool b1, bool b2) { (_, _) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60); } } "; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldarg.1 IL_0004: pop IL_0005: ret }"); } [Fact, WorkItem(46562, "https://github.com/dotnet/roslyn/issues/46562")] public void CompoundAssignment() { string source = @" class C { void M() { decimal x = 0; (var y, _) += 0.00m; (int z, _) += z; (var t, _) += (1, 2); } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,17): warning CS0219: The variable 'x' is assigned but its value is never used // decimal x = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 17), // (7,10): error CS8185: A declaration is not allowed in this context. // (var y, _) += 0.00m; Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var y").WithLocation(7, 10), // (7,17): error CS0103: The name '_' does not exist in the current context // (var y, _) += 0.00m; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(7, 17), // (8,10): error CS8185: A declaration is not allowed in this context. // (int z, _) += z; Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int z").WithLocation(8, 10), // (8,10): error CS0165: Use of unassigned local variable 'z' // (int z, _) += z; Diagnostic(ErrorCode.ERR_UseDefViolation, "int z").WithArguments("z").WithLocation(8, 10), // (8,17): error CS0103: The name '_' does not exist in the current context // (int z, _) += z; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(8, 17), // (9,10): error CS8185: A declaration is not allowed in this context. // (var t, _) += (1, 2); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var t").WithLocation(9, 10), // (9,17): error CS0103: The name '_' does not exist in the current context // (var t, _) += (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(9, 17) ); } [Fact, WorkItem(50654, "https://github.com/dotnet/roslyn/issues/50654")] public void Repro50654() { string source = @" class C { static void Main() { (int, (int, (int, int), (int, int)))[] vals = new[] { (1, (2, (3, 4), (5, 6))), (11, (12, (13, 14), (15, 16))) }; foreach (var (a, (b, (c, d), (e, f))) in vals) { System.Console.Write($""{a + b + c + d + e + f} ""); } foreach ((int a, (int b, (int c, int d), (int e, int f))) in vals) { System.Console.Write($""{a + b + c + d + e + f} ""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "21 81 21 81"); } [Fact] public void MixDeclarationAndAssignmentPermutationsOf2() { string source = @" class C { static void Main() { int x1 = 0; (x1, string y1) = new C(); System.Console.WriteLine(x1 + "" "" + y1); int x2; (x2, var y2) = new C(); System.Console.WriteLine(x2 + "" "" + y2); string y3 = """"; (int x3, y3) = new C(); System.Console.WriteLine(x3 + "" "" + y3); string y4; (var x4, y4) = new C(); System.Console.WriteLine(x4 + "" "" + y4); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello 1 hello 1 hello 1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 188 (0xbc) .maxstack 3 .locals init (int V_0, //x1 string V_1, //y1 int V_2, //x2 string V_3, //y2 string V_4, //y3 int V_5, //x3 string V_6, //y4 int V_7, //x4 int V_8, string V_9) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: newobj ""C..ctor()"" IL_0007: ldloca.s V_8 IL_0009: ldloca.s V_9 IL_000b: callvirt ""void C.Deconstruct(out int, out string)"" IL_0010: ldloc.s V_8 IL_0012: stloc.0 IL_0013: ldloc.s V_9 IL_0015: stloc.1 IL_0016: ldloca.s V_0 IL_0018: call ""string int.ToString()"" IL_001d: ldstr "" "" IL_0022: ldloc.1 IL_0023: call ""string string.Concat(string, string, string)"" IL_0028: call ""void System.Console.WriteLine(string)"" IL_002d: newobj ""C..ctor()"" IL_0032: ldloca.s V_8 IL_0034: ldloca.s V_9 IL_0036: callvirt ""void C.Deconstruct(out int, out string)"" IL_003b: ldloc.s V_8 IL_003d: stloc.2 IL_003e: ldloc.s V_9 IL_0040: stloc.3 IL_0041: ldloca.s V_2 IL_0043: call ""string int.ToString()"" IL_0048: ldstr "" "" IL_004d: ldloc.3 IL_004e: call ""string string.Concat(string, string, string)"" IL_0053: call ""void System.Console.WriteLine(string)"" IL_0058: ldstr """" IL_005d: stloc.s V_4 IL_005f: newobj ""C..ctor()"" IL_0064: ldloca.s V_8 IL_0066: ldloca.s V_9 IL_0068: callvirt ""void C.Deconstruct(out int, out string)"" IL_006d: ldloc.s V_8 IL_006f: stloc.s V_5 IL_0071: ldloc.s V_9 IL_0073: stloc.s V_4 IL_0075: ldloca.s V_5 IL_0077: call ""string int.ToString()"" IL_007c: ldstr "" "" IL_0081: ldloc.s V_4 IL_0083: call ""string string.Concat(string, string, string)"" IL_0088: call ""void System.Console.WriteLine(string)"" IL_008d: newobj ""C..ctor()"" IL_0092: ldloca.s V_8 IL_0094: ldloca.s V_9 IL_0096: callvirt ""void C.Deconstruct(out int, out string)"" IL_009b: ldloc.s V_8 IL_009d: stloc.s V_7 IL_009f: ldloc.s V_9 IL_00a1: stloc.s V_6 IL_00a3: ldloca.s V_7 IL_00a5: call ""string int.ToString()"" IL_00aa: ldstr "" "" IL_00af: ldloc.s V_6 IL_00b1: call ""string string.Concat(string, string, string)"" IL_00b6: call ""void System.Console.WriteLine(string)"" IL_00bb: ret }"); } [Fact] public void MixDeclarationAndAssignmentPermutationsOf3() { string source = @" class C { static void Main() { int x1; string y1; (x1, y1, var z1) = new C(); System.Console.WriteLine(x1 + "" "" + y1 + "" "" + z1); int x2; bool z2; (x2, var y2, z2) = new C(); System.Console.WriteLine(x2 + "" "" + y2 + "" "" + z2); string y3; bool z3; (var x3, y3, z3) = new C(); System.Console.WriteLine(x3 + "" "" + y3 + "" "" + z3); bool z4; (var x4, var y4, z4) = new C(); System.Console.WriteLine(x4 + "" "" + y4 + "" "" + z4); string y5; (var x5, y5, var z5) = new C(); System.Console.WriteLine(x5 + "" "" + y5 + "" "" + z5); int x6; (x6, var y6, var z6) = new C(); System.Console.WriteLine(x6 + "" "" + y6 + "" "" + z6); } public void Deconstruct(out int a, out string b, out bool c) { a = 1; b = ""hello""; c = true; } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello True 1 hello True 1 hello True 1 hello True 1 hello True 1 hello True"); comp.VerifyDiagnostics(); } [Fact] public void DontAllowMixedDeclarationAndAssignmentInExpressionContext() { string source = @" class C { static void Main() { int x1 = 0; var z1 = (x1, string y1) = new C(); string y2 = """"; var z2 = (int x2, y2) = new C(); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,23): error CS8185: A declaration is not allowed in this context. // var z1 = (x1, string y1) = new C(); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "string y1").WithLocation(7, 23), // (9,19): error CS8185: A declaration is not allowed in this context. // var z2 = (int x2, y2) = new C(); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x2").WithLocation(9, 19)); } [Fact] public void DontAllowMixedDeclarationAndAssignmentInForeachDeclarationVariable() { string source = @" class C { static void Main() { int x1; foreach((x1, string y1) in new C[0]); string y2; foreach((int x2, y2) in new C[0]); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(6, 13), // (7,17): error CS8186: A foreach loop must declare its iteration variables. // foreach((x1, string y1) in new C[0]); Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(x1, string y1)").WithLocation(7, 17), // (8,16): warning CS0168: The variable 'y2' is declared but never used // string y2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "y2").WithArguments("y2").WithLocation(8, 16), // (9,17): error CS8186: A foreach loop must declare its iteration variables. // foreach((int x2, y2) in new C[0]); Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(int x2, y2)").WithLocation(9, 17)); } [Fact] public void DuplicateDeclarationOfVariableDeclaredInMixedDeclarationAndAssignment() { string source = @" class C { static void Main() { int x1; string y1; (x1, string y1) = new C(); string y2; (int x2, y2) = new C(); int x2; } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (7,16): warning CS0168: The variable 'y1' is declared but never used // string y1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "y1").WithArguments("y1").WithLocation(7, 16), // (8,21): error CS0128: A local variable or function named 'y1' is already defined in this scope // (x1, string y1) = new C(); Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(8, 21), // (11,13): error CS0128: A local variable or function named 'x2' is already defined in this scope // int x2; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(11, 13), // (11,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(11, 13)); } [Fact] public void AssignmentToUndeclaredVariableInMixedDeclarationAndAssignment() { string source = @" class C { static void Main() { (x1, string y1) = new C(); (int x2, y2) = new C(); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (6,10): error CS0103: The name 'x1' does not exist in the current context // (x1, string y1) = new C(); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 10), // (7,18): error CS0103: The name 'y2' does not exist in the current context // (int x2, y2) = new C(); Diagnostic(ErrorCode.ERR_NameNotInContext, "y2").WithArguments("y2").WithLocation(7, 18)); } [Fact] public void MixedDeclarationAndAssignmentInForInitialization() { string source = @" class C { static void Main() { int x1; for((x1, string y1) = new C(); x1 < 2; x1++) System.Console.WriteLine(x1 + "" "" + y1); string y2; for((int x2, y2) = new C(); x2 < 2; x2++) System.Console.WriteLine(x2 + "" "" + y2); } public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello 1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 109 (0x6d) .maxstack 3 .locals init (int V_0, //x1 string V_1, //y2 string V_2, //y1 int V_3, string V_4, int V_5) //x2 IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_3 IL_0007: ldloca.s V_4 IL_0009: callvirt ""void C.Deconstruct(out int, out string)"" IL_000e: ldloc.3 IL_000f: stloc.0 IL_0010: ldloc.s V_4 IL_0012: stloc.2 IL_0013: br.s IL_0030 IL_0015: ldloca.s V_0 IL_0017: call ""string int.ToString()"" IL_001c: ldstr "" "" IL_0021: ldloc.2 IL_0022: call ""string string.Concat(string, string, string)"" IL_0027: call ""void System.Console.WriteLine(string)"" IL_002c: ldloc.0 IL_002d: ldc.i4.1 IL_002e: add IL_002f: stloc.0 IL_0030: ldloc.0 IL_0031: ldc.i4.2 IL_0032: blt.s IL_0015 IL_0034: newobj ""C..ctor()"" IL_0039: ldloca.s V_3 IL_003b: ldloca.s V_4 IL_003d: callvirt ""void C.Deconstruct(out int, out string)"" IL_0042: ldloc.3 IL_0043: stloc.s V_5 IL_0045: ldloc.s V_4 IL_0047: stloc.1 IL_0048: br.s IL_0067 IL_004a: ldloca.s V_5 IL_004c: call ""string int.ToString()"" IL_0051: ldstr "" "" IL_0056: ldloc.1 IL_0057: call ""string string.Concat(string, string, string)"" IL_005c: call ""void System.Console.WriteLine(string)"" IL_0061: ldloc.s V_5 IL_0063: ldc.i4.1 IL_0064: add IL_0065: stloc.s V_5 IL_0067: ldloc.s V_5 IL_0069: ldc.i4.2 IL_006a: blt.s IL_004a IL_006c: ret }"); } [Fact] public void MixDeclarationAndAssignmentInTupleDeconstructPermutationsOf2() { string source = @" class C { static void Main() { int x1 = 0; (x1, string y1) = (1, ""hello""); System.Console.WriteLine(x1 + "" "" + y1); int x2; (x2, var y2) = (1, ""hello""); System.Console.WriteLine(x2 + "" "" + y2); string y3 = """"; (int x3, y3) = (1, ""hello""); System.Console.WriteLine(x3 + "" "" + y3); string y4; (var x4, y4) = (1, ""hello""); System.Console.WriteLine(x4 + "" "" + y4); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello 1 hello 1 hello 1 hello"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 140 (0x8c) .maxstack 3 .locals init (int V_0, //x1 string V_1, //y1 int V_2, //x2 string V_3, //y2 string V_4, //y3 int V_5, //x3 string V_6, //y4 int V_7) //x4 IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldc.i4.1 IL_0003: stloc.0 IL_0004: ldstr ""hello"" IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""string int.ToString()"" IL_0011: ldstr "" "" IL_0016: ldloc.1 IL_0017: call ""string string.Concat(string, string, string)"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ldc.i4.1 IL_0022: stloc.2 IL_0023: ldstr ""hello"" IL_0028: stloc.3 IL_0029: ldloca.s V_2 IL_002b: call ""string int.ToString()"" IL_0030: ldstr "" "" IL_0035: ldloc.3 IL_0036: call ""string string.Concat(string, string, string)"" IL_003b: call ""void System.Console.WriteLine(string)"" IL_0040: ldstr """" IL_0045: stloc.s V_4 IL_0047: ldc.i4.1 IL_0048: stloc.s V_5 IL_004a: ldstr ""hello"" IL_004f: stloc.s V_4 IL_0051: ldloca.s V_5 IL_0053: call ""string int.ToString()"" IL_0058: ldstr "" "" IL_005d: ldloc.s V_4 IL_005f: call ""string string.Concat(string, string, string)"" IL_0064: call ""void System.Console.WriteLine(string)"" IL_0069: ldc.i4.1 IL_006a: stloc.s V_7 IL_006c: ldstr ""hello"" IL_0071: stloc.s V_6 IL_0073: ldloca.s V_7 IL_0075: call ""string int.ToString()"" IL_007a: ldstr "" "" IL_007f: ldloc.s V_6 IL_0081: call ""string string.Concat(string, string, string)"" IL_0086: call ""void System.Console.WriteLine(string)"" IL_008b: ret }"); } [Fact] public void MixedDeclarationAndAssignmentCSharpNine() { string source = @" class Program { static void Main() { int x1; (x1, string y1) = new A(); string y2; (int x2, y2) = new A(); bool z3; (int x3, (string y3, z3)) = new B(); int x4; (x4, var (y4, z4)) = new B(); } } class A { public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } class B { public void Deconstruct(out int a, out (string b, bool c) tuple) { a = 1; tuple = (""hello"", true); } } "; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (7,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (x1, string y1) = new A(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(x1, string y1) = new A()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(7, 9), // (9,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (int x2, y2) = new A(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x2, y2) = new A()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(9, 9), // (11,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (int x3, (string y3, z3)) = new B(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x3, (string y3, z3)) = new B()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(11, 9), // (13,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater. // (x4, var (y4, z4)) = new B(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(x4, var (y4, z4)) = new B()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(13, 9)); } [Fact] public void NestedMixedDeclarationAndAssignmentPermutations() { string source = @" class C { static void Main() { int x1; string y1; (x1, (y1, var z1)) = new C(); System.Console.WriteLine(x1 + "" "" + y1 + "" "" + z1); int x2; bool z2; (x2, (var y2, z2)) = new C(); System.Console.WriteLine(x2 + "" "" + y2 + "" "" + z2); string y3; bool z3; (var x3, (y3, z3)) = new C(); System.Console.WriteLine(x3 + "" "" + y3 + "" "" + z3); bool z4; (var x4, (var y4, z4)) = new C(); System.Console.WriteLine(x4 + "" "" + y4 + "" "" + z4); string y5; (var x5, (y5, var z5)) = new C(); System.Console.WriteLine(x5 + "" "" + y5 + "" "" + z5); int x6; (x6, (var y6, var z6)) = new C(); System.Console.WriteLine(x6 + "" "" + y6 + "" "" + z6); int x7; (x7, var (y7, z7)) = new C(); System.Console.WriteLine(x7 + "" "" + y7 + "" "" + z7); } public void Deconstruct(out int a, out (string a, bool b) b) { a = 1; b = (""hello"", true); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello True 1 hello True 1 hello True 1 hello True 1 hello True 1 hello True 1 hello True"); comp.VerifyDiagnostics(); } [Fact] public void MixedDeclarationAndAssignmentUseBeforeDeclaration() { string source = @" class Program { static void Main() { (x1, string y1) = new A(); int x1; (int x2, y2) = new A(); string y2; (int x3, (string y3, z3)) = new B(); bool z3; (x4, var (y4, z4)) = new B(); int x4; } } class A { public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } class B { public void Deconstruct(out int a, out (string b, bool c) tuple) { a = 1; tuple = (""hello"", true); } } "; CreateCompilation(source, parseOptions: TestOptions.RegularPreview) .VerifyDiagnostics( // (6,10): error CS0841: Cannot use local variable 'x1' before it is declared // (x1, string y1) = new A(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1", isSuppressed: false).WithArguments("x1").WithLocation(6, 10), // (8,18): error CS0841: Cannot use local variable 'y2' before it is declared // (int x2, y2) = new A(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y2", isSuppressed: false).WithArguments("y2").WithLocation(8, 18), // (10,30): error CS0841: Cannot use local variable 'z3' before it is declared // (int x3, (string y3, z3)) = new B(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "z3", isSuppressed: false).WithArguments("z3").WithLocation(10, 30), // (12,10): error CS0841: Cannot use local variable 'x4' before it is declared // (x4, var (y4, z4)) = new B(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4", isSuppressed: false).WithArguments("x4").WithLocation(12, 10)); } [Fact] public void MixedDeclarationAndAssignmentUseDeclaredVariableInAssignment() { string source = @" class Program { static void Main() { (var x1, x1) = new A(); (x2, var x2) = new A(); (var x3, (var y3, x3)) = new B(); (x4, (var y4, var x4)) = new B(); } } class A { public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; } } class B { public void Deconstruct(out int a, out (string b, bool c) tuple) { a = 1; tuple = (""hello"", true); } } "; CreateCompilation(source, parseOptions: TestOptions.RegularPreview) .VerifyDiagnostics( // (6,18): error CS0841: Cannot use local variable 'x1' before it is declared // (var x1, x1) = new A(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 18), // (7,10): error CS0841: Cannot use local variable 'x2' before it is declared // (x2, var x2) = new A(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(7, 10), // (8,27): error CS0841: Cannot use local variable 'x3' before it is declared // (var x3, (var y3, x3)) = new B(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x3").WithArguments("x3").WithLocation(8, 27), // (9,10): error CS0841: Cannot use local variable 'x4' before it is declared // (x4, (var y4, var x4)) = new B(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 10)); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/Core/Portable/DiagnosticAnalyzer/DiagnosticStartAnalysisScope.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.Concurrent; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Scope for setting up analyzers for an entire session, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerAnalysisContext : AnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostSessionStartAnalysisScope _scope; public AnalyzerAnalysisContext(DiagnosticAnalyzer analyzer, HostSessionStartAnalysisScope scope) { _analyzer = analyzer; _scope = scope; } public override void RegisterCompilationStartAction(Action<CompilationStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationStartAction(_analyzer, action); } public override void RegisterCompilationAction(Action<CompilationAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterAdditionalFileAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void EnableConcurrentExecution() { _scope.EnableConcurrentExecution(_analyzer); } public override void ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags mode) { _scope.ConfigureGeneratedCodeAnalysis(_analyzer, mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCompilationStartAnalysisContext : CompilationStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCompilationStartAnalysisScope _scope; private readonly CompilationAnalysisValueProviderFactory _compilationAnalysisValueProviderFactory; public AnalyzerCompilationStartAnalysisContext( DiagnosticAnalyzer analyzer, HostCompilationStartAnalysisScope scope, Compilation compilation, AnalyzerOptions options, CompilationAnalysisValueProviderFactory compilationAnalysisValueProviderFactory, CancellationToken cancellationToken) : base(compilation, options, cancellationToken) { _analyzer = analyzer; _scope = scope; _compilationAnalysisValueProviderFactory = compilationAnalysisValueProviderFactory; } public override void RegisterCompilationEndAction(Action<CompilationAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationEndAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterAdditionalFileAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } internal override bool TryGetValueCore<TKey, TValue>(TKey key, AnalysisValueProvider<TKey, TValue> valueProvider, [MaybeNullWhen(false)] out TValue value) { var compilationAnalysisValueProvider = _compilationAnalysisValueProviderFactory.GetValueProvider(valueProvider); return compilationAnalysisValueProvider.TryGetValue(key, out value); } } /// <summary> /// Scope for setting up analyzers for code within a symbol and its members. /// </summary> internal sealed class AnalyzerSymbolStartAnalysisContext : SymbolStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostSymbolStartAnalysisScope _scope; internal AnalyzerSymbolStartAnalysisContext(DiagnosticAnalyzer analyzer, HostSymbolStartAnalysisScope scope, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken) : base(owningSymbol, compilation, options, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterSymbolEndAction(Action<SymbolAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolEndAction(_analyzer, action); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } } /// <summary> /// Scope for setting up analyzers for a code block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCodeBlockStartAnalysisContext<TLanguageKindEnum> : CodeBlockStartAnalysisContext<TLanguageKindEnum> where TLanguageKindEnum : struct { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCodeBlockStartAnalysisScope<TLanguageKindEnum> _scope; internal AnalyzerCodeBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostCodeBlockStartAnalysisScope<TLanguageKindEnum> scope, SyntaxNode codeBlock, ISymbol owningSymbol, SemanticModel semanticModel, AnalyzerOptions options, CancellationToken cancellationToken) : base(codeBlock, owningSymbol, semanticModel, options, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterCodeBlockEndAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockEndAction(_analyzer, action); } public override void RegisterSyntaxNodeAction(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } } /// <summary> /// Scope for setting up analyzers for an operation block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerOperationBlockStartAnalysisContext : OperationBlockStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostOperationBlockStartAnalysisScope _scope; internal AnalyzerOperationBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostOperationBlockStartAnalysisScope scope, ImmutableArray<IOperation> operationBlocks, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, Func<IOperation, ControlFlowGraph> getControlFlowGraph, CancellationToken cancellationToken) : base(operationBlocks, owningSymbol, compilation, options, getControlFlowGraph, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterOperationBlockEndAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockEndAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } } /// <summary> /// Scope for setting up analyzers for an entire session, capable of retrieving the actions. /// </summary> internal sealed class HostSessionStartAnalysisScope : HostAnalysisScope { private ImmutableHashSet<DiagnosticAnalyzer> _concurrentAnalyzers = ImmutableHashSet<DiagnosticAnalyzer>.Empty; private readonly ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags> _generatedCodeConfigurationMap = new ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags>(); public bool IsConcurrentAnalyzer(DiagnosticAnalyzer analyzer) { return _concurrentAnalyzers.Contains(analyzer); } public GeneratedCodeAnalysisFlags GetGeneratedCodeAnalysisFlags(DiagnosticAnalyzer analyzer) { GeneratedCodeAnalysisFlags mode; return _generatedCodeConfigurationMap.TryGetValue(analyzer, out mode) ? mode : AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags; } public void RegisterCompilationStartAction(DiagnosticAnalyzer analyzer, Action<CompilationStartAnalysisContext> action) { CompilationStartAnalyzerAction analyzerAction = new CompilationStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationStartAction(analyzerAction); } public void EnableConcurrentExecution(DiagnosticAnalyzer analyzer) { _concurrentAnalyzers = _concurrentAnalyzers.Add(analyzer); GetOrCreateAnalyzerActions(analyzer).Value.EnableConcurrentExecution(); } public void ConfigureGeneratedCodeAnalysis(DiagnosticAnalyzer analyzer, GeneratedCodeAnalysisFlags mode) { _generatedCodeConfigurationMap.AddOrUpdate(analyzer, addValue: mode, updateValueFactory: (a, c) => mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, capable of retrieving the actions. /// </summary> internal sealed class HostCompilationStartAnalysisScope : HostAnalysisScope { private readonly HostSessionStartAnalysisScope _sessionScope; public HostCompilationStartAnalysisScope(HostSessionStartAnalysisScope sessionScope) { _sessionScope = sessionScope; } public override AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { AnalyzerActions compilationActions = base.GetAnalyzerActions(analyzer); AnalyzerActions sessionActions = _sessionScope.GetAnalyzerActions(analyzer); if (sessionActions.IsEmpty) { return compilationActions; } if (compilationActions.IsEmpty) { return sessionActions; } return compilationActions.Append(in sessionActions); } } /// <summary> /// Scope for setting up analyzers for analyzing a symbol and its members. /// </summary> internal sealed class HostSymbolStartAnalysisScope : HostAnalysisScope { public HostSymbolStartAnalysisScope() { } } /// <summary> /// Scope for setting up analyzers for a code block, capable of retrieving the actions. /// </summary> internal sealed class HostCodeBlockStartAnalysisScope<TLanguageKindEnum> where TLanguageKindEnum : struct { private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; private ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> _syntaxNodeActions = ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.Empty; public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } public ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> SyntaxNodeActions { get { return _syntaxNodeActions; } } internal HostCodeBlockStartAnalysisScope() { } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { _codeBlockEndActions = _codeBlockEndActions.Add(new CodeBlockAnalyzerAction(action, analyzer)); } public void RegisterSyntaxNodeAction(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { _syntaxNodeActions = _syntaxNodeActions.Add(new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer)); } } internal sealed class HostOperationBlockStartAnalysisScope { private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; private ImmutableArray<OperationAnalyzerAction> _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions => _operationBlockEndActions; public ImmutableArray<OperationAnalyzerAction> OperationActions => _operationActions; internal HostOperationBlockStartAnalysisScope() { } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { _operationBlockEndActions = _operationBlockEndActions.Add(new OperationBlockAnalyzerAction(action, analyzer)); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { _operationActions = _operationActions.Add(new OperationAnalyzerAction(action, operationKinds, analyzer)); } } internal abstract class HostAnalysisScope { private readonly ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>> _analyzerActions = new ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>>(); public virtual AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { return this.GetOrCreateAnalyzerActions(analyzer).Value; } public void RegisterCompilationAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationAction(analyzerAction); } public void RegisterCompilationEndAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationEndAction(analyzerAction); } public void RegisterSemanticModelAction(DiagnosticAnalyzer analyzer, Action<SemanticModelAnalysisContext> action) { SemanticModelAnalyzerAction analyzerAction = new SemanticModelAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSemanticModelAction(analyzerAction); } public void RegisterSyntaxTreeAction(DiagnosticAnalyzer analyzer, Action<SyntaxTreeAnalysisContext> action) { SyntaxTreeAnalyzerAction analyzerAction = new SyntaxTreeAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxTreeAction(analyzerAction); } public void RegisterAdditionalFileAction(DiagnosticAnalyzer analyzer, Action<AdditionalFileAnalysisContext> action) { var analyzerAction = new AdditionalFileAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddAdditionalFileAction(analyzerAction); } public void RegisterSymbolAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { SymbolAnalyzerAction analyzerAction = new SymbolAnalyzerAction(action, symbolKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolAction(analyzerAction); // The SymbolAnalyzerAction does not handle SymbolKind.Parameter because the compiler // does not make CompilationEvents for them. As a workaround, handle them specially by // registering further SymbolActions (for Methods) and utilize the results to construct // the necessary SymbolAnalysisContexts. if (symbolKinds.Contains(SymbolKind.Parameter)) { RegisterSymbolAction( analyzer, context => { ImmutableArray<IParameterSymbol> parameters; switch (context.Symbol.Kind) { case SymbolKind.Method: parameters = ((IMethodSymbol)context.Symbol).Parameters; break; case SymbolKind.Property: parameters = ((IPropertySymbol)context.Symbol).Parameters; break; case SymbolKind.NamedType: var namedType = (INamedTypeSymbol)context.Symbol; var delegateInvokeMethod = namedType.DelegateInvokeMethod; parameters = delegateInvokeMethod?.Parameters ?? ImmutableArray.Create<IParameterSymbol>(); break; default: throw new ArgumentException($"{context.Symbol.Kind} is not supported.", nameof(context)); } foreach (var parameter in parameters) { if (!parameter.IsImplicitlyDeclared) { action(new SymbolAnalysisContext( parameter, context.Compilation, context.Options, context.ReportDiagnostic, context.IsSupportedDiagnostic, context.CancellationToken)); } } }, ImmutableArray.Create(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType)); } } public void RegisterSymbolStartAction(DiagnosticAnalyzer analyzer, Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { var analyzerAction = new SymbolStartAnalyzerAction(action, symbolKind, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolStartAction(analyzerAction); } public void RegisterSymbolEndAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action) { var analyzerAction = new SymbolEndAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolEndAction(analyzerAction); } public void RegisterCodeBlockStartAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) where TLanguageKindEnum : struct { CodeBlockStartAnalyzerAction<TLanguageKindEnum> analyzerAction = new CodeBlockStartAnalyzerAction<TLanguageKindEnum>(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockStartAction(analyzerAction); } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockEndAction(analyzerAction); } public void RegisterCodeBlockAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockAction(analyzerAction); } public void RegisterSyntaxNodeAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) where TLanguageKindEnum : struct { SyntaxNodeAnalyzerAction<TLanguageKindEnum> analyzerAction = new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxNodeAction(analyzerAction); } public void RegisterOperationBlockStartAction(DiagnosticAnalyzer analyzer, Action<OperationBlockStartAnalysisContext> action) { OperationBlockStartAnalyzerAction analyzerAction = new OperationBlockStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockStartAction(analyzerAction); } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockEndAction(analyzerAction); } public void RegisterOperationBlockAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockAction(analyzerAction); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { OperationAnalyzerAction analyzerAction = new OperationAnalyzerAction(action, operationKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationAction(analyzerAction); } protected StrongBox<AnalyzerActions> GetOrCreateAnalyzerActions(DiagnosticAnalyzer analyzer) { return _analyzerActions.GetOrAdd(analyzer, _ => new StrongBox<AnalyzerActions>(AnalyzerActions.Empty)); } } /// <summary> /// Actions registered by a particular analyzer. /// </summary> // ToDo: AnalyzerActions, and all of the mechanism around it, can be eliminated if the IDE diagnostic analyzer driver // moves from an analyzer-centric model to an action-centric model. For example, the driver would need to stop asking // if a particular analyzer can analyze syntax trees, and instead ask if any syntax tree actions are present. Also, // the driver needs to apply all relevant actions rather then applying the actions of individual analyzers. internal struct AnalyzerActions { public static readonly AnalyzerActions Empty = new AnalyzerActions(concurrent: false); private ImmutableArray<CompilationStartAnalyzerAction> _compilationStartActions; private ImmutableArray<CompilationAnalyzerAction> _compilationEndActions; private ImmutableArray<CompilationAnalyzerAction> _compilationActions; private ImmutableArray<SyntaxTreeAnalyzerAction> _syntaxTreeActions; private ImmutableArray<AdditionalFileAnalyzerAction> _additionalFileActions; private ImmutableArray<SemanticModelAnalyzerAction> _semanticModelActions; private ImmutableArray<SymbolAnalyzerAction> _symbolActions; private ImmutableArray<SymbolStartAnalyzerAction> _symbolStartActions; private ImmutableArray<SymbolEndAnalyzerAction> _symbolEndActions; private ImmutableArray<AnalyzerAction> _codeBlockStartActions; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockActions; private ImmutableArray<OperationBlockStartAnalyzerAction> _operationBlockStartActions; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockActions; private ImmutableArray<AnalyzerAction> _syntaxNodeActions; private ImmutableArray<OperationAnalyzerAction> _operationActions; private bool _concurrent; internal AnalyzerActions(bool concurrent) { _compilationStartActions = ImmutableArray<CompilationStartAnalyzerAction>.Empty; _compilationEndActions = ImmutableArray<CompilationAnalyzerAction>.Empty; _compilationActions = ImmutableArray<CompilationAnalyzerAction>.Empty; _syntaxTreeActions = ImmutableArray<SyntaxTreeAnalyzerAction>.Empty; _additionalFileActions = ImmutableArray<AdditionalFileAnalyzerAction>.Empty; _semanticModelActions = ImmutableArray<SemanticModelAnalyzerAction>.Empty; _symbolActions = ImmutableArray<SymbolAnalyzerAction>.Empty; _symbolStartActions = ImmutableArray<SymbolStartAnalyzerAction>.Empty; _symbolEndActions = ImmutableArray<SymbolEndAnalyzerAction>.Empty; _codeBlockStartActions = ImmutableArray<AnalyzerAction>.Empty; _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; _codeBlockActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; _operationBlockStartActions = ImmutableArray<OperationBlockStartAnalyzerAction>.Empty; _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; _operationBlockActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; _syntaxNodeActions = ImmutableArray<AnalyzerAction>.Empty; _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; _concurrent = concurrent; IsEmpty = true; } public AnalyzerActions( ImmutableArray<CompilationStartAnalyzerAction> compilationStartActions, ImmutableArray<CompilationAnalyzerAction> compilationEndActions, ImmutableArray<CompilationAnalyzerAction> compilationActions, ImmutableArray<SyntaxTreeAnalyzerAction> syntaxTreeActions, ImmutableArray<AdditionalFileAnalyzerAction> additionalFileActions, ImmutableArray<SemanticModelAnalyzerAction> semanticModelActions, ImmutableArray<SymbolAnalyzerAction> symbolActions, ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions, ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, ImmutableArray<AnalyzerAction> codeBlockStartActions, ImmutableArray<CodeBlockAnalyzerAction> codeBlockEndActions, ImmutableArray<CodeBlockAnalyzerAction> codeBlockActions, ImmutableArray<OperationBlockStartAnalyzerAction> operationBlockStartActions, ImmutableArray<OperationBlockAnalyzerAction> operationBlockEndActions, ImmutableArray<OperationBlockAnalyzerAction> operationBlockActions, ImmutableArray<AnalyzerAction> syntaxNodeActions, ImmutableArray<OperationAnalyzerAction> operationActions, bool concurrent, bool isEmpty) { _compilationStartActions = compilationStartActions; _compilationEndActions = compilationEndActions; _compilationActions = compilationActions; _syntaxTreeActions = syntaxTreeActions; _additionalFileActions = additionalFileActions; _semanticModelActions = semanticModelActions; _symbolActions = symbolActions; _symbolStartActions = symbolStartActions; _symbolEndActions = symbolEndActions; _codeBlockStartActions = codeBlockStartActions; _codeBlockEndActions = codeBlockEndActions; _codeBlockActions = codeBlockActions; _operationBlockStartActions = operationBlockStartActions; _operationBlockEndActions = operationBlockEndActions; _operationBlockActions = operationBlockActions; _syntaxNodeActions = syntaxNodeActions; _operationActions = operationActions; _concurrent = concurrent; IsEmpty = isEmpty; } public readonly int CompilationStartActionsCount { get { return _compilationStartActions.Length; } } public readonly int CompilationEndActionsCount { get { return _compilationEndActions.Length; } } public readonly int CompilationActionsCount { get { return _compilationActions.Length; } } public readonly int SyntaxTreeActionsCount { get { return _syntaxTreeActions.Length; } } public readonly int AdditionalFileActionsCount { get { return _additionalFileActions.Length; } } public readonly int SemanticModelActionsCount { get { return _semanticModelActions.Length; } } public readonly int SymbolActionsCount { get { return _symbolActions.Length; } } public readonly int SymbolStartActionsCount { get { return _symbolStartActions.Length; } } public readonly int SymbolEndActionsCount { get { return _symbolEndActions.Length; } } public readonly int SyntaxNodeActionsCount { get { return _syntaxNodeActions.Length; } } public readonly int OperationActionsCount { get { return _operationActions.Length; } } public readonly int OperationBlockStartActionsCount { get { return _operationBlockStartActions.Length; } } public readonly int OperationBlockEndActionsCount { get { return _operationBlockEndActions.Length; } } public readonly int OperationBlockActionsCount { get { return _operationBlockActions.Length; } } public readonly int CodeBlockStartActionsCount { get { return _codeBlockStartActions.Length; } } public readonly int CodeBlockEndActionsCount { get { return _codeBlockEndActions.Length; } } public readonly int CodeBlockActionsCount { get { return _codeBlockActions.Length; } } public readonly bool Concurrent => _concurrent; public bool IsEmpty { readonly get; private set; } public readonly bool IsDefault => _compilationStartActions.IsDefault; internal readonly ImmutableArray<CompilationStartAnalyzerAction> CompilationStartActions { get { return _compilationStartActions; } } internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationEndActions { get { return _compilationEndActions; } } internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationActions { get { return _compilationActions; } } internal readonly ImmutableArray<SyntaxTreeAnalyzerAction> SyntaxTreeActions { get { return _syntaxTreeActions; } } internal readonly ImmutableArray<AdditionalFileAnalyzerAction> AdditionalFileActions { get { return _additionalFileActions; } } internal readonly ImmutableArray<SemanticModelAnalyzerAction> SemanticModelActions { get { return _semanticModelActions; } } internal readonly ImmutableArray<SymbolAnalyzerAction> SymbolActions { get { return _symbolActions; } } internal readonly ImmutableArray<SymbolStartAnalyzerAction> SymbolStartActions { get { return _symbolStartActions; } } internal readonly ImmutableArray<SymbolEndAnalyzerAction> SymbolEndActions { get { return _symbolEndActions; } } internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockActions { get { return _codeBlockActions; } } internal readonly ImmutableArray<CodeBlockStartAnalyzerAction<TLanguageKindEnum>> GetCodeBlockStartActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _codeBlockStartActions.OfType<CodeBlockStartAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _syntaxNodeActions.OfType<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>(DiagnosticAnalyzer analyzer) where TLanguageKindEnum : struct { var builder = ArrayBuilder<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.GetInstance(); foreach (var action in _syntaxNodeActions) { if (action.Analyzer == analyzer && action is SyntaxNodeAnalyzerAction<TLanguageKindEnum> syntaxNodeAction) { builder.Add(syntaxNodeAction); } } return builder.ToImmutableAndFree(); } internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockActions { get { return _operationBlockActions; } } internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions { get { return _operationBlockEndActions; } } internal readonly ImmutableArray<OperationBlockStartAnalyzerAction> OperationBlockStartActions { get { return _operationBlockStartActions; } } internal readonly ImmutableArray<OperationAnalyzerAction> OperationActions { get { return _operationActions; } } internal void AddCompilationStartAction(CompilationStartAnalyzerAction action) { _compilationStartActions = _compilationStartActions.Add(action); IsEmpty = false; } internal void AddCompilationEndAction(CompilationAnalyzerAction action) { _compilationEndActions = _compilationEndActions.Add(action); IsEmpty = false; } internal void AddCompilationAction(CompilationAnalyzerAction action) { _compilationActions = _compilationActions.Add(action); IsEmpty = false; } internal void AddSyntaxTreeAction(SyntaxTreeAnalyzerAction action) { _syntaxTreeActions = _syntaxTreeActions.Add(action); IsEmpty = false; } internal void AddAdditionalFileAction(AdditionalFileAnalyzerAction action) { _additionalFileActions = _additionalFileActions.Add(action); IsEmpty = false; } internal void AddSemanticModelAction(SemanticModelAnalyzerAction action) { _semanticModelActions = _semanticModelActions.Add(action); IsEmpty = false; } internal void AddSymbolAction(SymbolAnalyzerAction action) { _symbolActions = _symbolActions.Add(action); IsEmpty = false; } internal void AddSymbolStartAction(SymbolStartAnalyzerAction action) { _symbolStartActions = _symbolStartActions.Add(action); IsEmpty = false; } internal void AddSymbolEndAction(SymbolEndAnalyzerAction action) { _symbolEndActions = _symbolEndActions.Add(action); IsEmpty = false; } internal void AddCodeBlockStartAction<TLanguageKindEnum>(CodeBlockStartAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _codeBlockStartActions = _codeBlockStartActions.Add(action); IsEmpty = false; } internal void AddCodeBlockEndAction(CodeBlockAnalyzerAction action) { _codeBlockEndActions = _codeBlockEndActions.Add(action); IsEmpty = false; } internal void AddCodeBlockAction(CodeBlockAnalyzerAction action) { _codeBlockActions = _codeBlockActions.Add(action); IsEmpty = false; } internal void AddSyntaxNodeAction<TLanguageKindEnum>(SyntaxNodeAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _syntaxNodeActions = _syntaxNodeActions.Add(action); IsEmpty = false; } internal void AddOperationBlockStartAction(OperationBlockStartAnalyzerAction action) { _operationBlockStartActions = _operationBlockStartActions.Add(action); IsEmpty = false; } internal void AddOperationBlockAction(OperationBlockAnalyzerAction action) { _operationBlockActions = _operationBlockActions.Add(action); IsEmpty = false; } internal void AddOperationBlockEndAction(OperationBlockAnalyzerAction action) { _operationBlockEndActions = _operationBlockEndActions.Add(action); IsEmpty = false; } internal void AddOperationAction(OperationAnalyzerAction action) { _operationActions = _operationActions.Add(action); IsEmpty = false; } internal void EnableConcurrentExecution() { _concurrent = true; } /// <summary> /// Append analyzer actions from <paramref name="otherActions"/> to actions from this instance. /// </summary> /// <param name="otherActions">Analyzer actions to append</param>. public readonly AnalyzerActions Append(in AnalyzerActions otherActions, bool appendSymbolStartAndSymbolEndActions = true) { if (otherActions.IsDefault) { throw new ArgumentNullException(nameof(otherActions)); } AnalyzerActions actions = new AnalyzerActions(concurrent: _concurrent || otherActions.Concurrent); actions._compilationStartActions = _compilationStartActions.AddRange(otherActions._compilationStartActions); actions._compilationEndActions = _compilationEndActions.AddRange(otherActions._compilationEndActions); actions._compilationActions = _compilationActions.AddRange(otherActions._compilationActions); actions._syntaxTreeActions = _syntaxTreeActions.AddRange(otherActions._syntaxTreeActions); actions._additionalFileActions = _additionalFileActions.AddRange(otherActions._additionalFileActions); actions._semanticModelActions = _semanticModelActions.AddRange(otherActions._semanticModelActions); actions._symbolActions = _symbolActions.AddRange(otherActions._symbolActions); actions._symbolStartActions = appendSymbolStartAndSymbolEndActions ? _symbolStartActions.AddRange(otherActions._symbolStartActions) : _symbolStartActions; actions._symbolEndActions = appendSymbolStartAndSymbolEndActions ? _symbolEndActions.AddRange(otherActions._symbolEndActions) : _symbolEndActions; actions._codeBlockStartActions = _codeBlockStartActions.AddRange(otherActions._codeBlockStartActions); actions._codeBlockEndActions = _codeBlockEndActions.AddRange(otherActions._codeBlockEndActions); actions._codeBlockActions = _codeBlockActions.AddRange(otherActions._codeBlockActions); actions._syntaxNodeActions = _syntaxNodeActions.AddRange(otherActions._syntaxNodeActions); actions._operationActions = _operationActions.AddRange(otherActions._operationActions); actions._operationBlockStartActions = _operationBlockStartActions.AddRange(otherActions._operationBlockStartActions); actions._operationBlockEndActions = _operationBlockEndActions.AddRange(otherActions._operationBlockEndActions); actions._operationBlockActions = _operationBlockActions.AddRange(otherActions._operationBlockActions); actions.IsEmpty = IsEmpty && otherActions.IsEmpty; return actions; } } }
// Licensed to the .NET Foundation under one or more 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.Concurrent; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Scope for setting up analyzers for an entire session, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerAnalysisContext : AnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostSessionStartAnalysisScope _scope; public AnalyzerAnalysisContext(DiagnosticAnalyzer analyzer, HostSessionStartAnalysisScope scope) { _analyzer = analyzer; _scope = scope; } public override void RegisterCompilationStartAction(Action<CompilationStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationStartAction(_analyzer, action); } public override void RegisterCompilationAction(Action<CompilationAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterAdditionalFileAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void EnableConcurrentExecution() { _scope.EnableConcurrentExecution(_analyzer); } public override void ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags mode) { _scope.ConfigureGeneratedCodeAnalysis(_analyzer, mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCompilationStartAnalysisContext : CompilationStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCompilationStartAnalysisScope _scope; private readonly CompilationAnalysisValueProviderFactory _compilationAnalysisValueProviderFactory; public AnalyzerCompilationStartAnalysisContext( DiagnosticAnalyzer analyzer, HostCompilationStartAnalysisScope scope, Compilation compilation, AnalyzerOptions options, CompilationAnalysisValueProviderFactory compilationAnalysisValueProviderFactory, CancellationToken cancellationToken) : base(compilation, options, cancellationToken) { _analyzer = analyzer; _scope = scope; _compilationAnalysisValueProviderFactory = compilationAnalysisValueProviderFactory; } public override void RegisterCompilationEndAction(Action<CompilationAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationEndAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterAdditionalFileAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } internal override bool TryGetValueCore<TKey, TValue>(TKey key, AnalysisValueProvider<TKey, TValue> valueProvider, [MaybeNullWhen(false)] out TValue value) { var compilationAnalysisValueProvider = _compilationAnalysisValueProviderFactory.GetValueProvider(valueProvider); return compilationAnalysisValueProvider.TryGetValue(key, out value); } } /// <summary> /// Scope for setting up analyzers for code within a symbol and its members. /// </summary> internal sealed class AnalyzerSymbolStartAnalysisContext : SymbolStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostSymbolStartAnalysisScope _scope; internal AnalyzerSymbolStartAnalysisContext(DiagnosticAnalyzer analyzer, HostSymbolStartAnalysisScope scope, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken) : base(owningSymbol, compilation, options, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterSymbolEndAction(Action<SymbolAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolEndAction(_analyzer, action); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } } /// <summary> /// Scope for setting up analyzers for a code block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCodeBlockStartAnalysisContext<TLanguageKindEnum> : CodeBlockStartAnalysisContext<TLanguageKindEnum> where TLanguageKindEnum : struct { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCodeBlockStartAnalysisScope<TLanguageKindEnum> _scope; internal AnalyzerCodeBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostCodeBlockStartAnalysisScope<TLanguageKindEnum> scope, SyntaxNode codeBlock, ISymbol owningSymbol, SemanticModel semanticModel, AnalyzerOptions options, CancellationToken cancellationToken) : base(codeBlock, owningSymbol, semanticModel, options, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterCodeBlockEndAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockEndAction(_analyzer, action); } public override void RegisterSyntaxNodeAction(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } } /// <summary> /// Scope for setting up analyzers for an operation block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerOperationBlockStartAnalysisContext : OperationBlockStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostOperationBlockStartAnalysisScope _scope; internal AnalyzerOperationBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostOperationBlockStartAnalysisScope scope, ImmutableArray<IOperation> operationBlocks, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, Func<IOperation, ControlFlowGraph> getControlFlowGraph, CancellationToken cancellationToken) : base(operationBlocks, owningSymbol, compilation, options, getControlFlowGraph, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterOperationBlockEndAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockEndAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } } /// <summary> /// Scope for setting up analyzers for an entire session, capable of retrieving the actions. /// </summary> internal sealed class HostSessionStartAnalysisScope : HostAnalysisScope { private ImmutableHashSet<DiagnosticAnalyzer> _concurrentAnalyzers = ImmutableHashSet<DiagnosticAnalyzer>.Empty; private readonly ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags> _generatedCodeConfigurationMap = new ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags>(); public bool IsConcurrentAnalyzer(DiagnosticAnalyzer analyzer) { return _concurrentAnalyzers.Contains(analyzer); } public GeneratedCodeAnalysisFlags GetGeneratedCodeAnalysisFlags(DiagnosticAnalyzer analyzer) { GeneratedCodeAnalysisFlags mode; return _generatedCodeConfigurationMap.TryGetValue(analyzer, out mode) ? mode : AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags; } public void RegisterCompilationStartAction(DiagnosticAnalyzer analyzer, Action<CompilationStartAnalysisContext> action) { CompilationStartAnalyzerAction analyzerAction = new CompilationStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationStartAction(analyzerAction); } public void EnableConcurrentExecution(DiagnosticAnalyzer analyzer) { _concurrentAnalyzers = _concurrentAnalyzers.Add(analyzer); GetOrCreateAnalyzerActions(analyzer).Value.EnableConcurrentExecution(); } public void ConfigureGeneratedCodeAnalysis(DiagnosticAnalyzer analyzer, GeneratedCodeAnalysisFlags mode) { _generatedCodeConfigurationMap.AddOrUpdate(analyzer, addValue: mode, updateValueFactory: (a, c) => mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, capable of retrieving the actions. /// </summary> internal sealed class HostCompilationStartAnalysisScope : HostAnalysisScope { private readonly HostSessionStartAnalysisScope _sessionScope; public HostCompilationStartAnalysisScope(HostSessionStartAnalysisScope sessionScope) { _sessionScope = sessionScope; } public override AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { AnalyzerActions compilationActions = base.GetAnalyzerActions(analyzer); AnalyzerActions sessionActions = _sessionScope.GetAnalyzerActions(analyzer); if (sessionActions.IsEmpty) { return compilationActions; } if (compilationActions.IsEmpty) { return sessionActions; } return compilationActions.Append(in sessionActions); } } /// <summary> /// Scope for setting up analyzers for analyzing a symbol and its members. /// </summary> internal sealed class HostSymbolStartAnalysisScope : HostAnalysisScope { public HostSymbolStartAnalysisScope() { } } /// <summary> /// Scope for setting up analyzers for a code block, capable of retrieving the actions. /// </summary> internal sealed class HostCodeBlockStartAnalysisScope<TLanguageKindEnum> where TLanguageKindEnum : struct { private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; private ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> _syntaxNodeActions = ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.Empty; public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } public ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> SyntaxNodeActions { get { return _syntaxNodeActions; } } internal HostCodeBlockStartAnalysisScope() { } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { _codeBlockEndActions = _codeBlockEndActions.Add(new CodeBlockAnalyzerAction(action, analyzer)); } public void RegisterSyntaxNodeAction(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { _syntaxNodeActions = _syntaxNodeActions.Add(new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer)); } } internal sealed class HostOperationBlockStartAnalysisScope { private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; private ImmutableArray<OperationAnalyzerAction> _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions => _operationBlockEndActions; public ImmutableArray<OperationAnalyzerAction> OperationActions => _operationActions; internal HostOperationBlockStartAnalysisScope() { } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { _operationBlockEndActions = _operationBlockEndActions.Add(new OperationBlockAnalyzerAction(action, analyzer)); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { _operationActions = _operationActions.Add(new OperationAnalyzerAction(action, operationKinds, analyzer)); } } internal abstract class HostAnalysisScope { private readonly ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>> _analyzerActions = new ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>>(); public virtual AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { return this.GetOrCreateAnalyzerActions(analyzer).Value; } public void RegisterCompilationAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationAction(analyzerAction); } public void RegisterCompilationEndAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationEndAction(analyzerAction); } public void RegisterSemanticModelAction(DiagnosticAnalyzer analyzer, Action<SemanticModelAnalysisContext> action) { SemanticModelAnalyzerAction analyzerAction = new SemanticModelAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSemanticModelAction(analyzerAction); } public void RegisterSyntaxTreeAction(DiagnosticAnalyzer analyzer, Action<SyntaxTreeAnalysisContext> action) { SyntaxTreeAnalyzerAction analyzerAction = new SyntaxTreeAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxTreeAction(analyzerAction); } public void RegisterAdditionalFileAction(DiagnosticAnalyzer analyzer, Action<AdditionalFileAnalysisContext> action) { var analyzerAction = new AdditionalFileAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddAdditionalFileAction(analyzerAction); } public void RegisterSymbolAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { SymbolAnalyzerAction analyzerAction = new SymbolAnalyzerAction(action, symbolKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolAction(analyzerAction); // The SymbolAnalyzerAction does not handle SymbolKind.Parameter because the compiler // does not make CompilationEvents for them. As a workaround, handle them specially by // registering further SymbolActions (for Methods) and utilize the results to construct // the necessary SymbolAnalysisContexts. if (symbolKinds.Contains(SymbolKind.Parameter)) { RegisterSymbolAction( analyzer, context => { ImmutableArray<IParameterSymbol> parameters; switch (context.Symbol.Kind) { case SymbolKind.Method: parameters = ((IMethodSymbol)context.Symbol).Parameters; break; case SymbolKind.Property: parameters = ((IPropertySymbol)context.Symbol).Parameters; break; case SymbolKind.NamedType: var namedType = (INamedTypeSymbol)context.Symbol; var delegateInvokeMethod = namedType.DelegateInvokeMethod; parameters = delegateInvokeMethod?.Parameters ?? ImmutableArray.Create<IParameterSymbol>(); break; default: throw new ArgumentException($"{context.Symbol.Kind} is not supported.", nameof(context)); } foreach (var parameter in parameters) { if (!parameter.IsImplicitlyDeclared) { action(new SymbolAnalysisContext( parameter, context.Compilation, context.Options, context.ReportDiagnostic, context.IsSupportedDiagnostic, context.CancellationToken)); } } }, ImmutableArray.Create(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType)); } } public void RegisterSymbolStartAction(DiagnosticAnalyzer analyzer, Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { var analyzerAction = new SymbolStartAnalyzerAction(action, symbolKind, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolStartAction(analyzerAction); } public void RegisterSymbolEndAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action) { var analyzerAction = new SymbolEndAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolEndAction(analyzerAction); } public void RegisterCodeBlockStartAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) where TLanguageKindEnum : struct { CodeBlockStartAnalyzerAction<TLanguageKindEnum> analyzerAction = new CodeBlockStartAnalyzerAction<TLanguageKindEnum>(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockStartAction(analyzerAction); } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockEndAction(analyzerAction); } public void RegisterCodeBlockAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockAction(analyzerAction); } public void RegisterSyntaxNodeAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) where TLanguageKindEnum : struct { SyntaxNodeAnalyzerAction<TLanguageKindEnum> analyzerAction = new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxNodeAction(analyzerAction); } public void RegisterOperationBlockStartAction(DiagnosticAnalyzer analyzer, Action<OperationBlockStartAnalysisContext> action) { OperationBlockStartAnalyzerAction analyzerAction = new OperationBlockStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockStartAction(analyzerAction); } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockEndAction(analyzerAction); } public void RegisterOperationBlockAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockAction(analyzerAction); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { OperationAnalyzerAction analyzerAction = new OperationAnalyzerAction(action, operationKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationAction(analyzerAction); } protected StrongBox<AnalyzerActions> GetOrCreateAnalyzerActions(DiagnosticAnalyzer analyzer) { return _analyzerActions.GetOrAdd(analyzer, _ => new StrongBox<AnalyzerActions>(AnalyzerActions.Empty)); } } /// <summary> /// Actions registered by a particular analyzer. /// </summary> // ToDo: AnalyzerActions, and all of the mechanism around it, can be eliminated if the IDE diagnostic analyzer driver // moves from an analyzer-centric model to an action-centric model. For example, the driver would need to stop asking // if a particular analyzer can analyze syntax trees, and instead ask if any syntax tree actions are present. Also, // the driver needs to apply all relevant actions rather then applying the actions of individual analyzers. internal struct AnalyzerActions { public static readonly AnalyzerActions Empty = new AnalyzerActions(concurrent: false); private ImmutableArray<CompilationStartAnalyzerAction> _compilationStartActions; private ImmutableArray<CompilationAnalyzerAction> _compilationEndActions; private ImmutableArray<CompilationAnalyzerAction> _compilationActions; private ImmutableArray<SyntaxTreeAnalyzerAction> _syntaxTreeActions; private ImmutableArray<AdditionalFileAnalyzerAction> _additionalFileActions; private ImmutableArray<SemanticModelAnalyzerAction> _semanticModelActions; private ImmutableArray<SymbolAnalyzerAction> _symbolActions; private ImmutableArray<SymbolStartAnalyzerAction> _symbolStartActions; private ImmutableArray<SymbolEndAnalyzerAction> _symbolEndActions; private ImmutableArray<AnalyzerAction> _codeBlockStartActions; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockActions; private ImmutableArray<OperationBlockStartAnalyzerAction> _operationBlockStartActions; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockActions; private ImmutableArray<AnalyzerAction> _syntaxNodeActions; private ImmutableArray<OperationAnalyzerAction> _operationActions; private bool _concurrent; internal AnalyzerActions(bool concurrent) { _compilationStartActions = ImmutableArray<CompilationStartAnalyzerAction>.Empty; _compilationEndActions = ImmutableArray<CompilationAnalyzerAction>.Empty; _compilationActions = ImmutableArray<CompilationAnalyzerAction>.Empty; _syntaxTreeActions = ImmutableArray<SyntaxTreeAnalyzerAction>.Empty; _additionalFileActions = ImmutableArray<AdditionalFileAnalyzerAction>.Empty; _semanticModelActions = ImmutableArray<SemanticModelAnalyzerAction>.Empty; _symbolActions = ImmutableArray<SymbolAnalyzerAction>.Empty; _symbolStartActions = ImmutableArray<SymbolStartAnalyzerAction>.Empty; _symbolEndActions = ImmutableArray<SymbolEndAnalyzerAction>.Empty; _codeBlockStartActions = ImmutableArray<AnalyzerAction>.Empty; _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; _codeBlockActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; _operationBlockStartActions = ImmutableArray<OperationBlockStartAnalyzerAction>.Empty; _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; _operationBlockActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; _syntaxNodeActions = ImmutableArray<AnalyzerAction>.Empty; _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; _concurrent = concurrent; IsEmpty = true; } public AnalyzerActions( ImmutableArray<CompilationStartAnalyzerAction> compilationStartActions, ImmutableArray<CompilationAnalyzerAction> compilationEndActions, ImmutableArray<CompilationAnalyzerAction> compilationActions, ImmutableArray<SyntaxTreeAnalyzerAction> syntaxTreeActions, ImmutableArray<AdditionalFileAnalyzerAction> additionalFileActions, ImmutableArray<SemanticModelAnalyzerAction> semanticModelActions, ImmutableArray<SymbolAnalyzerAction> symbolActions, ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions, ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, ImmutableArray<AnalyzerAction> codeBlockStartActions, ImmutableArray<CodeBlockAnalyzerAction> codeBlockEndActions, ImmutableArray<CodeBlockAnalyzerAction> codeBlockActions, ImmutableArray<OperationBlockStartAnalyzerAction> operationBlockStartActions, ImmutableArray<OperationBlockAnalyzerAction> operationBlockEndActions, ImmutableArray<OperationBlockAnalyzerAction> operationBlockActions, ImmutableArray<AnalyzerAction> syntaxNodeActions, ImmutableArray<OperationAnalyzerAction> operationActions, bool concurrent, bool isEmpty) { _compilationStartActions = compilationStartActions; _compilationEndActions = compilationEndActions; _compilationActions = compilationActions; _syntaxTreeActions = syntaxTreeActions; _additionalFileActions = additionalFileActions; _semanticModelActions = semanticModelActions; _symbolActions = symbolActions; _symbolStartActions = symbolStartActions; _symbolEndActions = symbolEndActions; _codeBlockStartActions = codeBlockStartActions; _codeBlockEndActions = codeBlockEndActions; _codeBlockActions = codeBlockActions; _operationBlockStartActions = operationBlockStartActions; _operationBlockEndActions = operationBlockEndActions; _operationBlockActions = operationBlockActions; _syntaxNodeActions = syntaxNodeActions; _operationActions = operationActions; _concurrent = concurrent; IsEmpty = isEmpty; } public readonly int CompilationStartActionsCount { get { return _compilationStartActions.Length; } } public readonly int CompilationEndActionsCount { get { return _compilationEndActions.Length; } } public readonly int CompilationActionsCount { get { return _compilationActions.Length; } } public readonly int SyntaxTreeActionsCount { get { return _syntaxTreeActions.Length; } } public readonly int AdditionalFileActionsCount { get { return _additionalFileActions.Length; } } public readonly int SemanticModelActionsCount { get { return _semanticModelActions.Length; } } public readonly int SymbolActionsCount { get { return _symbolActions.Length; } } public readonly int SymbolStartActionsCount { get { return _symbolStartActions.Length; } } public readonly int SymbolEndActionsCount { get { return _symbolEndActions.Length; } } public readonly int SyntaxNodeActionsCount { get { return _syntaxNodeActions.Length; } } public readonly int OperationActionsCount { get { return _operationActions.Length; } } public readonly int OperationBlockStartActionsCount { get { return _operationBlockStartActions.Length; } } public readonly int OperationBlockEndActionsCount { get { return _operationBlockEndActions.Length; } } public readonly int OperationBlockActionsCount { get { return _operationBlockActions.Length; } } public readonly int CodeBlockStartActionsCount { get { return _codeBlockStartActions.Length; } } public readonly int CodeBlockEndActionsCount { get { return _codeBlockEndActions.Length; } } public readonly int CodeBlockActionsCount { get { return _codeBlockActions.Length; } } public readonly bool Concurrent => _concurrent; public bool IsEmpty { readonly get; private set; } public readonly bool IsDefault => _compilationStartActions.IsDefault; internal readonly ImmutableArray<CompilationStartAnalyzerAction> CompilationStartActions { get { return _compilationStartActions; } } internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationEndActions { get { return _compilationEndActions; } } internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationActions { get { return _compilationActions; } } internal readonly ImmutableArray<SyntaxTreeAnalyzerAction> SyntaxTreeActions { get { return _syntaxTreeActions; } } internal readonly ImmutableArray<AdditionalFileAnalyzerAction> AdditionalFileActions { get { return _additionalFileActions; } } internal readonly ImmutableArray<SemanticModelAnalyzerAction> SemanticModelActions { get { return _semanticModelActions; } } internal readonly ImmutableArray<SymbolAnalyzerAction> SymbolActions { get { return _symbolActions; } } internal readonly ImmutableArray<SymbolStartAnalyzerAction> SymbolStartActions { get { return _symbolStartActions; } } internal readonly ImmutableArray<SymbolEndAnalyzerAction> SymbolEndActions { get { return _symbolEndActions; } } internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockActions { get { return _codeBlockActions; } } internal readonly ImmutableArray<CodeBlockStartAnalyzerAction<TLanguageKindEnum>> GetCodeBlockStartActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _codeBlockStartActions.OfType<CodeBlockStartAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _syntaxNodeActions.OfType<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>(DiagnosticAnalyzer analyzer) where TLanguageKindEnum : struct { var builder = ArrayBuilder<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.GetInstance(); foreach (var action in _syntaxNodeActions) { if (action.Analyzer == analyzer && action is SyntaxNodeAnalyzerAction<TLanguageKindEnum> syntaxNodeAction) { builder.Add(syntaxNodeAction); } } return builder.ToImmutableAndFree(); } internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockActions { get { return _operationBlockActions; } } internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions { get { return _operationBlockEndActions; } } internal readonly ImmutableArray<OperationBlockStartAnalyzerAction> OperationBlockStartActions { get { return _operationBlockStartActions; } } internal readonly ImmutableArray<OperationAnalyzerAction> OperationActions { get { return _operationActions; } } internal void AddCompilationStartAction(CompilationStartAnalyzerAction action) { _compilationStartActions = _compilationStartActions.Add(action); IsEmpty = false; } internal void AddCompilationEndAction(CompilationAnalyzerAction action) { _compilationEndActions = _compilationEndActions.Add(action); IsEmpty = false; } internal void AddCompilationAction(CompilationAnalyzerAction action) { _compilationActions = _compilationActions.Add(action); IsEmpty = false; } internal void AddSyntaxTreeAction(SyntaxTreeAnalyzerAction action) { _syntaxTreeActions = _syntaxTreeActions.Add(action); IsEmpty = false; } internal void AddAdditionalFileAction(AdditionalFileAnalyzerAction action) { _additionalFileActions = _additionalFileActions.Add(action); IsEmpty = false; } internal void AddSemanticModelAction(SemanticModelAnalyzerAction action) { _semanticModelActions = _semanticModelActions.Add(action); IsEmpty = false; } internal void AddSymbolAction(SymbolAnalyzerAction action) { _symbolActions = _symbolActions.Add(action); IsEmpty = false; } internal void AddSymbolStartAction(SymbolStartAnalyzerAction action) { _symbolStartActions = _symbolStartActions.Add(action); IsEmpty = false; } internal void AddSymbolEndAction(SymbolEndAnalyzerAction action) { _symbolEndActions = _symbolEndActions.Add(action); IsEmpty = false; } internal void AddCodeBlockStartAction<TLanguageKindEnum>(CodeBlockStartAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _codeBlockStartActions = _codeBlockStartActions.Add(action); IsEmpty = false; } internal void AddCodeBlockEndAction(CodeBlockAnalyzerAction action) { _codeBlockEndActions = _codeBlockEndActions.Add(action); IsEmpty = false; } internal void AddCodeBlockAction(CodeBlockAnalyzerAction action) { _codeBlockActions = _codeBlockActions.Add(action); IsEmpty = false; } internal void AddSyntaxNodeAction<TLanguageKindEnum>(SyntaxNodeAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _syntaxNodeActions = _syntaxNodeActions.Add(action); IsEmpty = false; } internal void AddOperationBlockStartAction(OperationBlockStartAnalyzerAction action) { _operationBlockStartActions = _operationBlockStartActions.Add(action); IsEmpty = false; } internal void AddOperationBlockAction(OperationBlockAnalyzerAction action) { _operationBlockActions = _operationBlockActions.Add(action); IsEmpty = false; } internal void AddOperationBlockEndAction(OperationBlockAnalyzerAction action) { _operationBlockEndActions = _operationBlockEndActions.Add(action); IsEmpty = false; } internal void AddOperationAction(OperationAnalyzerAction action) { _operationActions = _operationActions.Add(action); IsEmpty = false; } internal void EnableConcurrentExecution() { _concurrent = true; } /// <summary> /// Append analyzer actions from <paramref name="otherActions"/> to actions from this instance. /// </summary> /// <param name="otherActions">Analyzer actions to append</param>. public readonly AnalyzerActions Append(in AnalyzerActions otherActions, bool appendSymbolStartAndSymbolEndActions = true) { if (otherActions.IsDefault) { throw new ArgumentNullException(nameof(otherActions)); } AnalyzerActions actions = new AnalyzerActions(concurrent: _concurrent || otherActions.Concurrent); actions._compilationStartActions = _compilationStartActions.AddRange(otherActions._compilationStartActions); actions._compilationEndActions = _compilationEndActions.AddRange(otherActions._compilationEndActions); actions._compilationActions = _compilationActions.AddRange(otherActions._compilationActions); actions._syntaxTreeActions = _syntaxTreeActions.AddRange(otherActions._syntaxTreeActions); actions._additionalFileActions = _additionalFileActions.AddRange(otherActions._additionalFileActions); actions._semanticModelActions = _semanticModelActions.AddRange(otherActions._semanticModelActions); actions._symbolActions = _symbolActions.AddRange(otherActions._symbolActions); actions._symbolStartActions = appendSymbolStartAndSymbolEndActions ? _symbolStartActions.AddRange(otherActions._symbolStartActions) : _symbolStartActions; actions._symbolEndActions = appendSymbolStartAndSymbolEndActions ? _symbolEndActions.AddRange(otherActions._symbolEndActions) : _symbolEndActions; actions._codeBlockStartActions = _codeBlockStartActions.AddRange(otherActions._codeBlockStartActions); actions._codeBlockEndActions = _codeBlockEndActions.AddRange(otherActions._codeBlockEndActions); actions._codeBlockActions = _codeBlockActions.AddRange(otherActions._codeBlockActions); actions._syntaxNodeActions = _syntaxNodeActions.AddRange(otherActions._syntaxNodeActions); actions._operationActions = _operationActions.AddRange(otherActions._operationActions); actions._operationBlockStartActions = _operationBlockStartActions.AddRange(otherActions._operationBlockStartActions); actions._operationBlockEndActions = _operationBlockEndActions.AddRange(otherActions._operationBlockEndActions); actions._operationBlockActions = _operationBlockActions.AddRange(otherActions._operationBlockActions); actions.IsEmpty = IsEmpty && otherActions.IsEmpty; return actions; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/FormattingContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { /// <summary> /// this class maintain contextual information such as /// indentation of current position, based token to follow in current position and etc. /// </summary> internal partial class FormattingContext { private readonly AbstractFormatEngine _engine; private readonly TokenStream _tokenStream; // interval tree for inseparable regions (Span to indentation data) // due to dependencies, each region defined in the data can't be formatted independently. private readonly ContextIntervalTree<RelativeIndentationData, FormattingContextIntervalIntrospector> _relativeIndentationTree; // interval tree for each operations. // given a span in the tree, it returns data (indentation, anchor delta, etc) to be applied for the span private readonly ContextIntervalTree<IndentationData, FormattingContextIntervalIntrospector> _indentationTree; private readonly ContextIntervalTree<SuppressWrappingData, SuppressIntervalIntrospector> _suppressWrappingTree; private readonly ContextIntervalTree<SuppressSpacingData, SuppressIntervalIntrospector> _suppressSpacingTree; private readonly ContextIntervalTree<SuppressSpacingData, SuppressIntervalIntrospector> _suppressFormattingTree; private readonly ContextIntervalTree<AnchorData, FormattingContextIntervalIntrospector> _anchorTree; // anchor token to anchor data map. // unlike anchorTree that would return anchor data for given span in the tree, it will return // anchorData based on key which is anchor token. private readonly SegmentedDictionary<SyntaxToken, AnchorData> _anchorBaseTokenMap; // hashset to prevent duplicate entries in the trees. private readonly HashSet<TextSpan> _indentationMap; private readonly HashSet<TextSpan> _suppressWrappingMap; private readonly HashSet<TextSpan> _suppressSpacingMap; private readonly HashSet<TextSpan> _suppressFormattingMap; private readonly HashSet<TextSpan> _anchorMap; // used for selection based formatting case. it contains operations that will define // what indentation to use as a starting indentation. (we always use 0 for formatting whole tree case) private List<IndentBlockOperation> _initialIndentBlockOperations; public FormattingContext(AbstractFormatEngine engine, TokenStream tokenStream) { Contract.ThrowIfNull(engine); Contract.ThrowIfNull(tokenStream); _engine = engine; _tokenStream = tokenStream; _relativeIndentationTree = new ContextIntervalTree<RelativeIndentationData, FormattingContextIntervalIntrospector>(new FormattingContextIntervalIntrospector()); _indentationTree = new ContextIntervalTree<IndentationData, FormattingContextIntervalIntrospector>(new FormattingContextIntervalIntrospector()); _suppressWrappingTree = new ContextIntervalTree<SuppressWrappingData, SuppressIntervalIntrospector>(new SuppressIntervalIntrospector()); _suppressSpacingTree = new ContextIntervalTree<SuppressSpacingData, SuppressIntervalIntrospector>(new SuppressIntervalIntrospector()); _suppressFormattingTree = new ContextIntervalTree<SuppressSpacingData, SuppressIntervalIntrospector>(new SuppressIntervalIntrospector()); _anchorTree = new ContextIntervalTree<AnchorData, FormattingContextIntervalIntrospector>(new FormattingContextIntervalIntrospector()); _anchorBaseTokenMap = new SegmentedDictionary<SyntaxToken, AnchorData>(); _indentationMap = new HashSet<TextSpan>(); _suppressWrappingMap = new HashSet<TextSpan>(); _suppressSpacingMap = new HashSet<TextSpan>(); _suppressFormattingMap = new HashSet<TextSpan>(); _anchorMap = new HashSet<TextSpan>(); _initialIndentBlockOperations = new List<IndentBlockOperation>(); } public void Initialize( ChainedFormattingRules formattingRules, SyntaxToken startToken, SyntaxToken endToken, CancellationToken cancellationToken) { var rootNode = this.TreeData.Root; if (_tokenStream.IsFormattingWholeDocument) { // if we are trying to format whole document, there is no reason to get initial context. just set // initial indentation. var data = new RootIndentationData(rootNode); _indentationTree.AddIntervalInPlace(data); _indentationMap.Add(data.TextSpan); return; } var initialContextFinder = new InitialContextFinder(_tokenStream, formattingRules, rootNode); var (indentOperations, suppressOperations) = initialContextFinder.Do(startToken, endToken); if (indentOperations != null) { var indentationOperations = indentOperations; var initialOperation = indentationOperations[0]; var baseIndentationFinder = new BottomUpBaseIndentationFinder( formattingRules, this.Options.GetOption(FormattingOptions2.TabSize), this.Options.GetOption(FormattingOptions2.IndentationSize), _tokenStream, _engine.SyntaxFacts); var initialIndentation = baseIndentationFinder.GetIndentationOfCurrentPosition( rootNode, initialOperation, t => _tokenStream.GetCurrentColumn(t), cancellationToken); var data = new SimpleIndentationData(initialOperation.TextSpan, initialIndentation); _indentationTree.AddIntervalInPlace(data); _indentationMap.Add(data.TextSpan); // hold onto initial operations _initialIndentBlockOperations = indentationOperations; } suppressOperations?.Do(o => this.AddInitialSuppressOperation(o)); } public void AddIndentBlockOperations( List<IndentBlockOperation> operations, CancellationToken cancellationToken) { Contract.ThrowIfNull(operations); // if there is no initial block operations if (_initialIndentBlockOperations.Count <= 0) { // sort operations and add them to interval tree operations.Sort(CommonFormattingHelpers.IndentBlockOperationComparer); operations.Do(o => { cancellationToken.ThrowIfCancellationRequested(); this.AddIndentBlockOperation(o); }); return; } var baseSpan = _initialIndentBlockOperations[0].TextSpan; // indentation tree must build up from inputs that are in right order except initial indentation. // merge indentation operations from two places (initial operations for current selection, and nodes inside of selections) // sort it in right order and apply them to tree var count = _initialIndentBlockOperations.Count - 1 + operations.Count; var mergedList = new List<IndentBlockOperation>(count); // initial operations are already sorted, just add, no need to filter for (var i = 1; i < _initialIndentBlockOperations.Count; i++) { mergedList.Add(_initialIndentBlockOperations[i]); } for (var i = 0; i < operations.Count; i++) { cancellationToken.ThrowIfCancellationRequested(); // filter out operations whose position is before the base indentation var operationSpan = operations[i].TextSpan; if (operationSpan.Start < baseSpan.Start || operationSpan.Contains(baseSpan)) { continue; } mergedList.Add(operations[i]); } mergedList.Sort(CommonFormattingHelpers.IndentBlockOperationComparer); mergedList.Do(o => { cancellationToken.ThrowIfCancellationRequested(); this.AddIndentBlockOperation(o); }); } public void AddIndentBlockOperation(IndentBlockOperation operation) { var intervalTreeSpan = operation.TextSpan; // don't add stuff if it is empty if (intervalTreeSpan.IsEmpty || _indentationMap.Contains(intervalTreeSpan)) { return; } // relative indentation case where indentation depends on other token if (operation.IsRelativeIndentation) { var effectiveBaseToken = operation.Option.IsOn(IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine) ? _tokenStream.FirstTokenOfBaseTokenLine(operation.BaseToken) : operation.BaseToken; var inseparableRegionStartingPosition = effectiveBaseToken.FullSpan.Start; var relativeIndentationGetter = new Lazy<int>(() => { var baseIndentationDelta = operation.GetAdjustedIndentationDelta(_engine.SyntaxFacts, TreeData.Root, effectiveBaseToken); var indentationDelta = baseIndentationDelta * this.Options.GetOption(FormattingOptions2.IndentationSize); // baseIndentation is calculated for the adjusted token if option is RelativeToFirstTokenOnBaseTokenLine var baseIndentation = _tokenStream.GetCurrentColumn(operation.Option.IsOn(IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine) ? _tokenStream.FirstTokenOfBaseTokenLine(operation.BaseToken) : operation.BaseToken); return baseIndentation + indentationDelta; }, isThreadSafe: true); // set new indentation var relativeIndentationData = new RelativeIndentationData(inseparableRegionStartingPosition, intervalTreeSpan, operation, relativeIndentationGetter); _indentationTree.AddIntervalInPlace(relativeIndentationData); _relativeIndentationTree.AddIntervalInPlace(relativeIndentationData); _indentationMap.Add(intervalTreeSpan); return; } // absolute position case if (operation.Option.IsOn(IndentBlockOption.AbsolutePosition)) { _indentationTree.AddIntervalInPlace(new SimpleIndentationData(intervalTreeSpan, operation.IndentationDeltaOrPosition)); _indentationMap.Add(intervalTreeSpan); return; } // regular indentation case where indentation is based on its previous indentation var indentationData = _indentationTree.GetSmallestContainingInterval(operation.TextSpan.Start, 0); if (indentationData == null) { // no previous indentation var indentation = operation.IndentationDeltaOrPosition * this.Options.GetOption(FormattingOptions2.IndentationSize); _indentationTree.AddIntervalInPlace(new SimpleIndentationData(intervalTreeSpan, indentation)); _indentationMap.Add(intervalTreeSpan); return; } // get indentation based on its previous indentation var indentationGetter = new Lazy<int>(() => { var indentationDelta = operation.IndentationDeltaOrPosition * this.Options.GetOption(FormattingOptions2.IndentationSize); return indentationData.Indentation + indentationDelta; }, isThreadSafe: true); // set new indentation _indentationTree.AddIntervalInPlace(new LazyIndentationData(intervalTreeSpan, indentationGetter)); _indentationMap.Add(intervalTreeSpan); } public void AddInitialSuppressOperation(SuppressOperation operation) { // don't add stuff if it is empty if (operation == null || operation.TextSpan.IsEmpty) { return; } var onSameLine = _tokenStream.TwoTokensOriginallyOnSameLine(operation.StartToken, operation.EndToken); AddSuppressOperation(operation, onSameLine); } public void AddSuppressOperations( List<SuppressOperation> operations, CancellationToken cancellationToken) { var valuePairs = new SegmentedArray<(SuppressOperation operation, bool shouldSuppress, bool onSameLine)>(operations.Count); // TODO: think about a way to figure out whether it is already suppressed and skip the expensive check below. for (var i = 0; i < operations.Count; i++) { cancellationToken.ThrowIfCancellationRequested(); var operation = operations[i]; // if an operation contains elastic trivia itself and the operation is not marked to ignore the elastic trivia // ignore the operation if (operation.ContainsElasticTrivia(_tokenStream) && !operation.Option.IsOn(SuppressOption.IgnoreElasticWrapping)) { // don't bother to calculate line alignment between tokens valuePairs[i] = (operation, shouldSuppress: false, onSameLine: false); continue; } var onSameLine = _tokenStream.TwoTokensOriginallyOnSameLine(operation.StartToken, operation.EndToken); valuePairs[i] = (operation, shouldSuppress: true, onSameLine); } foreach (var (operation, shouldSuppress, onSameLine) in valuePairs) { cancellationToken.ThrowIfCancellationRequested(); if (shouldSuppress) { AddSuppressOperation(operation, onSameLine); } } } private void AddSuppressOperation(SuppressOperation operation, bool onSameLine) { AddSpacingSuppressOperation(operation, onSameLine); AddFormattingSuppressOperation(operation); AddWrappingSuppressOperation(operation, onSameLine); } private void AddSpacingSuppressOperation(SuppressOperation operation, bool twoTokensOnSameLine) { // don't add stuff if it is empty if (operation == null || operation.TextSpan.IsEmpty) { return; } // we might need to merge bits with enclosing suppress flag var option = operation.Option; if (!option.IsMaskOn(SuppressOption.NoSpacing) || _suppressSpacingMap.Contains(operation.TextSpan)) { return; } if (!(option.IsOn(SuppressOption.NoSpacingIfOnSingleLine) && twoTokensOnSameLine) && !(option.IsOn(SuppressOption.NoSpacingIfOnMultipleLine) && !twoTokensOnSameLine)) { return; } var data = new SuppressSpacingData(operation.TextSpan); _suppressSpacingMap.Add(operation.TextSpan); _suppressSpacingTree.AddIntervalInPlace(data); } private void AddFormattingSuppressOperation(SuppressOperation operation) { // don't add stuff if it is empty if (operation == null || operation.TextSpan.IsEmpty) { return; } // we might need to merge bits with enclosing suppress flag var option = operation.Option; if (!option.IsOn(SuppressOption.DisableFormatting) || _suppressFormattingMap.Contains(operation.TextSpan)) { return; } var data = new SuppressSpacingData(operation.TextSpan); _suppressFormattingMap.Add(operation.TextSpan); _suppressFormattingTree.AddIntervalInPlace(data); } private void AddWrappingSuppressOperation(SuppressOperation operation, bool twoTokensOnSameLine) { // don't add stuff if it is empty if (operation == null || operation.TextSpan.IsEmpty) { return; } var option = operation.Option; if (!option.IsMaskOn(SuppressOption.NoWrapping) || _suppressWrappingMap.Contains(operation.TextSpan)) { return; } if (!(option.IsOn(SuppressOption.NoWrappingIfOnSingleLine) && twoTokensOnSameLine) && !(option.IsOn(SuppressOption.NoWrappingIfOnMultipleLine) && !twoTokensOnSameLine)) { return; } var ignoreElastic = option.IsMaskOn(SuppressOption.IgnoreElasticWrapping) || !operation.ContainsElasticTrivia(_tokenStream); var data = new SuppressWrappingData(operation.TextSpan, ignoreElastic: ignoreElastic); _suppressWrappingMap.Add(operation.TextSpan); _suppressWrappingTree.AddIntervalInPlace(data); } public void AddAnchorIndentationOperation(AnchorIndentationOperation operation) { // don't add stuff if it is empty if (operation.TextSpan.IsEmpty || _anchorMap.Contains(operation.TextSpan) || _anchorBaseTokenMap.ContainsKey(operation.AnchorToken)) { return; } var originalSpace = _tokenStream.GetOriginalColumn(operation.StartToken); var data = new AnchorData(operation, originalSpace); _anchorTree.AddIntervalInPlace(data); _anchorBaseTokenMap.Add(operation.AnchorToken, data); _anchorMap.Add(operation.TextSpan); } [Conditional("DEBUG")] private static void DebugCheckEmpty<T, TIntrospector>(ContextIntervalTree<T, TIntrospector> tree, TextSpan textSpan) where TIntrospector : struct, IIntervalIntrospector<T> { var intervals = tree.GetIntervalsThatContain(textSpan.Start, textSpan.Length); Contract.ThrowIfFalse(intervals.Length == 0); } public int GetBaseIndentation(SyntaxToken token) => GetBaseIndentation(token.SpanStart); public int GetBaseIndentation(int position) { var indentationData = _indentationTree.GetSmallestContainingInterval(position, 0); if (indentationData == null) { DebugCheckEmpty(_indentationTree, new TextSpan(position, 0)); return 0; } return indentationData.Indentation; } public IEnumerable<IndentBlockOperation> GetAllRelativeIndentBlockOperations() => _relativeIndentationTree.GetIntervalsThatIntersectWith(this.TreeData.StartPosition, this.TreeData.EndPosition, new FormattingContextIntervalIntrospector()).Select(i => i.Operation); public bool TryGetEndTokenForRelativeIndentationSpan(SyntaxToken token, int maxChainDepth, out SyntaxToken endToken, CancellationToken cancellationToken) { endToken = default; var depth = 0; while (true) { cancellationToken.ThrowIfCancellationRequested(); if (depth++ > maxChainDepth) { return false; } var span = token.Span; var indentationData = _relativeIndentationTree.GetSmallestContainingInterval(span.Start, 0); if (indentationData == null) { // this means the given token is not inside of inseparable regions endToken = token; return true; } // recursively find the end token outside of inseparable regions token = indentationData.EndToken.GetNextToken(includeZeroWidth: true); if (token.RawKind == 0) { // reached end of tree return true; } } } private AnchorData? GetAnchorData(SyntaxToken token) { var span = token.Span; var anchorData = _anchorTree.GetSmallestContainingInterval(span.Start, 0); if (anchorData == null) { // no anchor DebugCheckEmpty(_anchorTree, new TextSpan(span.Start, 0)); return null; } return anchorData; } public int GetAnchorDeltaFromOriginalColumn(SyntaxToken token) { var anchorData = GetAnchorData(token); if (anchorData == null) { return 0; } var currentColumn = _tokenStream.GetCurrentColumn(anchorData.AnchorToken); return currentColumn - anchorData.OriginalColumn; } public SyntaxToken GetAnchorToken(SyntaxToken token) { var anchorData = GetAnchorData(token); if (anchorData == null) { return default; } return anchorData.AnchorToken; } public int GetDeltaFromPreviousChangesMap(SyntaxToken token, Dictionary<SyntaxToken, int> previousChangesMap) { // no changes if (!previousChangesMap.ContainsKey(token)) { return 0; } var currentColumn = _tokenStream.GetCurrentColumn(token); return currentColumn - previousChangesMap[token]; } public SyntaxToken GetEndTokenForAnchorSpan(TokenData tokenData) { // consider situation like below // // var q = from c in cs // where c > 1 // + // 2; // // if alignment operation moves "where" to align with "from" // we want to move "+" and "2" along with it (anchor operation) // // below we are trying to figure out up to which token ("2" in the above example) // we should apply the anchor operation var baseAnchorData = FindAnchorSpanOnSameLineAfterToken(tokenData); if (baseAnchorData == null) { return default; } // our anchor operation is very flexible so it not only let one anchor to contain others, it also // let anchors to overlap each other for whatever reasons // below, we will try to flat the overlapped anchor span, and find the last position (token) of that span // find other anchors overlapping with current anchor span var anchorData = _anchorTree.GetIntervalsThatOverlapWith(baseAnchorData.TextSpan.Start, baseAnchorData.TextSpan.Length); // among those anchors find the biggest end token var lastEndToken = baseAnchorData.EndToken; foreach (var interval in anchorData) { // anchor token is not in scope, move to next if (!baseAnchorData.TextSpan.IntersectsWith(interval.AnchorToken.Span)) { continue; } if (interval.EndToken.Span.End < lastEndToken.Span.End) { continue; } lastEndToken = interval.EndToken; } return lastEndToken; } private AnchorData? FindAnchorSpanOnSameLineAfterToken(TokenData tokenData) { // every token after given token on same line is implicitly dependent to the token. // check whether one of them is an anchor token. AnchorData? lastBaseAnchorData = null; while (tokenData.IndexInStream >= 0) { if (_anchorBaseTokenMap.TryGetValue(tokenData.Token, out var tempAnchorData)) { lastBaseAnchorData = tempAnchorData; } // tokenPairIndex is always 0 <= ... < TokenCount - 1 var tokenPairIndex = tokenData.IndexInStream; if (_tokenStream.TokenCount - 1 <= tokenPairIndex || _tokenStream.GetTriviaData(tokenPairIndex).SecondTokenIsFirstTokenOnLine) { return lastBaseAnchorData; } tokenData = tokenData.GetNextTokenData(); } return lastBaseAnchorData; } public bool IsWrappingSuppressed(TextSpan textSpan, bool containsElasticTrivia) { if (IsFormattingDisabled(textSpan)) { return true; } // use edge exclusive version of GetSmallestContainingInterval var data = _suppressWrappingTree.GetSmallestEdgeExclusivelyContainingInterval(textSpan.Start, textSpan.Length); if (data == null) { return false; } if (containsElasticTrivia && !data.IgnoreElastic) { return false; } return true; } public bool IsSpacingSuppressed(TextSpan textSpan, bool containsElasticTrivia) { if (IsFormattingDisabled(textSpan)) { return true; } // For spaces, never ignore elastic trivia because that can // generate incorrect code if (containsElasticTrivia) { return false; } // use edge exclusive version of GetSmallestContainingInterval var data = _suppressSpacingTree.GetSmallestEdgeExclusivelyContainingInterval(textSpan.Start, textSpan.Length); if (data == null) { return false; } return true; } public bool IsSpacingSuppressed(int pairIndex) { var token1 = _tokenStream.GetToken(pairIndex); var token2 = _tokenStream.GetToken(pairIndex + 1); var spanBetweenTwoTokens = TextSpan.FromBounds(token1.SpanStart, token2.Span.End); // this version of SpacingSuppressed will be called after all basic space operations are done. // so no more elastic trivia should have left out return IsSpacingSuppressed(spanBetweenTwoTokens, containsElasticTrivia: false); } public bool IsFormattingDisabled(TextSpan textSpan) => _suppressFormattingTree.HasIntervalThatIntersectsWith(textSpan.Start, textSpan.Length); public bool IsFormattingDisabled(int pairIndex) { var token1 = _tokenStream.GetToken(pairIndex); var token2 = _tokenStream.GetToken(pairIndex + 1); var spanBetweenTwoTokens = TextSpan.FromBounds(token1.SpanStart, token2.Span.End); return IsFormattingDisabled(spanBetweenTwoTokens); } public AnalyzerConfigOptions Options => _engine.Options; public TreeData TreeData => _engine.TreeData; public TokenStream TokenStream => _tokenStream; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { /// <summary> /// this class maintain contextual information such as /// indentation of current position, based token to follow in current position and etc. /// </summary> internal partial class FormattingContext { private readonly AbstractFormatEngine _engine; private readonly TokenStream _tokenStream; // interval tree for inseparable regions (Span to indentation data) // due to dependencies, each region defined in the data can't be formatted independently. private readonly ContextIntervalTree<RelativeIndentationData, FormattingContextIntervalIntrospector> _relativeIndentationTree; // interval tree for each operations. // given a span in the tree, it returns data (indentation, anchor delta, etc) to be applied for the span private readonly ContextIntervalTree<IndentationData, FormattingContextIntervalIntrospector> _indentationTree; private readonly ContextIntervalTree<SuppressWrappingData, SuppressIntervalIntrospector> _suppressWrappingTree; private readonly ContextIntervalTree<SuppressSpacingData, SuppressIntervalIntrospector> _suppressSpacingTree; private readonly ContextIntervalTree<SuppressSpacingData, SuppressIntervalIntrospector> _suppressFormattingTree; private readonly ContextIntervalTree<AnchorData, FormattingContextIntervalIntrospector> _anchorTree; // anchor token to anchor data map. // unlike anchorTree that would return anchor data for given span in the tree, it will return // anchorData based on key which is anchor token. private readonly SegmentedDictionary<SyntaxToken, AnchorData> _anchorBaseTokenMap; // hashset to prevent duplicate entries in the trees. private readonly HashSet<TextSpan> _indentationMap; private readonly HashSet<TextSpan> _suppressWrappingMap; private readonly HashSet<TextSpan> _suppressSpacingMap; private readonly HashSet<TextSpan> _suppressFormattingMap; private readonly HashSet<TextSpan> _anchorMap; // used for selection based formatting case. it contains operations that will define // what indentation to use as a starting indentation. (we always use 0 for formatting whole tree case) private List<IndentBlockOperation> _initialIndentBlockOperations; public FormattingContext(AbstractFormatEngine engine, TokenStream tokenStream) { Contract.ThrowIfNull(engine); Contract.ThrowIfNull(tokenStream); _engine = engine; _tokenStream = tokenStream; _relativeIndentationTree = new ContextIntervalTree<RelativeIndentationData, FormattingContextIntervalIntrospector>(new FormattingContextIntervalIntrospector()); _indentationTree = new ContextIntervalTree<IndentationData, FormattingContextIntervalIntrospector>(new FormattingContextIntervalIntrospector()); _suppressWrappingTree = new ContextIntervalTree<SuppressWrappingData, SuppressIntervalIntrospector>(new SuppressIntervalIntrospector()); _suppressSpacingTree = new ContextIntervalTree<SuppressSpacingData, SuppressIntervalIntrospector>(new SuppressIntervalIntrospector()); _suppressFormattingTree = new ContextIntervalTree<SuppressSpacingData, SuppressIntervalIntrospector>(new SuppressIntervalIntrospector()); _anchorTree = new ContextIntervalTree<AnchorData, FormattingContextIntervalIntrospector>(new FormattingContextIntervalIntrospector()); _anchorBaseTokenMap = new SegmentedDictionary<SyntaxToken, AnchorData>(); _indentationMap = new HashSet<TextSpan>(); _suppressWrappingMap = new HashSet<TextSpan>(); _suppressSpacingMap = new HashSet<TextSpan>(); _suppressFormattingMap = new HashSet<TextSpan>(); _anchorMap = new HashSet<TextSpan>(); _initialIndentBlockOperations = new List<IndentBlockOperation>(); } public void Initialize( ChainedFormattingRules formattingRules, SyntaxToken startToken, SyntaxToken endToken, CancellationToken cancellationToken) { var rootNode = this.TreeData.Root; if (_tokenStream.IsFormattingWholeDocument) { // if we are trying to format whole document, there is no reason to get initial context. just set // initial indentation. var data = new RootIndentationData(rootNode); _indentationTree.AddIntervalInPlace(data); _indentationMap.Add(data.TextSpan); return; } var initialContextFinder = new InitialContextFinder(_tokenStream, formattingRules, rootNode); var (indentOperations, suppressOperations) = initialContextFinder.Do(startToken, endToken); if (indentOperations != null) { var indentationOperations = indentOperations; var initialOperation = indentationOperations[0]; var baseIndentationFinder = new BottomUpBaseIndentationFinder( formattingRules, this.Options.GetOption(FormattingOptions2.TabSize), this.Options.GetOption(FormattingOptions2.IndentationSize), _tokenStream, _engine.SyntaxFacts); var initialIndentation = baseIndentationFinder.GetIndentationOfCurrentPosition( rootNode, initialOperation, t => _tokenStream.GetCurrentColumn(t), cancellationToken); var data = new SimpleIndentationData(initialOperation.TextSpan, initialIndentation); _indentationTree.AddIntervalInPlace(data); _indentationMap.Add(data.TextSpan); // hold onto initial operations _initialIndentBlockOperations = indentationOperations; } suppressOperations?.Do(o => this.AddInitialSuppressOperation(o)); } public void AddIndentBlockOperations( List<IndentBlockOperation> operations, CancellationToken cancellationToken) { Contract.ThrowIfNull(operations); // if there is no initial block operations if (_initialIndentBlockOperations.Count <= 0) { // sort operations and add them to interval tree operations.Sort(CommonFormattingHelpers.IndentBlockOperationComparer); operations.Do(o => { cancellationToken.ThrowIfCancellationRequested(); this.AddIndentBlockOperation(o); }); return; } var baseSpan = _initialIndentBlockOperations[0].TextSpan; // indentation tree must build up from inputs that are in right order except initial indentation. // merge indentation operations from two places (initial operations for current selection, and nodes inside of selections) // sort it in right order and apply them to tree var count = _initialIndentBlockOperations.Count - 1 + operations.Count; var mergedList = new List<IndentBlockOperation>(count); // initial operations are already sorted, just add, no need to filter for (var i = 1; i < _initialIndentBlockOperations.Count; i++) { mergedList.Add(_initialIndentBlockOperations[i]); } for (var i = 0; i < operations.Count; i++) { cancellationToken.ThrowIfCancellationRequested(); // filter out operations whose position is before the base indentation var operationSpan = operations[i].TextSpan; if (operationSpan.Start < baseSpan.Start || operationSpan.Contains(baseSpan)) { continue; } mergedList.Add(operations[i]); } mergedList.Sort(CommonFormattingHelpers.IndentBlockOperationComparer); mergedList.Do(o => { cancellationToken.ThrowIfCancellationRequested(); this.AddIndentBlockOperation(o); }); } public void AddIndentBlockOperation(IndentBlockOperation operation) { var intervalTreeSpan = operation.TextSpan; // don't add stuff if it is empty if (intervalTreeSpan.IsEmpty || _indentationMap.Contains(intervalTreeSpan)) { return; } // relative indentation case where indentation depends on other token if (operation.IsRelativeIndentation) { var effectiveBaseToken = operation.Option.IsOn(IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine) ? _tokenStream.FirstTokenOfBaseTokenLine(operation.BaseToken) : operation.BaseToken; var inseparableRegionStartingPosition = effectiveBaseToken.FullSpan.Start; var relativeIndentationGetter = new Lazy<int>(() => { var baseIndentationDelta = operation.GetAdjustedIndentationDelta(_engine.SyntaxFacts, TreeData.Root, effectiveBaseToken); var indentationDelta = baseIndentationDelta * this.Options.GetOption(FormattingOptions2.IndentationSize); // baseIndentation is calculated for the adjusted token if option is RelativeToFirstTokenOnBaseTokenLine var baseIndentation = _tokenStream.GetCurrentColumn(operation.Option.IsOn(IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine) ? _tokenStream.FirstTokenOfBaseTokenLine(operation.BaseToken) : operation.BaseToken); return baseIndentation + indentationDelta; }, isThreadSafe: true); // set new indentation var relativeIndentationData = new RelativeIndentationData(inseparableRegionStartingPosition, intervalTreeSpan, operation, relativeIndentationGetter); _indentationTree.AddIntervalInPlace(relativeIndentationData); _relativeIndentationTree.AddIntervalInPlace(relativeIndentationData); _indentationMap.Add(intervalTreeSpan); return; } // absolute position case if (operation.Option.IsOn(IndentBlockOption.AbsolutePosition)) { _indentationTree.AddIntervalInPlace(new SimpleIndentationData(intervalTreeSpan, operation.IndentationDeltaOrPosition)); _indentationMap.Add(intervalTreeSpan); return; } // regular indentation case where indentation is based on its previous indentation var indentationData = _indentationTree.GetSmallestContainingInterval(operation.TextSpan.Start, 0); if (indentationData == null) { // no previous indentation var indentation = operation.IndentationDeltaOrPosition * this.Options.GetOption(FormattingOptions2.IndentationSize); _indentationTree.AddIntervalInPlace(new SimpleIndentationData(intervalTreeSpan, indentation)); _indentationMap.Add(intervalTreeSpan); return; } // get indentation based on its previous indentation var indentationGetter = new Lazy<int>(() => { var indentationDelta = operation.IndentationDeltaOrPosition * this.Options.GetOption(FormattingOptions2.IndentationSize); return indentationData.Indentation + indentationDelta; }, isThreadSafe: true); // set new indentation _indentationTree.AddIntervalInPlace(new LazyIndentationData(intervalTreeSpan, indentationGetter)); _indentationMap.Add(intervalTreeSpan); } public void AddInitialSuppressOperation(SuppressOperation operation) { // don't add stuff if it is empty if (operation == null || operation.TextSpan.IsEmpty) { return; } var onSameLine = _tokenStream.TwoTokensOriginallyOnSameLine(operation.StartToken, operation.EndToken); AddSuppressOperation(operation, onSameLine); } public void AddSuppressOperations( List<SuppressOperation> operations, CancellationToken cancellationToken) { var valuePairs = new SegmentedArray<(SuppressOperation operation, bool shouldSuppress, bool onSameLine)>(operations.Count); // TODO: think about a way to figure out whether it is already suppressed and skip the expensive check below. for (var i = 0; i < operations.Count; i++) { cancellationToken.ThrowIfCancellationRequested(); var operation = operations[i]; // if an operation contains elastic trivia itself and the operation is not marked to ignore the elastic trivia // ignore the operation if (operation.ContainsElasticTrivia(_tokenStream) && !operation.Option.IsOn(SuppressOption.IgnoreElasticWrapping)) { // don't bother to calculate line alignment between tokens valuePairs[i] = (operation, shouldSuppress: false, onSameLine: false); continue; } var onSameLine = _tokenStream.TwoTokensOriginallyOnSameLine(operation.StartToken, operation.EndToken); valuePairs[i] = (operation, shouldSuppress: true, onSameLine); } foreach (var (operation, shouldSuppress, onSameLine) in valuePairs) { cancellationToken.ThrowIfCancellationRequested(); if (shouldSuppress) { AddSuppressOperation(operation, onSameLine); } } } private void AddSuppressOperation(SuppressOperation operation, bool onSameLine) { AddSpacingSuppressOperation(operation, onSameLine); AddFormattingSuppressOperation(operation); AddWrappingSuppressOperation(operation, onSameLine); } private void AddSpacingSuppressOperation(SuppressOperation operation, bool twoTokensOnSameLine) { // don't add stuff if it is empty if (operation == null || operation.TextSpan.IsEmpty) { return; } // we might need to merge bits with enclosing suppress flag var option = operation.Option; if (!option.IsMaskOn(SuppressOption.NoSpacing) || _suppressSpacingMap.Contains(operation.TextSpan)) { return; } if (!(option.IsOn(SuppressOption.NoSpacingIfOnSingleLine) && twoTokensOnSameLine) && !(option.IsOn(SuppressOption.NoSpacingIfOnMultipleLine) && !twoTokensOnSameLine)) { return; } var data = new SuppressSpacingData(operation.TextSpan); _suppressSpacingMap.Add(operation.TextSpan); _suppressSpacingTree.AddIntervalInPlace(data); } private void AddFormattingSuppressOperation(SuppressOperation operation) { // don't add stuff if it is empty if (operation == null || operation.TextSpan.IsEmpty) { return; } // we might need to merge bits with enclosing suppress flag var option = operation.Option; if (!option.IsOn(SuppressOption.DisableFormatting) || _suppressFormattingMap.Contains(operation.TextSpan)) { return; } var data = new SuppressSpacingData(operation.TextSpan); _suppressFormattingMap.Add(operation.TextSpan); _suppressFormattingTree.AddIntervalInPlace(data); } private void AddWrappingSuppressOperation(SuppressOperation operation, bool twoTokensOnSameLine) { // don't add stuff if it is empty if (operation == null || operation.TextSpan.IsEmpty) { return; } var option = operation.Option; if (!option.IsMaskOn(SuppressOption.NoWrapping) || _suppressWrappingMap.Contains(operation.TextSpan)) { return; } if (!(option.IsOn(SuppressOption.NoWrappingIfOnSingleLine) && twoTokensOnSameLine) && !(option.IsOn(SuppressOption.NoWrappingIfOnMultipleLine) && !twoTokensOnSameLine)) { return; } var ignoreElastic = option.IsMaskOn(SuppressOption.IgnoreElasticWrapping) || !operation.ContainsElasticTrivia(_tokenStream); var data = new SuppressWrappingData(operation.TextSpan, ignoreElastic: ignoreElastic); _suppressWrappingMap.Add(operation.TextSpan); _suppressWrappingTree.AddIntervalInPlace(data); } public void AddAnchorIndentationOperation(AnchorIndentationOperation operation) { // don't add stuff if it is empty if (operation.TextSpan.IsEmpty || _anchorMap.Contains(operation.TextSpan) || _anchorBaseTokenMap.ContainsKey(operation.AnchorToken)) { return; } var originalSpace = _tokenStream.GetOriginalColumn(operation.StartToken); var data = new AnchorData(operation, originalSpace); _anchorTree.AddIntervalInPlace(data); _anchorBaseTokenMap.Add(operation.AnchorToken, data); _anchorMap.Add(operation.TextSpan); } [Conditional("DEBUG")] private static void DebugCheckEmpty<T, TIntrospector>(ContextIntervalTree<T, TIntrospector> tree, TextSpan textSpan) where TIntrospector : struct, IIntervalIntrospector<T> { var intervals = tree.GetIntervalsThatContain(textSpan.Start, textSpan.Length); Contract.ThrowIfFalse(intervals.Length == 0); } public int GetBaseIndentation(SyntaxToken token) => GetBaseIndentation(token.SpanStart); public int GetBaseIndentation(int position) { var indentationData = _indentationTree.GetSmallestContainingInterval(position, 0); if (indentationData == null) { DebugCheckEmpty(_indentationTree, new TextSpan(position, 0)); return 0; } return indentationData.Indentation; } public IEnumerable<IndentBlockOperation> GetAllRelativeIndentBlockOperations() => _relativeIndentationTree.GetIntervalsThatIntersectWith(this.TreeData.StartPosition, this.TreeData.EndPosition, new FormattingContextIntervalIntrospector()).Select(i => i.Operation); public bool TryGetEndTokenForRelativeIndentationSpan(SyntaxToken token, int maxChainDepth, out SyntaxToken endToken, CancellationToken cancellationToken) { endToken = default; var depth = 0; while (true) { cancellationToken.ThrowIfCancellationRequested(); if (depth++ > maxChainDepth) { return false; } var span = token.Span; var indentationData = _relativeIndentationTree.GetSmallestContainingInterval(span.Start, 0); if (indentationData == null) { // this means the given token is not inside of inseparable regions endToken = token; return true; } // recursively find the end token outside of inseparable regions token = indentationData.EndToken.GetNextToken(includeZeroWidth: true); if (token.RawKind == 0) { // reached end of tree return true; } } } private AnchorData? GetAnchorData(SyntaxToken token) { var span = token.Span; var anchorData = _anchorTree.GetSmallestContainingInterval(span.Start, 0); if (anchorData == null) { // no anchor DebugCheckEmpty(_anchorTree, new TextSpan(span.Start, 0)); return null; } return anchorData; } public int GetAnchorDeltaFromOriginalColumn(SyntaxToken token) { var anchorData = GetAnchorData(token); if (anchorData == null) { return 0; } var currentColumn = _tokenStream.GetCurrentColumn(anchorData.AnchorToken); return currentColumn - anchorData.OriginalColumn; } public SyntaxToken GetAnchorToken(SyntaxToken token) { var anchorData = GetAnchorData(token); if (anchorData == null) { return default; } return anchorData.AnchorToken; } public int GetDeltaFromPreviousChangesMap(SyntaxToken token, Dictionary<SyntaxToken, int> previousChangesMap) { // no changes if (!previousChangesMap.ContainsKey(token)) { return 0; } var currentColumn = _tokenStream.GetCurrentColumn(token); return currentColumn - previousChangesMap[token]; } public SyntaxToken GetEndTokenForAnchorSpan(TokenData tokenData) { // consider situation like below // // var q = from c in cs // where c > 1 // + // 2; // // if alignment operation moves "where" to align with "from" // we want to move "+" and "2" along with it (anchor operation) // // below we are trying to figure out up to which token ("2" in the above example) // we should apply the anchor operation var baseAnchorData = FindAnchorSpanOnSameLineAfterToken(tokenData); if (baseAnchorData == null) { return default; } // our anchor operation is very flexible so it not only let one anchor to contain others, it also // let anchors to overlap each other for whatever reasons // below, we will try to flat the overlapped anchor span, and find the last position (token) of that span // find other anchors overlapping with current anchor span var anchorData = _anchorTree.GetIntervalsThatOverlapWith(baseAnchorData.TextSpan.Start, baseAnchorData.TextSpan.Length); // among those anchors find the biggest end token var lastEndToken = baseAnchorData.EndToken; foreach (var interval in anchorData) { // anchor token is not in scope, move to next if (!baseAnchorData.TextSpan.IntersectsWith(interval.AnchorToken.Span)) { continue; } if (interval.EndToken.Span.End < lastEndToken.Span.End) { continue; } lastEndToken = interval.EndToken; } return lastEndToken; } private AnchorData? FindAnchorSpanOnSameLineAfterToken(TokenData tokenData) { // every token after given token on same line is implicitly dependent to the token. // check whether one of them is an anchor token. AnchorData? lastBaseAnchorData = null; while (tokenData.IndexInStream >= 0) { if (_anchorBaseTokenMap.TryGetValue(tokenData.Token, out var tempAnchorData)) { lastBaseAnchorData = tempAnchorData; } // tokenPairIndex is always 0 <= ... < TokenCount - 1 var tokenPairIndex = tokenData.IndexInStream; if (_tokenStream.TokenCount - 1 <= tokenPairIndex || _tokenStream.GetTriviaData(tokenPairIndex).SecondTokenIsFirstTokenOnLine) { return lastBaseAnchorData; } tokenData = tokenData.GetNextTokenData(); } return lastBaseAnchorData; } public bool IsWrappingSuppressed(TextSpan textSpan, bool containsElasticTrivia) { if (IsFormattingDisabled(textSpan)) { return true; } // use edge exclusive version of GetSmallestContainingInterval var data = _suppressWrappingTree.GetSmallestEdgeExclusivelyContainingInterval(textSpan.Start, textSpan.Length); if (data == null) { return false; } if (containsElasticTrivia && !data.IgnoreElastic) { return false; } return true; } public bool IsSpacingSuppressed(TextSpan textSpan, bool containsElasticTrivia) { if (IsFormattingDisabled(textSpan)) { return true; } // For spaces, never ignore elastic trivia because that can // generate incorrect code if (containsElasticTrivia) { return false; } // use edge exclusive version of GetSmallestContainingInterval var data = _suppressSpacingTree.GetSmallestEdgeExclusivelyContainingInterval(textSpan.Start, textSpan.Length); if (data == null) { return false; } return true; } public bool IsSpacingSuppressed(int pairIndex) { var token1 = _tokenStream.GetToken(pairIndex); var token2 = _tokenStream.GetToken(pairIndex + 1); var spanBetweenTwoTokens = TextSpan.FromBounds(token1.SpanStart, token2.Span.End); // this version of SpacingSuppressed will be called after all basic space operations are done. // so no more elastic trivia should have left out return IsSpacingSuppressed(spanBetweenTwoTokens, containsElasticTrivia: false); } public bool IsFormattingDisabled(TextSpan textSpan) => _suppressFormattingTree.HasIntervalThatIntersectsWith(textSpan.Start, textSpan.Length); public bool IsFormattingDisabled(int pairIndex) { var token1 = _tokenStream.GetToken(pairIndex); var token2 = _tokenStream.GetToken(pairIndex + 1); var spanBetweenTwoTokens = TextSpan.FromBounds(token1.SpanStart, token2.Span.End); return IsFormattingDisabled(spanBetweenTwoTokens); } public AnalyzerConfigOptions Options => _engine.Options; public TreeData TreeData => _engine.TreeData; public TokenStream TokenStream => _tokenStream; } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./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,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Features/Core/Portable/AddPackage/InstallPackageParentCodeAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Tags; namespace Microsoft.CodeAnalysis.AddPackage { /// <summary> /// This is the top level 'Install Nuget Package' code action we show in /// the lightbulb. It will have children to 'Install Latest', /// 'Install Version 'X' ..., and 'Install with package manager'. /// </summary> internal class InstallPackageParentCodeAction : CodeAction.CodeActionWithNestedActions { public override ImmutableArray<string> Tags => WellKnownTagArrays.NuGet; /// <summary> /// Even though we have child actions, we mark ourselves as explicitly non-inlinable. /// We want to the experience of having the top level item the user has to see and /// navigate through, and we don't want our child items confusingly being added to the /// top level light-bulb where it's not clear what effect they would have if invoked. /// </summary> public InstallPackageParentCodeAction( IPackageInstallerService installerService, string source, string packageName, bool includePrerelease, Document document) : base(string.Format(FeaturesResources.Install_package_0, packageName), CreateNestedActions(installerService, source, packageName, includePrerelease, document), isInlinable: false) { } private static ImmutableArray<CodeAction> CreateNestedActions( IPackageInstallerService installerService, string source, string packageName, bool includePrerelease, Document document) { // Determine what versions of this package are already installed in some project // in this solution. We'll offer to add those specific versions to this project, // followed by an option to "Find and install latest version." var installedVersions = installerService.GetInstalledVersions(packageName); var codeActions = ArrayBuilder<CodeAction>.GetInstance(); // First add the actions to install a specific version. codeActions.AddRange(installedVersions.Select(v => CreateCodeAction( installerService, source, packageName, document, versionOpt: v, includePrerelease: includePrerelease, isLocal: true))); // Now add the action to install the specific version. codeActions.Add(CreateCodeAction( installerService, source, packageName, document, versionOpt: null, includePrerelease: includePrerelease, isLocal: false)); // And finally the action to show the package manager dialog. codeActions.Add(new InstallWithPackageManagerCodeAction(installerService, packageName)); return codeActions.ToImmutableAndFree(); } private static CodeAction CreateCodeAction( IPackageInstallerService installerService, string source, string packageName, Document document, string versionOpt, bool includePrerelease, bool isLocal) { return new InstallPackageDirectlyCodeAction( installerService, document, source, packageName, versionOpt, includePrerelease, isLocal); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Tags; namespace Microsoft.CodeAnalysis.AddPackage { /// <summary> /// This is the top level 'Install Nuget Package' code action we show in /// the lightbulb. It will have children to 'Install Latest', /// 'Install Version 'X' ..., and 'Install with package manager'. /// </summary> internal class InstallPackageParentCodeAction : CodeAction.CodeActionWithNestedActions { public override ImmutableArray<string> Tags => WellKnownTagArrays.NuGet; /// <summary> /// Even though we have child actions, we mark ourselves as explicitly non-inlinable. /// We want to the experience of having the top level item the user has to see and /// navigate through, and we don't want our child items confusingly being added to the /// top level light-bulb where it's not clear what effect they would have if invoked. /// </summary> public InstallPackageParentCodeAction( IPackageInstallerService installerService, string source, string packageName, bool includePrerelease, Document document) : base(string.Format(FeaturesResources.Install_package_0, packageName), CreateNestedActions(installerService, source, packageName, includePrerelease, document), isInlinable: false) { } private static ImmutableArray<CodeAction> CreateNestedActions( IPackageInstallerService installerService, string source, string packageName, bool includePrerelease, Document document) { // Determine what versions of this package are already installed in some project // in this solution. We'll offer to add those specific versions to this project, // followed by an option to "Find and install latest version." var installedVersions = installerService.GetInstalledVersions(packageName); var codeActions = ArrayBuilder<CodeAction>.GetInstance(); // First add the actions to install a specific version. codeActions.AddRange(installedVersions.Select(v => CreateCodeAction( installerService, source, packageName, document, versionOpt: v, includePrerelease: includePrerelease, isLocal: true))); // Now add the action to install the specific version. codeActions.Add(CreateCodeAction( installerService, source, packageName, document, versionOpt: null, includePrerelease: includePrerelease, isLocal: false)); // And finally the action to show the package manager dialog. codeActions.Add(new InstallWithPackageManagerCodeAction(installerService, packageName)); return codeActions.ToImmutableAndFree(); } private static CodeAction CreateCodeAction( IPackageInstallerService installerService, string source, string packageName, Document document, string versionOpt, bool includePrerelease, bool isLocal) { return new InstallPackageDirectlyCodeAction( installerService, document, source, packageName, versionOpt, includePrerelease, isLocal); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/VisualStudio/Core/Def/EditorConfigSettings/Whitespace/View/ColumnDefnitions/WhitespaceValueColumnDefinition.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.ComponentModel.Composition; using System.Windows; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Utilities; using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.Whitespace; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.View.ColumnDefnitions { [Export(typeof(ITableColumnDefinition))] [Name(Value)] internal class WhitespaceValueColumnDefinition : TableColumnDefinitionBase { private readonly IEnumerable<IEnumSettingViewModelFactory> _factories; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WhitespaceValueColumnDefinition([ImportMany] IEnumerable<IEnumSettingViewModelFactory> factories) { _factories = factories; } public override string Name => Value; public override string DisplayName => ServicesVSResources.Value; public override double MinWidth => 80; public override bool DefaultVisible => false; public override bool IsFilterable => false; public override bool IsSortable => false; public override TextWrapping TextWrapping => TextWrapping.NoWrap; public override bool TryCreateColumnContent(ITableEntryHandle entry, bool singleColumnView, out FrameworkElement? content) { if (!entry.TryGetValue(Value, out WhitespaceSetting setting)) { content = null; return false; } if (setting.Type == typeof(bool)) { content = new WhitespaceBoolSettingView(setting); return true; } foreach (var factory in _factories) { if (factory.IsSupported(setting.Key)) { var viewModel = factory.CreateViewModel(setting); content = new EnumSettingView(viewModel); return true; } } content = null; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Windows; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Utilities; using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.Whitespace; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.View.ColumnDefnitions { [Export(typeof(ITableColumnDefinition))] [Name(Value)] internal class WhitespaceValueColumnDefinition : TableColumnDefinitionBase { private readonly IEnumerable<IEnumSettingViewModelFactory> _factories; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WhitespaceValueColumnDefinition([ImportMany] IEnumerable<IEnumSettingViewModelFactory> factories) { _factories = factories; } public override string Name => Value; public override string DisplayName => ServicesVSResources.Value; public override double MinWidth => 80; public override bool DefaultVisible => false; public override bool IsFilterable => false; public override bool IsSortable => false; public override TextWrapping TextWrapping => TextWrapping.NoWrap; public override bool TryCreateColumnContent(ITableEntryHandle entry, bool singleColumnView, out FrameworkElement? content) { if (!entry.TryGetValue(Value, out WhitespaceSetting setting)) { content = null; return false; } if (setting.Type == typeof(bool)) { content = new WhitespaceBoolSettingView(setting); return true; } foreach (var factory in _factories) { if (factory.IsSupported(setting.Key)) { var viewModel = factory.CreateViewModel(setting); content = new EnumSettingView(viewModel); return true; } } content = null; return false; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./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,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Helpers/MefHostServicesHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection; namespace Microsoft.CodeAnalysis.Host.Mef { internal static class MefHostServicesHelpers { public static ImmutableArray<Assembly> LoadNearbyAssemblies(IEnumerable<string> assemblyNames) { var assemblies = new List<Assembly>(); foreach (var assemblyName in assemblyNames) { var assembly = TryLoadNearbyAssembly(assemblyName); if (assembly != null) { assemblies.Add(assembly); } } return assemblies.ToImmutableArray(); } private static Assembly TryLoadNearbyAssembly(string assemblySimpleName) { var thisAssemblyName = typeof(MefHostServicesHelpers).GetTypeInfo().Assembly.GetName(); var assemblyShortName = thisAssemblyName.Name; var assemblyVersion = thisAssemblyName.Version; var publicKeyToken = thisAssemblyName.GetPublicKeyToken().Aggregate(string.Empty, (s, b) => s + b.ToString("x2")); if (string.IsNullOrEmpty(publicKeyToken)) { publicKeyToken = "null"; } var assemblyName = new AssemblyName(string.Format("{0}, Version={1}, Culture=neutral, PublicKeyToken={2}", assemblySimpleName, assemblyVersion, publicKeyToken)); try { return Assembly.Load(assemblyName); } catch (Exception) { 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection; namespace Microsoft.CodeAnalysis.Host.Mef { internal static class MefHostServicesHelpers { public static ImmutableArray<Assembly> LoadNearbyAssemblies(IEnumerable<string> assemblyNames) { var assemblies = new List<Assembly>(); foreach (var assemblyName in assemblyNames) { var assembly = TryLoadNearbyAssembly(assemblyName); if (assembly != null) { assemblies.Add(assembly); } } return assemblies.ToImmutableArray(); } private static Assembly TryLoadNearbyAssembly(string assemblySimpleName) { var thisAssemblyName = typeof(MefHostServicesHelpers).GetTypeInfo().Assembly.GetName(); var assemblyShortName = thisAssemblyName.Name; var assemblyVersion = thisAssemblyName.Version; var publicKeyToken = thisAssemblyName.GetPublicKeyToken().Aggregate(string.Empty, (s, b) => s + b.ToString("x2")); if (string.IsNullOrEmpty(publicKeyToken)) { publicKeyToken = "null"; } var assemblyName = new AssemblyName(string.Format("{0}, Version={1}, Culture=neutral, PublicKeyToken={2}", assemblySimpleName, assemblyVersion, publicKeyToken)); try { return Assembly.Load(assemblyName); } catch (Exception) { return null; } } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/VisualStudio/Core/Def/Implementation/Utilities/VsEnumDebugName.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 Microsoft.VisualStudio; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities { internal class VsEnumDebugName : IVsEnumDebugName { private readonly IList<IVsDebugName> _values; private int _currentIndex; public VsEnumDebugName(IList<IVsDebugName> values) { _values = values; _currentIndex = 0; } public int Clone(out IVsEnumDebugName ppEnum) { ppEnum = new VsEnumDebugName(_values); return VSConstants.S_OK; } public int GetCount(out uint pceltCount) { pceltCount = (uint)_values.Count; return VSConstants.S_OK; } public int Next(uint celt, IVsDebugName[] rgelt, uint[] pceltFetched) { var i = 0; for (; i < celt && _currentIndex < _values.Count; i++, _currentIndex++) { rgelt[i] = _values[_currentIndex]; } if (pceltFetched != null && pceltFetched.Length > 0) { pceltFetched[0] = (uint)i; } return i < celt ? VSConstants.S_FALSE : VSConstants.S_OK; } public int Reset() { _currentIndex = 0; return VSConstants.S_OK; } public int Skip(uint celt) { _currentIndex += (int)celt; return _currentIndex < _values.Count ? VSConstants.S_OK : VSConstants.S_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.Generic; using Microsoft.VisualStudio; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities { internal class VsEnumDebugName : IVsEnumDebugName { private readonly IList<IVsDebugName> _values; private int _currentIndex; public VsEnumDebugName(IList<IVsDebugName> values) { _values = values; _currentIndex = 0; } public int Clone(out IVsEnumDebugName ppEnum) { ppEnum = new VsEnumDebugName(_values); return VSConstants.S_OK; } public int GetCount(out uint pceltCount) { pceltCount = (uint)_values.Count; return VSConstants.S_OK; } public int Next(uint celt, IVsDebugName[] rgelt, uint[] pceltFetched) { var i = 0; for (; i < celt && _currentIndex < _values.Count; i++, _currentIndex++) { rgelt[i] = _values[_currentIndex]; } if (pceltFetched != null && pceltFetched.Length > 0) { pceltFetched[0] = (uint)i; } return i < celt ? VSConstants.S_FALSE : VSConstants.S_OK; } public int Reset() { _currentIndex = 0; return VSConstants.S_OK; } public int Skip(uint celt) { _currentIndex += (int)celt; return _currentIndex < _values.Count ? VSConstants.S_OK : VSConstants.S_FALSE; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/VisualStudio/Core/Def/Implementation/Interop/WeakComHandle.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Interop { internal struct WeakComHandle<THandle, TObject> where THandle : class where TObject : class, THandle { // NOTE: The logic here is a little bit tricky. We can't just keep a WeakReference to // something like a ComHandle, since it's not something that our clients keep alive. // instead, we keep a weak reference to the inner managed object, which we know will // always be alive if the outer aggregate is alive. We can't just keep a WeakReference // to the RCW for the outer object either, since in cases where we have a DCOM or native // client, the RCW will be cleaned up, even though there is still a native reference // to the underlying native outer object. // // Instead we make use of an implementation detail of the way the CLR's COM aggregation // works. Namely, if all references to the aggregated object are released, the CLR // responds to QI's for IUnknown with a different object. So, we store the original // value, when we know that we have a client, and then we use that to compare to see // if we still have a client alive. // // NOTE: This is _NOT_ AddRef'd. We use it just to store the integer value of the // IUnknown for comparison purposes. private readonly WeakReference _managedObjectWeakReference; private readonly IntPtr _pUnkOfInnerUnknownWhenAlive; public WeakComHandle(THandle comAggregateObject) { if (comAggregateObject == null) { _managedObjectWeakReference = null; _pUnkOfInnerUnknownWhenAlive = IntPtr.Zero; } var pUnk = IntPtr.Zero; var managedObject = ComAggregate.GetManagedObject<TObject>(comAggregateObject); try { pUnk = Marshal.GetIUnknownForObject(managedObject); _pUnkOfInnerUnknownWhenAlive = pUnk; } finally { if (pUnk != IntPtr.Zero) { Marshal.Release(pUnk); } } _managedObjectWeakReference = new WeakReference(managedObject); } public WeakComHandle(ComHandle<THandle, TObject> handle) { var pUnk = IntPtr.Zero; try { pUnk = Marshal.GetIUnknownForObject(handle.Object); _pUnkOfInnerUnknownWhenAlive = pUnk; } finally { if (pUnk != IntPtr.Zero) { Marshal.Release(pUnk); } } _managedObjectWeakReference = new WeakReference(handle.Object); } public THandle ComAggregateObject { get { // This is pretty fragile code, watch carefully for race conditions! var pUnk = IntPtr.Zero; try { if (_managedObjectWeakReference == null) { return null; } // Copy target locally to make sure other thread won't delete it before we use it var target = _managedObjectWeakReference.Target; if (target == null) { return null; } pUnk = Marshal.GetIUnknownForObject(target); if (pUnk == _pUnkOfInnerUnknownWhenAlive) { // QueryInterface on COM aggregate might fail during shutdown, so we // defensively use "as" instead of casting (see Dev10 816848). return Marshal.GetObjectForIUnknown(pUnk) as THandle; } else { return null; } } finally { if (pUnk != IntPtr.Zero) { Marshal.Release(pUnk); } } } } internal bool TryGetManagedObjectWithoutCaringWhetherNativeObjectIsAlive(out TObject managedObject) { // NOTE: Only use this method if you do NOT care whether the native ComAggregate // object has already been released. if (_managedObjectWeakReference == null) { managedObject = null; return false; } managedObject = _managedObjectWeakReference.Target as TObject; return managedObject != null; } public ComHandle<THandle, TObject>? ComHandle { get { var rcw = this.ComAggregateObject; if (rcw == null) { return null; } Debug.Assert(_managedObjectWeakReference != null); if (_managedObjectWeakReference.Target is TObject managedObject) { // Construct a new ComHandle without going through the cycle of unwrapping // the managed object from the rcw, that has shown to be a perf concern for // progression (see Dev10 Bug 628992). return new ComHandle<THandle, TObject>(rcw, managedObject); } else { // We fall back to trying to unwrap the managed object out of the rcw, but // the Weakref to the managed object shouldn't go null if the rcw is still // alive, should it? Debug.Fail("Can this really happen?"); return new ComHandle<THandle, TObject>(rcw); } } } public bool IsAlive() { if (_managedObjectWeakReference == null) { return false; } return _managedObjectWeakReference.IsAlive; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Interop { internal struct WeakComHandle<THandle, TObject> where THandle : class where TObject : class, THandle { // NOTE: The logic here is a little bit tricky. We can't just keep a WeakReference to // something like a ComHandle, since it's not something that our clients keep alive. // instead, we keep a weak reference to the inner managed object, which we know will // always be alive if the outer aggregate is alive. We can't just keep a WeakReference // to the RCW for the outer object either, since in cases where we have a DCOM or native // client, the RCW will be cleaned up, even though there is still a native reference // to the underlying native outer object. // // Instead we make use of an implementation detail of the way the CLR's COM aggregation // works. Namely, if all references to the aggregated object are released, the CLR // responds to QI's for IUnknown with a different object. So, we store the original // value, when we know that we have a client, and then we use that to compare to see // if we still have a client alive. // // NOTE: This is _NOT_ AddRef'd. We use it just to store the integer value of the // IUnknown for comparison purposes. private readonly WeakReference _managedObjectWeakReference; private readonly IntPtr _pUnkOfInnerUnknownWhenAlive; public WeakComHandle(THandle comAggregateObject) { if (comAggregateObject == null) { _managedObjectWeakReference = null; _pUnkOfInnerUnknownWhenAlive = IntPtr.Zero; } var pUnk = IntPtr.Zero; var managedObject = ComAggregate.GetManagedObject<TObject>(comAggregateObject); try { pUnk = Marshal.GetIUnknownForObject(managedObject); _pUnkOfInnerUnknownWhenAlive = pUnk; } finally { if (pUnk != IntPtr.Zero) { Marshal.Release(pUnk); } } _managedObjectWeakReference = new WeakReference(managedObject); } public WeakComHandle(ComHandle<THandle, TObject> handle) { var pUnk = IntPtr.Zero; try { pUnk = Marshal.GetIUnknownForObject(handle.Object); _pUnkOfInnerUnknownWhenAlive = pUnk; } finally { if (pUnk != IntPtr.Zero) { Marshal.Release(pUnk); } } _managedObjectWeakReference = new WeakReference(handle.Object); } public THandle ComAggregateObject { get { // This is pretty fragile code, watch carefully for race conditions! var pUnk = IntPtr.Zero; try { if (_managedObjectWeakReference == null) { return null; } // Copy target locally to make sure other thread won't delete it before we use it var target = _managedObjectWeakReference.Target; if (target == null) { return null; } pUnk = Marshal.GetIUnknownForObject(target); if (pUnk == _pUnkOfInnerUnknownWhenAlive) { // QueryInterface on COM aggregate might fail during shutdown, so we // defensively use "as" instead of casting (see Dev10 816848). return Marshal.GetObjectForIUnknown(pUnk) as THandle; } else { return null; } } finally { if (pUnk != IntPtr.Zero) { Marshal.Release(pUnk); } } } } internal bool TryGetManagedObjectWithoutCaringWhetherNativeObjectIsAlive(out TObject managedObject) { // NOTE: Only use this method if you do NOT care whether the native ComAggregate // object has already been released. if (_managedObjectWeakReference == null) { managedObject = null; return false; } managedObject = _managedObjectWeakReference.Target as TObject; return managedObject != null; } public ComHandle<THandle, TObject>? ComHandle { get { var rcw = this.ComAggregateObject; if (rcw == null) { return null; } Debug.Assert(_managedObjectWeakReference != null); if (_managedObjectWeakReference.Target is TObject managedObject) { // Construct a new ComHandle without going through the cycle of unwrapping // the managed object from the rcw, that has shown to be a perf concern for // progression (see Dev10 Bug 628992). return new ComHandle<THandle, TObject>(rcw, managedObject); } else { // We fall back to trying to unwrap the managed object out of the rcw, but // the Weakref to the managed object shouldn't go null if the rcw is still // alive, should it? Debug.Fail("Can this really happen?"); return new ComHandle<THandle, TObject>(rcw); } } } public bool IsAlive() { if (_managedObjectWeakReference == null) { return false; } return _managedObjectWeakReference.IsAlive; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/ExpressionEvaluator/CSharp/Test/ResultProvider/AccessibilityTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class AccessibilityTests : CSharpResultProviderTestBase { [WorkItem(889710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889710")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/21084")] public void HideNonPublicMembersBaseClass() { var sourceA = @"public class A { public object FA0; internal object FA1; protected internal object FA2; protected object FA3; private object FA4; public object PA0 { get { return null; } } internal object PA1 { get { return null; } } protected internal object PA2 { get { return null; } } protected object PA3 { get { return null; } } private object PA4 { get { return null; } } public object PA5 { set { } } public object PA6 { internal get; set; } public object PA7 { protected internal get; set; } public object PA8 { protected get; set; } public object PA9 { private get; set; } internal object PAA { private get; set; } protected internal object PAB { internal get; set; } protected internal object PAC { protected get; set; } protected object PAD { private get; set; } public static object SFA0; internal static object SFA1; protected static internal object SPA2 { get { return null; } } protected static object SPA3 { get { return null; } } public static object SPA4 { private get { return null; } set { } } }"; var sourceB = @"public class B : A { public object FB0; internal object FB1; protected internal object FB2; protected object FB3; private object FB4; public object PB0 { get { return null; } } internal object PB1 { get { return null; } } protected internal object PB2 { get { return null; } } protected object PB3 { get { return null; } } private object PB4 { get { return null; } } public object PB5 { set { } } public object PB6 { internal get; set; } public object PB7 { protected internal get; set; } public object PB8 { protected get; set; } public object PB9 { private get; set; } internal object PBA { private get; set; } protected internal object PBB { internal get; set; } protected internal object PBC { protected get; set; } protected object PBD { private get; set; } public static object SPB0 { get { return null; } } public static object SPB1 { internal get { return null; } set { } } protected static internal object SFB2; protected static object SFB3; private static object SFB4; } class C { A a = new B(); }"; // Derived class in assembly with PDB, // base class in assembly without PDB. var compilationA = CSharpTestBase.CreateCompilation(sourceA, options: TestOptions.ReleaseDll); var bytesA = compilationA.EmitToArray(); var referenceA = MetadataReference.CreateFromImage(bytesA); var compilationB = CSharpTestBase.CreateCompilation(sourceB, options: TestOptions.DebugDll, references: new MetadataReference[] { referenceA }); var bytesB = compilationB.EmitToArray(); var assemblyA = ReflectionUtilities.Load(bytesA); var assemblyB = ReflectionUtilities.Load(bytesB); DkmClrValue value; using (ReflectionUtilities.LoadAssemblies(assemblyA, assemblyB)) { var runtime = new DkmClrRuntimeInstance(new[] { assemblyB }); var type = assemblyB.GetType("C", throwOnError: true); value = CreateDkmClrValue( Activator.CreateInstance(type), runtime.GetType((TypeImpl)type)); } var rootExpr = "new C()"; var evalResult = FormatResult(rootExpr, value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers)); Verify(evalResult, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("a", "{B}", "A {B}", "(new C()).a", DkmEvaluationResultFlags.Expandable)); // The native EE includes properties where the setter is accessible but the getter is not. // We treat those properties as non-public. children = GetChildren(children[0]); Verify(children, EvalResult("FA0", "null", "object", "(new C()).a.FA0"), EvalResult("FA2", "null", "object", "(new C()).a.FA2"), EvalResult("FA3", "null", "object", "(new C()).a.FA3"), EvalResult("FB0", "null", "object", "((B)(new C()).a).FB0"), EvalResult("FB1", "null", "object", "((B)(new C()).a).FB1"), EvalResult("FB2", "null", "object", "((B)(new C()).a).FB2"), EvalResult("FB3", "null", "object", "((B)(new C()).a).FB3"), EvalResult("FB4", "null", "object", "((B)(new C()).a).FB4"), EvalResult("PA0", "null", "object", "(new C()).a.PA0", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA2", "null", "object", "(new C()).a.PA2", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA3", "null", "object", "(new C()).a.PA3", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA7", "null", "object", "(new C()).a.PA7"), EvalResult("PA8", "null", "object", "(new C()).a.PA8"), EvalResult("PAC", "null", "object", "(new C()).a.PAC"), EvalResult("PB0", "null", "object", "((B)(new C()).a).PB0", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB1", "null", "object", "((B)(new C()).a).PB1", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB2", "null", "object", "((B)(new C()).a).PB2", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB3", "null", "object", "((B)(new C()).a).PB3", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB4", "null", "object", "((B)(new C()).a).PB4", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB6", "null", "object", "((B)(new C()).a).PB6"), EvalResult("PB7", "null", "object", "((B)(new C()).a).PB7"), EvalResult("PB8", "null", "object", "((B)(new C()).a).PB8"), EvalResult("PB9", "null", "object", "((B)(new C()).a).PB9"), EvalResult("PBA", "null", "object", "((B)(new C()).a).PBA"), EvalResult("PBB", "null", "object", "((B)(new C()).a).PBB"), EvalResult("PBC", "null", "object", "((B)(new C()).a).PBC"), EvalResult("PBD", "null", "object", "((B)(new C()).a).PBD"), EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "(new C()).a, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); // Static members var more = GetChildren(children[children.Length - 2]); Verify(more, EvalResult("SFA0", "null", "object", "A.SFA0"), EvalResult("SFB2", "null", "object", "B.SFB2"), EvalResult("SFB3", "null", "object", "B.SFB3"), EvalResult("SFB4", "null", "object", "B.SFB4"), EvalResult("SPA2", "null", "object", "A.SPA2", DkmEvaluationResultFlags.ReadOnly), EvalResult("SPA3", "null", "object", "A.SPA3", DkmEvaluationResultFlags.ReadOnly), EvalResult("SPB0", "null", "object", "B.SPB0", DkmEvaluationResultFlags.ReadOnly), EvalResult("SPB1", "null", "object", "B.SPB1"), EvalResult("Non-Public members", null, "", "B, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); // Non-Public static members more = GetChildren(more[more.Length - 1]); Verify(more, EvalResult("SFA1", "null", "object", "A.SFA1"), EvalResult("SPA4", "null", "object", "A.SPA4")); // Non-Public members more = GetChildren(children[children.Length - 1]); Verify(more, EvalResult("FA1", "null", "object", "(new C()).a.FA1"), EvalResult("FA4", "null", "object", "(new C()).a.FA4"), EvalResult("PA1", "null", "object", "(new C()).a.PA1", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA4", "null", "object", "(new C()).a.PA4", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA6", "null", "object", "(new C()).a.PA6"), EvalResult("PA9", "null", "object", "(new C()).a.PA9"), EvalResult("PAA", "null", "object", "(new C()).a.PAA"), EvalResult("PAB", "null", "object", "(new C()).a.PAB"), EvalResult("PAD", "null", "object", "(new C()).a.PAD")); } [WorkItem(889710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889710")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/21084")] public void HideNonPublicMembersDerivedClass() { var sourceA = @"public class A { public object FA0; internal object FA1; protected internal object FA2; protected object FA3; private object FA4; public object PA0 { get { return null; } } internal object PA1 { get { return null; } } protected internal object PA2 { get { return null; } } protected object PA3 { get { return null; } } private object PA4 { get { return null; } } public object PA5 { set { } } public object PA6 { internal get; set; } public object PA7 { protected internal get; set; } public object PA8 { protected get; set; } public object PA9 { private get; set; } internal object PAA { private get; set; } protected internal object PAB { internal get; set; } protected internal object PAC { protected get; set; } protected object PAD { private get; set; } public static object SFA0; internal static object SFA1; protected static internal object SPA2 { get { return null; } } protected static object SPA3 { get { return null; } } public static object SPA4 { private get { return null; } set { } } }"; var sourceB = @"public class B : A { public object FB0; internal object FB1; protected internal object FB2; protected object FB3; private object FB4; public object PB0 { get { return null; } } internal object PB1 { get { return null; } } protected internal object PB2 { get { return null; } } protected object PB3 { get { return null; } } private object PB4 { get { return null; } } public object PB5 { set { } } public object PB6 { internal get; set; } public object PB7 { protected internal get; set; } public object PB8 { protected get; set; } public object PB9 { private get; set; } internal object PBA { private get; set; } protected internal object PBB { internal get; set; } protected internal object PBC { protected get; set; } protected object PBD { private get; set; } public static object SPB0 { get { return null; } } public static object SPB1 { internal get { return null; } set { } } protected static internal object SFB2; protected static object SFB3; private static object SFB4; } class C { A a = new B(); }"; // Base class in assembly with PDB, // derived class in assembly without PDB. var compilationA = CSharpTestBase.CreateCompilation(sourceA, options: TestOptions.DebugDll); var bytesA = compilationA.EmitToArray(); var referenceA = MetadataReference.CreateFromImage(bytesA); var compilationB = CSharpTestBase.CreateCompilation(sourceB, options: TestOptions.ReleaseDll, references: new MetadataReference[] { referenceA }); var bytesB = compilationB.EmitToArray(); var assemblyA = ReflectionUtilities.Load(bytesA); var assemblyB = ReflectionUtilities.Load(bytesB); DkmClrValue value; using (ReflectionUtilities.LoadAssemblies(assemblyA, assemblyB)) { var runtime = new DkmClrRuntimeInstance(new[] { assemblyA }); var type = assemblyB.GetType("C", throwOnError: true); value = CreateDkmClrValue( Activator.CreateInstance(type), runtime.GetType((TypeImpl)type)); } var rootExpr = "new C()"; var evalResult = FormatResult(rootExpr, value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers)); Verify(evalResult, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Non-Public members", null, "", "new C(), hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); children = GetChildren(children[0]); Verify(children, EvalResult("a", "{B}", "A {B}", "(new C()).a", DkmEvaluationResultFlags.Expandable)); // The native EE includes properties where the // setter is accessible but the getter is not. // We treat those properties as non-public. children = GetChildren(children[0]); Verify(children, EvalResult("FA0", "null", "object", "(new C()).a.FA0"), EvalResult("FA1", "null", "object", "(new C()).a.FA1"), EvalResult("FA2", "null", "object", "(new C()).a.FA2"), EvalResult("FA3", "null", "object", "(new C()).a.FA3"), EvalResult("FA4", "null", "object", "(new C()).a.FA4"), EvalResult("FB0", "null", "object", "((B)(new C()).a).FB0"), EvalResult("FB2", "null", "object", "((B)(new C()).a).FB2"), EvalResult("FB3", "null", "object", "((B)(new C()).a).FB3"), EvalResult("PA0", "null", "object", "(new C()).a.PA0", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA1", "null", "object", "(new C()).a.PA1", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA2", "null", "object", "(new C()).a.PA2", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA3", "null", "object", "(new C()).a.PA3", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA4", "null", "object", "(new C()).a.PA4", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA6", "null", "object", "(new C()).a.PA6"), EvalResult("PA7", "null", "object", "(new C()).a.PA7"), EvalResult("PA8", "null", "object", "(new C()).a.PA8"), EvalResult("PA9", "null", "object", "(new C()).a.PA9"), EvalResult("PAA", "null", "object", "(new C()).a.PAA"), EvalResult("PAB", "null", "object", "(new C()).a.PAB"), EvalResult("PAC", "null", "object", "(new C()).a.PAC"), EvalResult("PAD", "null", "object", "(new C()).a.PAD"), EvalResult("PB0", "null", "object", "((B)(new C()).a).PB0", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB2", "null", "object", "((B)(new C()).a).PB2", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB3", "null", "object", "((B)(new C()).a).PB3", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB7", "null", "object", "((B)(new C()).a).PB7"), EvalResult("PB8", "null", "object", "((B)(new C()).a).PB8"), EvalResult("PBC", "null", "object", "((B)(new C()).a).PBC"), EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "(new C()).a, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); // Static members var more = GetChildren(children[children.Length - 2]); Verify(more, EvalResult("SFA0", "null", "object", "A.SFA0"), EvalResult("SFA1", "null", "object", "A.SFA1"), EvalResult("SFB2", "null", "object", "B.SFB2"), EvalResult("SFB3", "null", "object", "B.SFB3"), EvalResult("SPA2", "null", "object", "A.SPA2", DkmEvaluationResultFlags.ReadOnly), EvalResult("SPA3", "null", "object", "A.SPA3", DkmEvaluationResultFlags.ReadOnly), EvalResult("SPA4", "null", "object", "A.SPA4"), EvalResult("SPB0", "null", "object", "B.SPB0", DkmEvaluationResultFlags.ReadOnly), EvalResult("Non-Public members", null, "", "B, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); // Non-Public static members more = GetChildren(more[more.Length - 1]); Verify(more, EvalResult("SFB4", "null", "object", "B.SFB4"), EvalResult("SPB1", "null", "object", "B.SPB1")); // Non-Public members more = GetChildren(children[children.Length - 1]); Verify(more, EvalResult("FB1", "null", "object", "((B)(new C()).a).FB1"), EvalResult("FB4", "null", "object", "((B)(new C()).a).FB4"), EvalResult("PB1", "null", "object", "((B)(new C()).a).PB1", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB4", "null", "object", "((B)(new C()).a).PB4", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB6", "null", "object", "((B)(new C()).a).PB6"), EvalResult("PB9", "null", "object", "((B)(new C()).a).PB9"), EvalResult("PBA", "null", "object", "((B)(new C()).a).PBA"), EvalResult("PBB", "null", "object", "((B)(new C()).a).PBB"), EvalResult("PBD", "null", "object", "((B)(new C()).a).PBD")); } /// <summary> /// Class in assembly with no module. (For instance, /// an anonymous type created during debugging.) /// </summary> [Fact] public void NoModule() { var source = @"class C { object F; }"; var assembly = GetAssembly(source); var runtime = new DkmClrRuntimeInstance(new[] { assembly }, (r, a) => null); var type = assembly.GetType("C"); var value = CreateDkmClrValue( Activator.CreateInstance(type), runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers)); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class AccessibilityTests : CSharpResultProviderTestBase { [WorkItem(889710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889710")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/21084")] public void HideNonPublicMembersBaseClass() { var sourceA = @"public class A { public object FA0; internal object FA1; protected internal object FA2; protected object FA3; private object FA4; public object PA0 { get { return null; } } internal object PA1 { get { return null; } } protected internal object PA2 { get { return null; } } protected object PA3 { get { return null; } } private object PA4 { get { return null; } } public object PA5 { set { } } public object PA6 { internal get; set; } public object PA7 { protected internal get; set; } public object PA8 { protected get; set; } public object PA9 { private get; set; } internal object PAA { private get; set; } protected internal object PAB { internal get; set; } protected internal object PAC { protected get; set; } protected object PAD { private get; set; } public static object SFA0; internal static object SFA1; protected static internal object SPA2 { get { return null; } } protected static object SPA3 { get { return null; } } public static object SPA4 { private get { return null; } set { } } }"; var sourceB = @"public class B : A { public object FB0; internal object FB1; protected internal object FB2; protected object FB3; private object FB4; public object PB0 { get { return null; } } internal object PB1 { get { return null; } } protected internal object PB2 { get { return null; } } protected object PB3 { get { return null; } } private object PB4 { get { return null; } } public object PB5 { set { } } public object PB6 { internal get; set; } public object PB7 { protected internal get; set; } public object PB8 { protected get; set; } public object PB9 { private get; set; } internal object PBA { private get; set; } protected internal object PBB { internal get; set; } protected internal object PBC { protected get; set; } protected object PBD { private get; set; } public static object SPB0 { get { return null; } } public static object SPB1 { internal get { return null; } set { } } protected static internal object SFB2; protected static object SFB3; private static object SFB4; } class C { A a = new B(); }"; // Derived class in assembly with PDB, // base class in assembly without PDB. var compilationA = CSharpTestBase.CreateCompilation(sourceA, options: TestOptions.ReleaseDll); var bytesA = compilationA.EmitToArray(); var referenceA = MetadataReference.CreateFromImage(bytesA); var compilationB = CSharpTestBase.CreateCompilation(sourceB, options: TestOptions.DebugDll, references: new MetadataReference[] { referenceA }); var bytesB = compilationB.EmitToArray(); var assemblyA = ReflectionUtilities.Load(bytesA); var assemblyB = ReflectionUtilities.Load(bytesB); DkmClrValue value; using (ReflectionUtilities.LoadAssemblies(assemblyA, assemblyB)) { var runtime = new DkmClrRuntimeInstance(new[] { assemblyB }); var type = assemblyB.GetType("C", throwOnError: true); value = CreateDkmClrValue( Activator.CreateInstance(type), runtime.GetType((TypeImpl)type)); } var rootExpr = "new C()"; var evalResult = FormatResult(rootExpr, value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers)); Verify(evalResult, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("a", "{B}", "A {B}", "(new C()).a", DkmEvaluationResultFlags.Expandable)); // The native EE includes properties where the setter is accessible but the getter is not. // We treat those properties as non-public. children = GetChildren(children[0]); Verify(children, EvalResult("FA0", "null", "object", "(new C()).a.FA0"), EvalResult("FA2", "null", "object", "(new C()).a.FA2"), EvalResult("FA3", "null", "object", "(new C()).a.FA3"), EvalResult("FB0", "null", "object", "((B)(new C()).a).FB0"), EvalResult("FB1", "null", "object", "((B)(new C()).a).FB1"), EvalResult("FB2", "null", "object", "((B)(new C()).a).FB2"), EvalResult("FB3", "null", "object", "((B)(new C()).a).FB3"), EvalResult("FB4", "null", "object", "((B)(new C()).a).FB4"), EvalResult("PA0", "null", "object", "(new C()).a.PA0", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA2", "null", "object", "(new C()).a.PA2", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA3", "null", "object", "(new C()).a.PA3", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA7", "null", "object", "(new C()).a.PA7"), EvalResult("PA8", "null", "object", "(new C()).a.PA8"), EvalResult("PAC", "null", "object", "(new C()).a.PAC"), EvalResult("PB0", "null", "object", "((B)(new C()).a).PB0", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB1", "null", "object", "((B)(new C()).a).PB1", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB2", "null", "object", "((B)(new C()).a).PB2", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB3", "null", "object", "((B)(new C()).a).PB3", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB4", "null", "object", "((B)(new C()).a).PB4", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB6", "null", "object", "((B)(new C()).a).PB6"), EvalResult("PB7", "null", "object", "((B)(new C()).a).PB7"), EvalResult("PB8", "null", "object", "((B)(new C()).a).PB8"), EvalResult("PB9", "null", "object", "((B)(new C()).a).PB9"), EvalResult("PBA", "null", "object", "((B)(new C()).a).PBA"), EvalResult("PBB", "null", "object", "((B)(new C()).a).PBB"), EvalResult("PBC", "null", "object", "((B)(new C()).a).PBC"), EvalResult("PBD", "null", "object", "((B)(new C()).a).PBD"), EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "(new C()).a, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); // Static members var more = GetChildren(children[children.Length - 2]); Verify(more, EvalResult("SFA0", "null", "object", "A.SFA0"), EvalResult("SFB2", "null", "object", "B.SFB2"), EvalResult("SFB3", "null", "object", "B.SFB3"), EvalResult("SFB4", "null", "object", "B.SFB4"), EvalResult("SPA2", "null", "object", "A.SPA2", DkmEvaluationResultFlags.ReadOnly), EvalResult("SPA3", "null", "object", "A.SPA3", DkmEvaluationResultFlags.ReadOnly), EvalResult("SPB0", "null", "object", "B.SPB0", DkmEvaluationResultFlags.ReadOnly), EvalResult("SPB1", "null", "object", "B.SPB1"), EvalResult("Non-Public members", null, "", "B, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); // Non-Public static members more = GetChildren(more[more.Length - 1]); Verify(more, EvalResult("SFA1", "null", "object", "A.SFA1"), EvalResult("SPA4", "null", "object", "A.SPA4")); // Non-Public members more = GetChildren(children[children.Length - 1]); Verify(more, EvalResult("FA1", "null", "object", "(new C()).a.FA1"), EvalResult("FA4", "null", "object", "(new C()).a.FA4"), EvalResult("PA1", "null", "object", "(new C()).a.PA1", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA4", "null", "object", "(new C()).a.PA4", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA6", "null", "object", "(new C()).a.PA6"), EvalResult("PA9", "null", "object", "(new C()).a.PA9"), EvalResult("PAA", "null", "object", "(new C()).a.PAA"), EvalResult("PAB", "null", "object", "(new C()).a.PAB"), EvalResult("PAD", "null", "object", "(new C()).a.PAD")); } [WorkItem(889710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889710")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/21084")] public void HideNonPublicMembersDerivedClass() { var sourceA = @"public class A { public object FA0; internal object FA1; protected internal object FA2; protected object FA3; private object FA4; public object PA0 { get { return null; } } internal object PA1 { get { return null; } } protected internal object PA2 { get { return null; } } protected object PA3 { get { return null; } } private object PA4 { get { return null; } } public object PA5 { set { } } public object PA6 { internal get; set; } public object PA7 { protected internal get; set; } public object PA8 { protected get; set; } public object PA9 { private get; set; } internal object PAA { private get; set; } protected internal object PAB { internal get; set; } protected internal object PAC { protected get; set; } protected object PAD { private get; set; } public static object SFA0; internal static object SFA1; protected static internal object SPA2 { get { return null; } } protected static object SPA3 { get { return null; } } public static object SPA4 { private get { return null; } set { } } }"; var sourceB = @"public class B : A { public object FB0; internal object FB1; protected internal object FB2; protected object FB3; private object FB4; public object PB0 { get { return null; } } internal object PB1 { get { return null; } } protected internal object PB2 { get { return null; } } protected object PB3 { get { return null; } } private object PB4 { get { return null; } } public object PB5 { set { } } public object PB6 { internal get; set; } public object PB7 { protected internal get; set; } public object PB8 { protected get; set; } public object PB9 { private get; set; } internal object PBA { private get; set; } protected internal object PBB { internal get; set; } protected internal object PBC { protected get; set; } protected object PBD { private get; set; } public static object SPB0 { get { return null; } } public static object SPB1 { internal get { return null; } set { } } protected static internal object SFB2; protected static object SFB3; private static object SFB4; } class C { A a = new B(); }"; // Base class in assembly with PDB, // derived class in assembly without PDB. var compilationA = CSharpTestBase.CreateCompilation(sourceA, options: TestOptions.DebugDll); var bytesA = compilationA.EmitToArray(); var referenceA = MetadataReference.CreateFromImage(bytesA); var compilationB = CSharpTestBase.CreateCompilation(sourceB, options: TestOptions.ReleaseDll, references: new MetadataReference[] { referenceA }); var bytesB = compilationB.EmitToArray(); var assemblyA = ReflectionUtilities.Load(bytesA); var assemblyB = ReflectionUtilities.Load(bytesB); DkmClrValue value; using (ReflectionUtilities.LoadAssemblies(assemblyA, assemblyB)) { var runtime = new DkmClrRuntimeInstance(new[] { assemblyA }); var type = assemblyB.GetType("C", throwOnError: true); value = CreateDkmClrValue( Activator.CreateInstance(type), runtime.GetType((TypeImpl)type)); } var rootExpr = "new C()"; var evalResult = FormatResult(rootExpr, value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers)); Verify(evalResult, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Non-Public members", null, "", "new C(), hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); children = GetChildren(children[0]); Verify(children, EvalResult("a", "{B}", "A {B}", "(new C()).a", DkmEvaluationResultFlags.Expandable)); // The native EE includes properties where the // setter is accessible but the getter is not. // We treat those properties as non-public. children = GetChildren(children[0]); Verify(children, EvalResult("FA0", "null", "object", "(new C()).a.FA0"), EvalResult("FA1", "null", "object", "(new C()).a.FA1"), EvalResult("FA2", "null", "object", "(new C()).a.FA2"), EvalResult("FA3", "null", "object", "(new C()).a.FA3"), EvalResult("FA4", "null", "object", "(new C()).a.FA4"), EvalResult("FB0", "null", "object", "((B)(new C()).a).FB0"), EvalResult("FB2", "null", "object", "((B)(new C()).a).FB2"), EvalResult("FB3", "null", "object", "((B)(new C()).a).FB3"), EvalResult("PA0", "null", "object", "(new C()).a.PA0", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA1", "null", "object", "(new C()).a.PA1", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA2", "null", "object", "(new C()).a.PA2", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA3", "null", "object", "(new C()).a.PA3", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA4", "null", "object", "(new C()).a.PA4", DkmEvaluationResultFlags.ReadOnly), EvalResult("PA6", "null", "object", "(new C()).a.PA6"), EvalResult("PA7", "null", "object", "(new C()).a.PA7"), EvalResult("PA8", "null", "object", "(new C()).a.PA8"), EvalResult("PA9", "null", "object", "(new C()).a.PA9"), EvalResult("PAA", "null", "object", "(new C()).a.PAA"), EvalResult("PAB", "null", "object", "(new C()).a.PAB"), EvalResult("PAC", "null", "object", "(new C()).a.PAC"), EvalResult("PAD", "null", "object", "(new C()).a.PAD"), EvalResult("PB0", "null", "object", "((B)(new C()).a).PB0", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB2", "null", "object", "((B)(new C()).a).PB2", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB3", "null", "object", "((B)(new C()).a).PB3", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB7", "null", "object", "((B)(new C()).a).PB7"), EvalResult("PB8", "null", "object", "((B)(new C()).a).PB8"), EvalResult("PBC", "null", "object", "((B)(new C()).a).PBC"), EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "(new C()).a, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); // Static members var more = GetChildren(children[children.Length - 2]); Verify(more, EvalResult("SFA0", "null", "object", "A.SFA0"), EvalResult("SFA1", "null", "object", "A.SFA1"), EvalResult("SFB2", "null", "object", "B.SFB2"), EvalResult("SFB3", "null", "object", "B.SFB3"), EvalResult("SPA2", "null", "object", "A.SPA2", DkmEvaluationResultFlags.ReadOnly), EvalResult("SPA3", "null", "object", "A.SPA3", DkmEvaluationResultFlags.ReadOnly), EvalResult("SPA4", "null", "object", "A.SPA4"), EvalResult("SPB0", "null", "object", "B.SPB0", DkmEvaluationResultFlags.ReadOnly), EvalResult("Non-Public members", null, "", "B, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); // Non-Public static members more = GetChildren(more[more.Length - 1]); Verify(more, EvalResult("SFB4", "null", "object", "B.SFB4"), EvalResult("SPB1", "null", "object", "B.SPB1")); // Non-Public members more = GetChildren(children[children.Length - 1]); Verify(more, EvalResult("FB1", "null", "object", "((B)(new C()).a).FB1"), EvalResult("FB4", "null", "object", "((B)(new C()).a).FB4"), EvalResult("PB1", "null", "object", "((B)(new C()).a).PB1", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB4", "null", "object", "((B)(new C()).a).PB4", DkmEvaluationResultFlags.ReadOnly), EvalResult("PB6", "null", "object", "((B)(new C()).a).PB6"), EvalResult("PB9", "null", "object", "((B)(new C()).a).PB9"), EvalResult("PBA", "null", "object", "((B)(new C()).a).PBA"), EvalResult("PBB", "null", "object", "((B)(new C()).a).PBB"), EvalResult("PBD", "null", "object", "((B)(new C()).a).PBD")); } /// <summary> /// Class in assembly with no module. (For instance, /// an anonymous type created during debugging.) /// </summary> [Fact] public void NoModule() { var source = @"class C { object F; }"; var assembly = GetAssembly(source); var runtime = new DkmClrRuntimeInstance(new[] { assembly }, (r, a) => null); var type = assembly.GetType("C"); var value = CreateDkmClrValue( Activator.CreateInstance(type), runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers)); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./docs/wiki/images/how-to-investigate-ci-test-failures-figure8.png
PNG  IHDRrsRGBgAMA a pHYsodtEXtSoftwarepaint.net 4.1.6N d$IDATx^\ו&&H/%"Cla#Pg;8w`,BsqD pN0 E"d:+&xsΛ%KR%3y'SYj}NsNuUZ{Wԩn_B!Ĝ!yB!ɳB1wHBC,Bg!b< !sY!;$B!!yB!ɳB1wHBC,~>bHp8g;@L6?f!Y$a6k1 Y11<v56v5` ɳabxk0#1m|k09;g! V؉`Fb`j9s,|w$BĴrXH/X c'^ic[̱ݑ< _&N3ηS˙c#yb`5L x f$o 3wG,~j;HL;L-gY01<v56v5Z ɳaƟxuD;hG0}o O>-vwG,~jؤHwN3#yҹs_<Zv?o]ݑ< _6)Wzth~1OYv54_bD`jٙ_?EvwG,~jؤL]_[H\|q]<qq=WM|k09;g! V&e|JcmHKlOԁ2u?:A~}g;7v5Z ɳa2]y% 7@\g|(ß:Gw[M?qFx݆;L-gYհI<|#}ܙϒG6~l;Χ<Q=s:hKso 3wG,~jؤLSo} S[Ђ?L Ϸί}O][}i㉇ُ? ]~=ͯ>Y}ډ`F=i;_ԗ_~dcCxg14G&W;s9GB.٣|O?ō˽SԲ^5{`#yb`57v3C=>uN|??-Ϸ^}YH3kk_<L8xg{>O}TU71{a'^Ah)<']|6y&ϯoٹ=}ّ&|9_KGF*}Z.`jٕ_?궅Yհl=zϾb =&[gOl.m<o&Z~; (ǁg~}wn޹ш]=]a;̨5&o%h|lk_$v\Y~;gfyƫ%8zyYڗGj^14a[eW^ޑm+;g! Vp; }G+m>zWXw ߶iO_y噑h3[/T~W_~Z3:]d|yF+Zc[ebPk} m<6ĸg0'cv%?Q-n~|?|N3j(]<3ϞFy~3 噏ѿk?牱ݑ< _*ß9PGoeWw8w㗹vnm'R;oJ;ۗ7_-Z ϟ:R}^{_yaswv&Ϸ6G<s<pߩ뇝o 3wG,~jDzݴ(?N?yϠ|ܜxϖUjzЉͧG%ilN3jM+ywn+^ t|swnXw~gLF=ת햝_ /{^?sRnuyu{_oo 3wG,~jؤzOLt<d8BپR~ 9;9Nǎh갣+{O=؃P'8R{k04;[o6zKӟ79e';5kp ?ŵ?'n)Gpbb:{zeƑj;L-gYհyF-j>y<;G{c3wukO< ]֝Boc?{쫽x fԚVƹ'ZcO&p3&数TGp<5y&Nlݺ[f876|`>H`jBփwnwt7^0$WOx fԚ<W#{]>3ηSˮB հ\n>1[N3j}Ā ^?stt}|}`jByţ?sVkO|oƎibk0#1m|k09;g! V=׎7?qsO<kM؉`Fb`j9s,|w$BĴrXH/X oČĴ Y (2Lj0#1m|k0- vuG,~Du2FLj0#1m|k0-g!J` 6v5\F..H/vT7Ê0AĴu`Lg`ak$BLl`:<o6v5~ΐD]-< _Luaj0X]_&5L_ud9`nH/BWhLwX~F`3[ Aco~_CbWZ7eF$B+!,.w!h`Lpx8t3G,ÊGՕ fB4+ȯW1$B;X٨r#-˦. -yBjFf'h.^;jВg!aբE5__N\8x5ʲˬ2$BV**XAXMXYPb>#3BN?< !FX[5,yvBBKMήͿZ\8мx%Waɳb[g1k!DkpP tf< !RyfHY !Z 'Qh^_«;HXmnQJ\Qb>C[ h .*4Pb< ߱ڰۭ|` qy yb_cŢN}[#h .\>Eg_< Pb!ybH}P6ʇ~!Z N𺳋P,p*3oQYp ypp$_%FugYXUg$l׿5BU&yBbUgg[,Dp.6;%BǪB y}BY 5?x< ʳ,IX=6K.mu(yBֹN_K.~;/ۼx٥(yB5:j׶ٖ !ZKI,hɳ G,Ճyww]f}!ɳ3VgBfO%b < !:c`7yM7I&+WXBoݺe$b <"< !b`<%@,Ճ3@W,<-yB4a`n<߾}&~8N SR ɳ3Vf.hCwQ."3u>JDpr)ɳ3Vf"=zG Tk -uN ,Cnj-< !:c`wlS}9R.p.QP,A^`K8bZHz07)E534,~>4f>HHz0Ϟ!~GvrDy [|;gBgb8$BX=<s DyD<g/-Hz0syOFՉ$%bcxLK(՜[,< !:c`/䙃ʘ<(U.hpMSD,ՃYYg!C,ɳ!yBtY< !:c@,`Hz yb0$BX=< 1g!DgH ɳ3V$B Yg!C,ɳ!yBtY< !:c@,`Hz yb0$BX=< 1g!DgH ɳ3V$B Yg!C,ɳ!yBtY< !:c@,`Hz yb0$BX=< 1g!DgH ɳ3V$B Yg!C,ɳ!yBtY< !:c``y}w5b< !:c`&򼶶f^H_tkB,g!Dg\:$bё< !:c` Е<Y{t ݄׮]lh{ta_"Ɠ7ɱ6b< !:c`6ZwʮhĻg %9L_.Ğ#yBtL7$RoEyz.vs$BX=3ۮ `%(8A(B9s-S1g. ֋A$wh=uY6g[N-ba],ͨ (%~@t8<ϡC㘅M1̅<o!ĂX&ܾ}{n|+;<:~FXk b`u:3W]|Fyػq6B777NĻ(hCېɳ`<!<\]QDߎ<'Y~ T :y8,aoCB{ i!2`<DՂ9Nsf-&B-4paNn]Qb}]V¯J 1WTt0/OٵAyەՅROf'栂N !\׸<VLg?-2#yH< ! ԔwyK ZPavBqf!϶B,#/vPavBL噾]# ! ߪZFg[WA_N/*41S!ʳ-#:兊0} !\Rh!:1#yD͒g!أB[EB QÀl+*ڵZJ%P\Y !f#t~Ϭ +3h/B3of4k!E7Bd(y6>C[ X^~_;.*Ndfy 3go!{ ͺ ]ILB{g:meik˭[~B' 8 < !G,DWg.(ψFP { ϼuFl\lk $_Ca< 3#y;s6b!_7J%B<֙mkˋ3nwI}3O[#X^n޼)y{ %B(ϠD˓˳VPYLyf$~f@yJz)3g\=]-ϟ?o˄{?_Fq6'!3g@<#-ȑ#W\Y]]@_~GQ&kkkL<%B4򼲲r5HK/K.=O) yboqY,1Ν;{tg{CBLyg}<[oeCBL__ ǎ;qēO>9<#ǣ"x}p}!}Mƞ3sWNx:W1&1$ qaSp*WLqࢠPpuLAg.`?y-v SW=g<_pCϞ=(f1%yf!kSV%eCx` :fX<Li6x&OⓄ? mhXH`>`{qL)n73q>~jC?%~Z\ 7_9,*3ڛ=|ryWVJ\#gF14Fm23>uq@2ׯ_θ(fѰN@<iF2s&T<*~ 7͐|;mގ9"y2E^y3gΜ>}S>SkC]:9BL 3g?RH˜\؎*gAݓUDW1k$VzI 4S|mܹS\sKy1Hemɳ[ ,%OhjO^4k!7ή# KǐX\ ֯5Ggs'8!h?0Ϝ뮻`V hƗQErlNQL1+6 m=?C t'g_^i?&(ɟ__P}6QYu'o&f* PE;T:Ƃ%>Kc`FlGCۀD7,D9}6D!" lglnn `ez0F-l:9`3G @ )lq]::R<FI&ayPAWDx+_~Ϟ1YWSGssq*^xɳxL~`,<} Pe4N)FbՋ2zG;-R:mbSIYg_$9O6R#X0v<Nb%I@ I60q<yYaAqINŴ[AdS-ϰoMC\NY1<@t]#<']!tgSu. @fWjȤ$\ c61ȩ ]UYᡱAĸsro1y.)Bqնb Um%P<O&ڐA>I3$R D|/l'$r¤ z3oMg"NH]gw˧Nz*"e(1K$9'U-vs0P 1D]O@2{h6=hdA;2c)X1"ZxH[ !UϡBt噏)_*r*GLZ$IWq6JH)'۩<^pSԚ`K*,sOGL%Ϋ0\?H]h{ (EO3ϖ`0 _{8!Ҡ"XXa.Q%Yd<CN,O`  7NypC(O9RA8O q \)`<)j3XyƉϭ<X=ic8^ M?^X4 c ;.E`'ϵ-(.WՅKNmR-$AL%p a Ɏho+9g@&R3ߦl]tР7b0]m s0,r)y7e+L0<4̒.*byKo4N2l?~[N666AvP<E0mXh#xsná<%'w@1pNo^ P X‡rWINH?yU V<&ω,ryXڿ(QKԵ,<D8%EXIPPķХP8L'䡋 @mXSy AC<1a˗=8i$#1J<C4\l$ZFI,'DyMN!8:X,\)+9I'йrW<&FPgvQiq<{Yw 8H'K/V!\2 {oŴNOTG,&ľeQyi^U8?ś91c$BtEǠHAu\r@df/}YHz[{SYڼHY18g!"yB YH#y+g!HY18g!"yB YH#y+g!HY18g!"yB NB#ľE,ɳ]< !G,DW$B< ɳbp$BtE,ɳ]< !G,DW$B< ɳbp$BtE,B,#yB NB#ľeQ{衇jw}y[& $Bteȑ#W\Y]]@_~Go޼6X[[eB@,DWXWVV]}饗0rҥi8$B-g!"y1:t?/Ĵ< ѕecǎ8q'Hs>D>i`Цwc㡇gyW7&= qaqɟ{F,DW^/\y~ᇡgϞE<cy^<KyK!9r,Ylm<7 ɟ$'_K-'n1b԰||6H3ڛ=|ryWV2Jʛk(FHMX(yAׯ_θ4PtAݓ;.ly!3g2g!eg<sӧ9 SO=6I!cL ]5q=ypQAtqaU5/%g! Je1a=y+Ҭp8p[+SkI஼jgs'8!h?IibLmnn9Yw ]k,(:A8/tѿYc!.tЕ< (,<<N$bA"hB´)KH2lGCۀD7,D}6D!G lD3 ٍ'o&ۡ{ \ӏIX#,0;nB88$BteggI^vsP8XOX^1^ 60l(ρ4c7T Oݱ$9ԥI68E?"7vO< WS, B` n`NOŴgY,<ggT$ t^ 9'z&M rBGWUcixbY6190DwG~1bG]a9m,tbGWu'dΑ'(fR D~a< ѕe˗/:uիfY/ ,yIT<Y®r&C$U3Xcn_r }}Cq ͊I>(֯ȏ`a>a20+&wмBt%B, K"ϫ.\TUX;k%u 9'Ssj $ R[U(Vm5qc2~D ++|yh4d|61ĘpݙDxX$;m0ƚ1g! 򼽽>JRB#Ŵ1X/DgXIb bMb4Nq ]ga&~8EPF#h$Yܻwr! $B, s0ʨHɻ,|_]x!v#yh%\7U ,chd؜\qΓ7 d]O/&7٘j >B,ʓ!+;63=fOΤy@QЖH3AI4**CmM_ [-P7Pe5p x9NC۰j 0'sZ:O gt}Ucʏx fpuy<UqALa*>m2vG!n$A:X"ybQX`yv-i{z!`X <u ԞDĠHʢH;9THy- tEb*o$Β(ove_-g!"ycp +m5Mai,< ɳbp$BtE,3?d$/<`zK, g!+40K>:i 9~mP, ɳbp&MC!DzWݕ<%@,is>RdByH^!yB δ+yɳbp%r6?>\t1U<c<uU,< !gZvoS))+++.j)[̅>(V"yB $\ݦOR8Y!ψm_1]$BDlGu('lt봑g $yC yB EsqY Y18Sg!IJ"P'Z3Zt`dY Y18ӒgP;nTDJ¤ h_9],@,i3"'g^B777ѠҌSPMd!U֧<Y Y18SgdRYI/^%l 6ZGIg и~:~JHӻo< !G,DW$B< ɳbp$BtE,ɳ]YTyߟl>-Bg!|ȑ+Wnll/?7oDp $!1g!򼲲r5H/ҥKS@,"y+} '!B,DWA;vĉ'|r yFǏGE/ BaA!Nl픳]W"gS|:aO.;DcmH~ p|Y,<_pCϞ=(f1%yfe+"&gN <WEȟ];8yNC-C=*Y,<s'W_}`J~WX I^gs`?' Z&K^19ǥ$'8|<n=ƟNh,tѥǠ1bLH%< ѕeg<sӧ9 SO=6I٭"A:ũ4CHT#,EƓÉu>$QF%Bteua=y+kdN):N]__G8O<tR8I2K3cmq*& O>ԥ x ق䱸|26I"n&NpƱ$?S=D{,&=80G4c$Bte%ňԍw"uԕ?XFRDgi ` G!ۑ$4a0 SD %ڢ<zN" i'S)5d 07oDnZrup_\:cqn <XwĢOPpfH2sg*n=bƺ`uz2h>9IpU' zBp܉$p \s`y]U̱/>{$xYra\|kLN#xpN< W`ѱs`9И `H23|?{PIuARO@^jzU` aZ,^!?F3ɍ v`Y|͑$ iH*?bXJ'YDӆ1beyAKiON~2ʷC ɳ]Yy|S^ʩ*TRzP9B<D.08O녛 Ih8.~4bgAT#vvlH/x֯hHSQ69 h0,)f>_LYOCxDG,DWDWWW/\j\]9nϮԕ?$$L%k+vBCbi=ʲ0$2isp識6O!j=zp`CBOL'4~2D)̐< ѕe,•|l1m s'gsk(XOaϮ+pWAb܆S 4d۰G2o $q8":G'wDaI|J4g>$BteyοU)y7e `VT<440Fo| :sIe5r Ѐ;tW zC6\ӿԝWE.d]uXb$;7"n T| 2C>c$>[8O΄ x d mlK&G,DW3y8n߾Hy_Wn/yͷzuJPVWWَ`mk",s z%φoVNnmmN/ t|O fb?_t]@(,v4l?:G eKbhhJBΣAq"@1'F)p$2ɳ]>B%PL&wť=RdMq ^QGXz{Tanar"vrT~IpO@,DWUށI$:> ^MYH u7pCL@Gtv“כ!y+=u }^|bWvXRG'?g!"yB YH#yK'X8G<b< !gBy%Y㌽[SgZk(#yB $_,<Cy.Z\D, %vՉyIv-< !<vxk +gьY18Ar0 =CUE#ܲBD¢ *31va?l' f=UIi' yMO$b@9?Iv"@(#yB N?y6FוDeрЦHxׅ @O(!U Ĵ.Lg3'(]wE\KWSO>uL5` ɳbpP)ÒԼ0ICatK'l'1)i,Zxi+ka lIh@~8I)f^57sbCyN\BnO%f܃r %Q~Ģ% [B 7qa3&rmܲqwT|mSˍY18XWsK<2&J6 3q=*^h;yNt<e\op0nm.pN1nrbh绦;T[%F,~Laxl慈=UJ @H0NoquIPEI-Eyㄩ"7lb|`N%)&k.IޒˊY18|tXhWDT1ˑ\EQ`|ISs&jp> 6dbd 4MbnCwZu1:ɳbpz3,Q͓Ꜽɉ#\wlBP*ۑ/-Lf 7n/}Q|pҕ3$S캷AݒGGd؍G]E;!Í ӭ):gmWÙ,g!gB%Hȕ[[[Q$Ҽ0 Md`UL!q1p.$GB–,hس@}4Mwg6:Hw6WJmg!L(9.9IbrGɳbp.bx7bo< !G< CE-g!H֞+$B< ѕEg,|o2!^ y+ ,k=3/ر7|m)2!^ y+PEÇ?~_ȞS@,"y+ N&9ED,DWAWVVj yF/}Kmd YO?Ob|HG>]#q~^Q+] VꦆC,DW^oOB_|E2)3]ꌒį|+K,8ծKyF\!#-ItBg+ᡌ_7,Tl<=E$Btb3Νosʹp u*c+DŽ̃<|GI|?g~xE=FAˍسY,"z-}g/ u6Qq*x{쫁JYwJOGIQ&<@zS<ax63C,DWp.<t֕솩,h?1IH}QYcO{up hOe&F|6zt'i8acvۦb%A7e\ƹsګh#ZLQnܸ' ;0UDlzpw 9 y+Z^ZRIx'$)|EXPXaoC.JvfVXw<О'/±Fk $Ӄ ,9`g1 k(I|0O6qbMUAsN\$90wӧ3OACNeL'188$BtWsg2Y=XFA8`2P 2-9W)7 ?^?Ɠ`P)4um}ܲnÎg7Ycy-II!;$BtW32.~ P8FXŔF#zpXcLb/ Sh##f1'wnEw?x;mN*0t(xtIz]z+ro0 \T# cn m,OUݓS-GPg!u'STϤfNڗNŴF^aU ).tBaKػZ|_"l FdVhx{s'm9=w{NK'Ƈ8,f:y.f^ q$X\ ɳ]պ 3|[TUekN׆XsF^b5@7gJ.CsG6UP"wn3gѥV맑Ga LyJj{N2/%..jfH օW>}z>kK'AIn)wtcuy2!B*`lNy&cLN2c6e84-*b9Il~~#`$z#Ecn!ɳ]պ<_ C>A\/XX7c-1oA7LKv.ӆb+l`>1"'vq$C %6y$vYOcw̲~Z?tY!V4y<ο. Y`VZm,EE'=< \*%e< CmM_P`ՁXz(sNjA(y&2lP7q6A9 [0F0}&,lj~hd$A](m3(*NAr`H)"BbЈlƘM< $DFwODKPwtApu~"y+ZU*b%"F Od2< ѕEg!& ﭧE~[,$BtE, _ףdNۄT< ѕl2k!.ŏ>%.NSxG$|h}Q1fx6HJF,hYH3y~z街^zsƜ'ɳbp=wلD`$'<ÿ{1\zbY< !gyԥK8ɳ$B<G&АE$B<KEW$BH1eHuf?8ڀܛ7֚]wEE0Cڵk6D==17`UI\)D,=g!L]9@{ʊet"7ػ>asݸ*Fb< !gytE(T.c֯I8ZF1= br <2!2<'I079E%%mp4Ӑ^rṶLĒ!yB t8ޠEA?0<c!@~&b< !g 073mK䙱ruWyD\,7g!L]]_ *n+,rM$x;Q@L!;Qa#Fb!yB jn<7N.ms`.1&RL&1blllH3<C"d<q:94\xcEQ,1ߪDNebz (R2R-ɳbpz@{f(Qɳbp$BtE,ɳ]< !G,DW$Bgyb>YTy ^"c#w}mb/< ѕ#G\reuu/?7oDp J!%g!򼲲rWW[.]J~wS@,"y+ N&9ED,DWA;vĉ'|r yFǏ1d?Oм1{yN·tzt`<ڛ/hHl˯(Oɳ]YxypB={QbJ̺FPw%Nv<X3Z?Ɩ#h?KCy<%qh y+ /honn>s)W_=X?I2a6Qi1L0R {bV|̣'y!y+ y̙ӧOsAէz qm ^mdNx6jR֝R% 1y]ɞlM,DWAQJvT{Z%u0~f|߱A­c)Z 注$ ƍ<О`Ll01N&0qq !M_0KKnt:j0Kǔbt̾v$bNL>9t< ѕeg2R7 8I \/QN=W]s%`mVRw<О'/,XFkaS]?=2|QK 4l'ԋY%9t=(L$94Qg<g3%f=%v$v]`<@4Cp< y+ u=6NDp+/IktڈK9E{]O}CYO-+>~~n۰8,N_c~Nh9H+֑lʣ8-Lɳ]Yyg5(z]/ t Q hDX?\FG<(b2N#@#&` {3T[9t(xtIz]z+ꦪc!blDIw9R=qF07DA m$ytU[8b< ѕe˗/:uիb&p%=(,,4rnAhB@']O6}\`hTd#U4"Puo$ҰMY<gtu )<4e֥o[{3 bҋ y+K"ϫ.\TN{iR?Xi!M왒!FXIrR,l B)Euf\ϢKoEMB.FDzIqΓS7z8$Btey{{{}}}>kK$r fStcy2!B#W*`lNy&clƸ F0]O1 ḽx,_l<!y+ 0X8b6m/ ,0.)L6"D/ظ b*qy&:BDixk$%ΓYv4AE0,IzLenqhIEs(X|_0Ɂ~vr$Bte$ڰvPn[E/au /aE&^y& +8`-W|_>M%oF$'q̢͸$8q#`*jUBt(]64@)xo#gOܐp6 uyThs0a3zɳ]Y`y.{wF<7O_)* y+*BL47@=G,DW57+nܸ[oӟ7߼~oaFC.zb?~ 1$BtVB1POh(zJaȚ޺eۺ{ >xnCG{ńokCd HJgJ;HY18gуkM˹E,~0ߛ txX|$y< !_Ai.V絝?9Q/!yB NB I]Ϣ<W◀fZ$ϒg!İ+4L/ζ1gs~ɳ- Mkq$;z;m,ܰ}NuU lnn`yrg&{aKboF?.=F1">3'ѿ@A-~0ز;˅7n܀1g\@Kd sY18 *iIENRSXEveO#Ix^3I LG~<[v9XӀ'w8yr-1>~;Ĉ?aSq\eqGu[h3Hӻ5J&qM3oG`J@$^h@y\sRvKτS O$Mnh Zƴ[n!:\,$B]h@^FS,8ÔlՊ1Se2Z?G?Lm㨈q/XX$[X A4P2hLa ln!< !gyv}`)  X{2FhhOLhL4؍~}8JT4g!pX'áq~. ~ \őx&sY18ȳWaDKyk/p=<. 8Q:]kL9qT&0;mK(0ch%y 9GWBc[k#yB $ PQ?X]68R3=FN<h"Cċ{ MXwM,=sIp/+8IIl6.x24NN##shĪ{ ɳbp&gclN,,. d(C4 ]r%>V|v5 L<Ædz/^tE?6n iG4p=C#/Ҁ' 4ν&1,Vy;9 񵌒ta6qxɒ9G, U;Qj=j4Ia8[㺷ׯ8 I#Æ'sBcF$qm!IWpk6C5YHN /^YBL D9G, yN@< !G,DW$B< ɳbp$BtE,g!fɢ3_Wϟ?o˄{Y,<9rʕ+ˏ>͛7&/!fY,<\v ˏ.]jYE,DW$Lrbs n}%g< ѕecǎ8q'H%C PECgfNXbЦy9@p\vkYqA< ѕ .@~a(ٳg,$Ϭbmd 5.t'O\byƩv=\eᡍI\ヅYa?o@,DW^|SΫz7òEv1¦\- -uWܕF=aF=83 g! gΜ9}4]]]}ꩧ׆ (1ѕ6j`*as],yNɣRMf5ɳ]YyFծӉIC%݌|:".?IH*u6E $a7n)8I q#phj#"/;-9⎒]&`A< m.+UC }ZsىC<1$H23@L$嬈Ө"҈ŝ.9n~06;lBh]XCsȮl`S>X[@N<WϤ,S*p10i3%fnruoh68w=-$BtegrTI Hxu=Ȁ#PzEnBqcFș{IVo(IѠe}$SÅ<5S8 ^ E!w-I<(7”rFVSI<[G@{I< ѕeg,~ Pq8 tMaj~5A1(V|J xoB!<08Cp;%(NSJ-x;&$.Dq0hЌ4# rWb<1 0(w,axbi!y+ ϗ/_>uիW9A}L*Q b{PXY"iJJAUhB@']O6}\Nhd#U4"2ೌ.syą<21֚V%~Nϭ.b,`8CQ_z8u$BteIyuu… 5ԯIR{/ģ"ZJ'9<=S;9@#\QMa$8EbʉG寰 ą9a~h4!wN<`о!ۆ=/>Fyw~nkSD,DWASyA$yn(5Lvnv<O&8Dh$zP,m݉1:τp~N ą'9"Z3&ԝ| ϐm#8%|k!f?xZH2<|5 &hE<~s 4-1oA7LKv.ӆ #6.$!1~bGgI2N2%Ɣ-U$Yn9`Offt)?!h" 0qƻBCƒ⃘?xM`J̡byV0S1C&uE,DWXJ lG05}Ayڵ*!꩓/a%^y&k%8`-t/DɦX7|3Z&8\RL%aq461 ID¸ e٘s|,H9qAgϊuB,DWX({eb%/PzY$BteQYEd#y+g!wC=MB,DW$B Qb·!pp $BtE,ɳ]< !gR_9! ɳbp&g qgH3<CkWVV:u3 ! < !gBy>/^l]G,ɳbp&go@q-yˁY183-32LAq\zg:g,3d6_ikW yBY183t--5E.qQIr {_K1f9ɖPg,(p ܾ}d}w~_ݺu뗿͛7z-'X^zXBn2K.ڎY 򜀵B!Y!}JB+MヒK zJaȚ>%Hm-ϸ+M|LR~cMrbw$zN^DϘqb D'$B-Q#ݢֺ<c3UG:yF !:!yB N?y.ޤr -9ʆhY18NJ ϸ[,.~3FBY18`̮|W717 6~@)D{$B'P;׿o^])mI63Va-,遯gtm"(< !</g)"g!ysx!!yB K/eT݆̅Y18'gԑ< !gYYTy+\}ϟeB@,DWX9rʕU/裏'ڄSsQ'Hʵk /Uyҥkg!ɳ]< A18g! |ر'N<ӕg}-7+/ n<39y׿ʐ?q[oN;'X1"u7#EA!ɳ]YxypB={YL&𿱱6J Ԯ \,m^U^l fX<LY6 ba:ra|X#6? r49MF,DW^|SΫz6V1ErШm+X!{~uD13hE499pF&̜4<<O$ k_&A,DWAq9sӜrp寮>S} ժYH0;W Z˳keN@VylG7 0*1qĪ\/IBAfOJɳ]W3K :Ѧ5k!2m ȋo]__GMa {D.4¹FQp+N4`r:3f0F`6Č*Lfs֏`_q0_n'v];<N!y+g3@qLeX(j,H)Z40$4B#͡mX((#ۏnACE&ϰ8`p}Z&ٮ#:GSus<g 1NS؂㖻.tu yLMY,<} Pe4wQQʗ^ĸadbO*q"ucƋ/1}e>q}E@hs-1% cT-[$$ɐdS#x^N< W̬0q‡ 8F$nbE-yVč nH23.gSu.²U}MWjȤ$ĸ61.*lbS:KCca4еqb\] RhmB0K<\x(L!u|8gI_͡7&fCOI< ѕ7n,<_|ԩSW^T %:Z*)mn!0Y®x&Cj!fsk Hb>l1q]Tw,E+F$X ɱW`a>`49_n<1kCWNŝC,DW\~ .p*ZZ*,9 1m ,ԅƸ*Q911 e$L y^<1m4( BXKnwIV91ϐS XByFa-\Y@!..DMn+(`y{{{}}}PyF5) hQ#X=0X//yNb bcGDP"tMB%E'6~C ]8\˅0hdG \&(g!vH<SaMn+(`ɿx#)kh\%~iÛ0+MfMjU ,chd؜DWa $-Aǝ @ moncsx8N(`8=fNI WKPJ< O~‚T,ĮR \$y?(@E[]]e;q(2*#iSXIP mp AХ$ixNC۰ 7'#4ybve$Nx H t9 4g#2zHb9pl-wlrq'ܰfyHq_IN~#\((g!^dXeޖ7 i?埨X ߊr?Cɳ9x㺀JȿA_..B\}.Kvz*7"2L .)̉?9nooF=^Sh0ew.`/^ '(_E-vy:T% iOfjN' SU vO6XJʉ0S;~ <噪J5<w^|b=),m^\(u T]!J20M3k:C+y3J0S>5e!>#~\hoQMkjHm;cV@?XVLa[g@y5< !z7ͮlXB,%dU0is93J5u*,ب=ǡ$ sQ[(&v yBŅ9RşB,+c#Qh3f $B6eY^P!RB=&DsmvyRXMe+ Hmf.Gr˖K @a.j3噪 LeK $B} 3ȕ f96*ĢadUǸj[a8g!D[mn_&^!RB1v\I6mg!D[6M3U5XکYB,1c10j(VՕ!yBſƛfjsd/XbY;Te@aQVإUB,hKuƵpj%~ ʀ (Ĕ®":>h)~IENDB`
PNG  IHDRrsRGBgAMA a pHYsodtEXtSoftwarepaint.net 4.1.6N d$IDATx^\ו&&H/%"Cla#Pg;8w`,BsqD pN0 E"d:+&xsΛ%KR%3y'SYj}NsNuUZ{Wԩn_B!Ĝ!yB!ɳB1wHBC,Bg!b< !sY!;$B!!yB!ɳB1wHBC,~>bHp8g;@L6?f!Y$a6k1 Y11<v56v5` ɳabxk0#1m|k09;g! V؉`Fb`j9s,|w$BĴrXH/X c'^ic[̱ݑ< _&N3ηS˙c#yb`5L x f$o 3wG,~j;HL;L-gY01<v56v5Z ɳaƟxuD;hG0}o O>-vwG,~jؤHwN3#yҹs_<Zv?o]ݑ< _6)Wzth~1OYv54_bD`jٙ_?EvwG,~jؤL]_[H\|q]<qq=WM|k09;g! V&e|JcmHKlOԁ2u?:A~}g;7v5Z ɳa2]y% 7@\g|(ß:Gw[M?qFx݆;L-gYհI<|#}ܙϒG6~l;Χ<Q=s:hKso 3wG,~jؤLSo} S[Ђ?L Ϸί}O][}i㉇ُ? ]~=ͯ>Y}ډ`F=i;_ԗ_~dcCxg14G&W;s9GB.٣|O?ō˽SԲ^5{`#yb`57v3C=>uN|??-Ϸ^}YH3kk_<L8xg{>O}TU71{a'^Ah)<']|6y&ϯoٹ=}ّ&|9_KGF*}Z.`jٕ_?궅Yհl=zϾb =&[gOl.m<o&Z~; (ǁg~}wn޹ш]=]a;̨5&o%h|lk_$v\Y~;gfyƫ%8zyYڗGj^14a[eW^ޑm+;g! Vp; }G+m>zWXw ߶iO_y噑h3[/T~W_~Z3:]d|yF+Zc[ebPk} m<6ĸg0'cv%?Q-n~|?|N3j(]<3ϞFy~3 噏ѿk?牱ݑ< _*ß9PGoeWw8w㗹vnm'R;oJ;ۗ7_-Z ϟ:R}^{_yaswv&Ϸ6G<s<pߩ뇝o 3wG,~jDzݴ(?N?yϠ|ܜxϖUjzЉͧG%ilN3jM+ywn+^ t|swnXw~gLF=ת햝_ /{^?sRnuyu{_oo 3wG,~jؤzOLt<d8BپR~ 9;9Nǎh갣+{O=؃P'8R{k04;[o6zKӟ79e';5kp ?ŵ?'n)Gpbb:{zeƑj;L-gYհyF-j>y<;G{c3wukO< ]֝Boc?{쫽x fԚVƹ'ZcO&p3&数TGp<5y&Nlݺ[f876|`>H`jBփwnwt7^0$WOx fԚ<W#{]>3ηSˮB հ\n>1[N3j}Ā ^?stt}|}`jByţ?sVkO|oƎibk0#1m|k09;g! V=׎7?qsO<kM؉`Fb`j9s,|w$BĴrXH/X oČĴ Y (2Lj0#1m|k0- vuG,~Du2FLj0#1m|k0-g!J` 6v5\F..H/vT7Ê0AĴu`Lg`ak$BLl`:<o6v5~ΐD]-< _Luaj0X]_&5L_ud9`nH/BWhLwX~F`3[ Aco~_CbWZ7eF$B+!,.w!h`Lpx8t3G,ÊGՕ fB4+ȯW1$B;X٨r#-˦. -yBjFf'h.^;jВg!aբE5__N\8x5ʲˬ2$BV**XAXMXYPb>#3BN?< !FX[5,yvBBKMήͿZ\8мx%Waɳb[g1k!DkpP tf< !RyfHY !Z 'Qh^_«;HXmnQJ\Qb>C[ h .*4Pb< ߱ڰۭ|` qy yb_cŢN}[#h .\>Eg_< Pb!ybH}P6ʇ~!Z N𺳋P,p*3oQYp ypp$_%FugYXUg$l׿5BU&yBbUgg[,Dp.6;%BǪB y}BY 5?x< ʳ,IX=6K.mu(yBֹN_K.~;/ۼx٥(yB5:j׶ٖ !ZKI,hɳ G,Ճyww]f}!ɳ3VgBfO%b < !:c`7yM7I&+WXBoݺe$b <"< !b`<%@,Ճ3@W,<-yB4a`n<߾}&~8N SR ɳ3Vf.hCwQ."3u>JDpr)ɳ3Vf"=zG Tk -uN ,Cnj-< !:c`wlS}9R.p.QP,A^`K8bZHz07)E534,~>4f>HHz0Ϟ!~GvrDy [|;gBgb8$BX=<s DyD<g/-Hz0syOFՉ$%bcxLK(՜[,< !:c`/䙃ʘ<(U.hpMSD,ՃYYg!C,ɳ!yBtY< !:c@,`Hz yb0$BX=< 1g!DgH ɳ3V$B Yg!C,ɳ!yBtY< !:c@,`Hz yb0$BX=< 1g!DgH ɳ3V$B Yg!C,ɳ!yBtY< !:c@,`Hz yb0$BX=< 1g!DgH ɳ3V$B Yg!C,ɳ!yBtY< !:c``y}w5b< !:c`&򼶶f^H_tkB,g!Dg\:$bё< !:c` Е<Y{t ݄׮]lh{ta_"Ɠ7ɱ6b< !:c`6ZwʮhĻg %9L_.Ğ#yBtL7$RoEyz.vs$BX=3ۮ `%(8A(B9s-S1g. ֋A$wh=uY6g[N-ba],ͨ (%~@t8<ϡC㘅M1̅<o!ĂX&ܾ}{n|+;<:~FXk b`u:3W]|Fyػq6B777NĻ(hCېɳ`<!<\]QDߎ<'Y~ T :y8,aoCB{ i!2`<DՂ9Nsf-&B-4paNn]Qb}]V¯J 1WTt0/OٵAyەՅROf'栂N !\׸<VLg?-2#yH< ! ԔwyK ZPavBqf!϶B,#/vPavBL噾]# ! ߪZFg[WA_N/*41S!ʳ-#:兊0} !\Rh!:1#yD͒g!أB[EB QÀl+*ڵZJ%P\Y !f#t~Ϭ +3h/B3of4k!E7Bd(y6>C[ X^~_;.*Ndfy 3go!{ ͺ ]ILB{g:meik˭[~B' 8 < !G,DWg.(ψFP { ϼuFl\lk $_Ca< 3#y;s6b!_7J%B<֙mkˋ3nwI}3O[#X^n޼)y{ %B(ϠD˓˳VPYLyf$~f@yJz)3g\=]-ϟ?o˄{?_Fq6'!3g@<#-ȑ#W\Y]]@_~GQ&kkkL<%B4򼲲r5HK/K.=O) yboqY,1Ν;{tg{CBLyg}<[oeCBL__ ǎ;qēO>9<#ǣ"x}p}!}Mƞ3sWNx:W1&1$ qaSp*WLqࢠPpuLAg.`?y-v SW=g<_pCϞ=(f1%yf!kSV%eCx` :fX<Li6x&OⓄ? mhXH`>`{qL)n73q>~jC?%~Z\ 7_9,*3ڛ=|ryWVJ\#gF14Fm23>uq@2ׯ_θ(fѰN@<iF2s&T<*~ 7͐|;mގ9"y2E^y3gΜ>}S>SkC]:9BL 3g?RH˜\؎*gAݓUDW1k$VzI 4S|mܹS\sKy1Hemɳ[ ,%OhjO^4k!7ή# KǐX\ ֯5Ggs'8!h?0Ϝ뮻`V hƗQErlNQL1+6 m=?C t'g_^i?&(ɟ__P}6QYu'o&f* PE;T:Ƃ%>Kc`FlGCۀD7,D9}6D!" lglnn `ez0F-l:9`3G @ )lq]::R<FI&ayPAWDx+_~Ϟ1YWSGssq*^xɳxL~`,<} Pe4N)FbՋ2zG;-R:mbSIYg_$9O6R#X0v<Nb%I@ I60q<yYaAqINŴ[AdS-ϰoMC\NY1<@t]#<']!tgSu. @fWjȤ$\ c61ȩ ]UYᡱAĸsro1y.)Bqնb Um%P<O&ڐA>I3$R D|/l'$r¤ z3oMg"NH]gw˧Nz*"e(1K$9'U-vs0P 1D]O@2{h6=hdA;2c)X1"ZxH[ !UϡBt噏)_*r*GLZ$IWq6JH)'۩<^pSԚ`K*,sOGL%Ϋ0\?H]h{ (EO3ϖ`0 _{8!Ҡ"XXa.Q%Yd<CN,O`  7NypC(O9RA8O q \)`<)j3XyƉϭ<X=ic8^ M?^X4 c ;.E`'ϵ-(.WՅKNmR-$AL%p a Ɏho+9g@&R3ߦl]tР7b0]m s0,r)y7e+L0<4̒.*byKo4N2l?~[N666AvP<E0mXh#xsná<%'w@1pNo^ P X‡rWINH?yU V<&ω,ryXڿ(QKԵ,<D8%EXIPPķХP8L'䡋 @mXSy AC<1a˗=8i$#1J<C4\l$ZFI,'DyMN!8:X,\)+9I'йrW<&FPgvQiq<{Yw 8H'K/V!\2 {oŴNOTG,&ľeQyi^U8?ś91c$BtEǠHAu\r@df/}YHz[{SYڼHY18g!"yB YH#y+g!HY18g!"yB YH#y+g!HY18g!"yB NB#ľE,ɳ]< !G,DW$B< ɳbp$BtE,ɳ]< !G,DW$B< ɳbp$BtE,B,#yB NB#ľeQ{衇jw}y[& $Bteȑ#W\Y]]@_~Go޼6X[[eB@,DWXWVV]}饗0rҥi8$B-g!"y1:t?/Ĵ< ѕecǎ8q'Hs>D>i`Цwc㡇gyW7&= qaqɟ{F,DW^/\y~ᇡgϞE<cy^<KyK!9r,Ylm<7 ɟ$'_K-'n1b԰||6H3ڛ=|ryWV2Jʛk(FHMX(yAׯ_θ4PtAݓ;.ly!3g2g!eg<sӧ9 SO=6I!cL ]5q=ypQAtqaU5/%g! Je1a=y+Ҭp8p[+SkI஼jgs'8!h?IibLmnn9Yw ]k,(:A8/tѿYc!.tЕ< (,<<N$bA"hB´)KH2lGCۀD7,D}6D!G lD3 ٍ'o&ۡ{ \ӏIX#,0;nB88$BteggI^vsP8XOX^1^ 60l(ρ4c7T Oݱ$9ԥI68E?"7vO< WS, B` n`NOŴgY,<ggT$ t^ 9'z&M rBGWUcixbY6190DwG~1bG]a9m,tbGWu'dΑ'(fR D~a< ѕe˗/:uիfY/ ,yIT<Y®r&C$U3Xcn_r }}Cq ͊I>(֯ȏ`a>a20+&wмBt%B, K"ϫ.\TUX;k%u 9'Ssj $ R[U(Vm5qc2~D ++|yh4d|61ĘpݙDxX$;m0ƚ1g! 򼽽>JRB#Ŵ1X/DgXIb bMb4Nq ]ga&~8EPF#h$Yܻwr! $B, s0ʨHɻ,|_]x!v#yh%\7U ,chd؜\qΓ7 d]O/&7٘j >B,ʓ!+;63=fOΤy@QЖH3AI4**CmM_ [-P7Pe5p x9NC۰j 0'sZ:O gt}Ucʏx fpuy<UqALa*>m2vG!n$A:X"ybQX`yv-i{z!`X <u ԞDĠHʢH;9THy- tEb*o$Β(ove_-g!"ycp +m5Mai,< ɳbp$BtE,3?d$/<`zK, g!+40K>:i 9~mP, ɳbp&MC!DzWݕ<%@,is>RdByH^!yB δ+yɳbp%r6?>\t1U<c<uU,< !gZvoS))+++.j)[̅>(V"yB $\ݦOR8Y!ψm_1]$BDlGu('lt봑g $yC yB EsqY Y18Sg!IJ"P'Z3Zt`dY Y18ӒgP;nTDJ¤ h_9],@,i3"'g^B777ѠҌSPMd!U֧<Y Y18SgdRYI/^%l 6ZGIg и~:~JHӻo< !G,DW$B< ɳbp$BtE,ɳ]YTyߟl>-Bg!|ȑ+Wnll/?7oDp $!1g!򼲲r5H/ҥKS@,"y+} '!B,DWA;vĉ'|r yFǏGE/ BaA!Nl픳]W"gS|:aO.;DcmH~ p|Y,<_pCϞ=(f1%yfe+"&gN <WEȟ];8yNC-C=*Y,<s'W_}`J~WX I^gs`?' Z&K^19ǥ$'8|<n=ƟNh,tѥǠ1bLH%< ѕeg<sӧ9 SO=6I٭"A:ũ4CHT#,EƓÉu>$QF%Bteua=y+kdN):N]__G8O<tR8I2K3cmq*& O>ԥ x ق䱸|26I"n&NpƱ$?S=D{,&=80G4c$Bte%ňԍw"uԕ?XFRDgi ` G!ۑ$4a0 SD %ڢ<zN" i'S)5d 07oDnZrup_\:cqn <XwĢOPpfH2sg*n=bƺ`uz2h>9IpU' zBp܉$p \s`y]U̱/>{$xYra\|kLN#xpN< W`ѱs`9И `H23|?{PIuARO@^jzU` aZ,^!?F3ɍ v`Y|͑$ iH*?bXJ'YDӆ1beyAKiON~2ʷC ɳ]Yy|S^ʩ*TRzP9B<D.08O녛 Ih8.~4bgAT#vvlH/x֯hHSQ69 h0,)f>_LYOCxDG,DWDWWW/\j\]9nϮԕ?$$L%k+vBCbi=ʲ0$2isp識6O!j=zp`CBOL'4~2D)̐< ѕe,•|l1m s'gsk(XOaϮ+pWAb܆S 4d۰G2o $q8":G'wDaI|J4g>$BteyοU)y7e `VT<440Fo| :sIe5r Ѐ;tW zC6\ӿԝWE.d]uXb$;7"n T| 2C>c$>[8O΄ x d mlK&G,DW3y8n߾Hy_Wn/yͷzuJPVWWَ`mk",s z%φoVNnmmN/ t|O fb?_t]@(,v4l?:G eKbhhJBΣAq"@1'F)p$2ɳ]>B%PL&wť=RdMq ^QGXz{Tanar"vrT~IpO@,DWUށI$:> ^MYH u7pCL@Gtv“כ!y+=u }^|bWvXRG'?g!"yB YH#yK'X8G<b< !gBy%Y㌽[SgZk(#yB $_,<Cy.Z\D, %vՉyIv-< !<vxk +gьY18Ar0 =CUE#ܲBD¢ *31va?l' f=UIi' yMO$b@9?Iv"@(#yB N?y6FוDeрЦHxׅ @O(!U Ĵ.Lg3'(]wE\KWSO>uL5` ɳbpP)ÒԼ0ICatK'l'1)i,Zxi+ka lIh@~8I)f^57sbCyN\BnO%f܃r %Q~Ģ% [B 7qa3&rmܲqwT|mSˍY18XWsK<2&J6 3q=*^h;yNt<e\op0nm.pN1nrbh绦;T[%F,~Laxl慈=UJ @H0NoquIPEI-Eyㄩ"7lb|`N%)&k.IޒˊY18|tXhWDT1ˑ\EQ`|ISs&jp> 6dbd 4MbnCwZu1:ɳbpz3,Q͓Ꜽɉ#\wlBP*ۑ/-Lf 7n/}Q|pҕ3$S캷AݒGGd؍G]E;!Í ӭ):gmWÙ,g!gB%Hȕ[[[Q$Ҽ0 Md`UL!q1p.$GB–,hس@}4Mwg6:Hw6WJmg!L(9.9IbrGɳbp.bx7bo< !G< CE-g!H֞+$B< ѕEg,|o2!^ y+ ,k=3/ر7|m)2!^ y+PEÇ?~_ȞS@,"y+ N&9ED,DWAWVVj yF/}Kmd YO?Ob|HG>]#q~^Q+] VꦆC,DW^oOB_|E2)3]ꌒį|+K,8ծKyF\!#-ItBg+ᡌ_7,Tl<=E$Btb3Νosʹp u*c+DŽ̃<|GI|?g~xE=FAˍسY,"z-}g/ u6Qq*x{쫁JYwJOGIQ&<@zS<ax63C,DWp.<t֕솩,h?1IH}QYcO{up hOe&F|6zt'i8acvۦb%A7e\ƹsګh#ZLQnܸ' ;0UDlzpw 9 y+Z^ZRIx'$)|EXPXaoC.JvfVXw<О'/±Fk $Ӄ ,9`g1 k(I|0O6qbMUAsN\$90wӧ3OACNeL'188$BtWsg2Y=XFA8`2P 2-9W)7 ?^?Ɠ`P)4um}ܲnÎg7Ycy-II!;$BtW32.~ P8FXŔF#zpXcLb/ Sh##f1'wnEw?x;mN*0t(xtIz]z+ro0 \T# cn m,OUݓS-GPg!u'STϤfNڗNŴF^aU ).tBaKػZ|_"l FdVhx{s'm9=w{NK'Ƈ8,f:y.f^ q$X\ ɳ]պ 3|[TUekN׆XsF^b5@7gJ.CsG6UP"wn3gѥV맑Ga LyJj{N2/%..jfH օW>}z>kK'AIn)wtcuy2!B*`lNy&cLN2c6e84-*b9Il~~#`$z#Ecn!ɳ]պ<_ C>A\/XX7c-1oA7LKv.ӆb+l`>1"'vq$C %6y$vYOcw̲~Z?tY!V4y<ο. Y`VZm,EE'=< \*%e< CmM_P`ՁXz(sNjA(y&2lP7q6A9 [0F0}&,lj~hd$A](m3(*NAr`H)"BbЈlƘM< $DFwODKPwtApu~"y+ZU*b%"F Od2< ѕEg!& ﭧE~[,$BtE, _ףdNۄT< ѕl2k!.ŏ>%.NSxG$|h}Q1fx6HJF,hYH3y~z街^zsƜ'ɳbp=wلD`$'<ÿ{1\zbY< !gyԥK8ɳ$B<G&АE$B<KEW$BH1eHuf?8ڀܛ7֚]wEE0Cڵk6D==17`UI\)D,=g!L]9@{ʊet"7ػ>asݸ*Fb< !gytE(T.c֯I8ZF1= br <2!2<'I079E%%mp4Ӑ^rṶLĒ!yB t8ޠEA?0<c!@~&b< !g 073mK䙱ruWyD\,7g!L]]_ *n+,rM$x;Q@L!;Qa#Fb!yB jn<7N.ms`.1&RL&1blllH3<C"d<q:94\xcEQ,1ߪDNebz (R2R-ɳbpz@{f(Qɳbp$BtE,ɳ]< !G,DW$Bgyb>YTy ^"c#w}mb/< ѕ#G\reuu/?7oDp J!%g!򼲲rWW[.]J~wS@,"y+ N&9ED,DWA;vĉ'|r yFǏ1d?Oм1{yN·tzt`<ڛ/hHl˯(Oɳ]YxypB={QbJ̺FPw%Nv<X3Z?Ɩ#h?KCy<%qh y+ /honn>s)W_=X?I2a6Qi1L0R {bV|̣'y!y+ y̙ӧOsAէz qm ^mdNx6jR֝R% 1y]ɞlM,DWAQJvT{Z%u0~f|߱A­c)Z 注$ ƍ<О`Ll01N&0qq !M_0KKnt:j0Kǔbt̾v$bNL>9t< ѕeg2R7 8I \/QN=W]s%`mVRw<О'/,XFkaS]?=2|QK 4l'ԋY%9t=(L$94Qg<g3%f=%v$v]`<@4Cp< y+ u=6NDp+/IktڈK9E{]O}CYO-+>~~n۰8,N_c~Nh9H+֑lʣ8-Lɳ]Yyg5(z]/ t Q hDX?\FG<(b2N#@#&` {3T[9t(xtIz]z+ꦪc!blDIw9R=qF07DA m$ytU[8b< ѕe˗/:uիb&p%=(,,4rnAhB@']O6}\`hTd#U4"Puo$ҰMY<gtu )<4e֥o[{3 bҋ y+K"ϫ.\TN{iR?Xi!M왒!FXIrR,l B)Euf\ϢKoEMB.FDzIqΓS7z8$Btey{{{}}}>kK$r fStcy2!B#W*`lNy&clƸ F0]O1 ḽx,_l<!y+ 0X8b6m/ ,0.)L6"D/ظ b*qy&:BDixk$%ΓYv4AE0,IzLenqhIEs(X|_0Ɂ~vr$Bte$ڰvPn[E/au /aE&^y& +8`-W|_>M%oF$'q̢͸$8q#`*jUBt(]64@)xo#gOܐp6 uyThs0a3zɳ]Y`y.{wF<7O_)* y+*BL47@=G,DW57+nܸ[oӟ7߼~oaFC.zb?~ 1$BtVB1POh(zJaȚ޺eۺ{ >xnCG{ńokCd HJgJ;HY18gуkM˹E,~0ߛ txX|$y< !_Ai.V絝?9Q/!yB NB I]Ϣ<W◀fZ$ϒg!İ+4L/ζ1gs~ɳ- Mkq$;z;m,ܰ}NuU lnn`yrg&{aKboF?.=F1">3'ѿ@A-~0ز;˅7n܀1g\@Kd sY18 *iIENRSXEveO#Ix^3I LG~<[v9XӀ'w8yr-1>~;Ĉ?aSq\eqGu[h3Hӻ5J&qM3oG`J@$^h@y\sRvKτS O$Mnh Zƴ[n!:\,$B]h@^FS,8ÔlՊ1Se2Z?G?Lm㨈q/XX$[X A4P2hLa ln!< !gyv}`)  X{2FhhOLhL4؍~}8JT4g!pX'áq~. ~ \őx&sY18ȳWaDKyk/p=<. 8Q:]kL9qT&0;mK(0ch%y 9GWBc[k#yB $ PQ?X]68R3=FN<h"Cċ{ MXwM,=sIp/+8IIl6.x24NN##shĪ{ ɳbp&gclN,,. d(C4 ]r%>V|v5 L<Ædz/^tE?6n iG4p=C#/Ҁ' 4ν&1,Vy;9 񵌒ta6qxɒ9G, U;Qj=j4Ia8[㺷ׯ8 I#Æ'sBcF$qm!IWpk6C5YHN /^YBL D9G, yN@< !G,DW$B< ɳbp$BtE,g!fɢ3_Wϟ?o˄{Y,<9rʕ+ˏ>͛7&/!fY,<\v ˏ.]jYE,DW$Lrbs n}%g< ѕecǎ8q'H%C PECgfNXbЦy9@p\vkYqA< ѕ .@~a(ٳg,$Ϭbmd 5.t'O\byƩv=\eᡍI\ヅYa?o@,DW^|SΫz7òEv1¦\- -uWܕF=aF=83 g! gΜ9}4]]]}ꩧ׆ (1ѕ6j`*as],yNɣRMf5ɳ]YyFծӉIC%݌|:".?IH*u6E $a7n)8I q#phj#"/;-9⎒]&`A< m.+UC }ZsىC<1$H23@L$嬈Ө"҈ŝ.9n~06;lBh]XCsȮl`S>X[@N<WϤ,S*p10i3%fnruoh68w=-$BtegrTI Hxu=Ȁ#PzEnBqcFș{IVo(IѠe}$SÅ<5S8 ^ E!w-I<(7”rFVSI<[G@{I< ѕeg,~ Pq8 tMaj~5A1(V|J xoB!<08Cp;%(NSJ-x;&$.Dq0hЌ4# rWb<1 0(w,axbi!y+ ϗ/_>uիW9A}L*Q b{PXY"iJJAUhB@']O6}\Nhd#U4"2ೌ.syą<21֚V%~Nϭ.b,`8CQ_z8u$BteIyuu… 5ԯIR{/ģ"ZJ'9<=S;9@#\QMa$8EbʉG寰 ą9a~h4!wN<`о!ۆ=/>Fyw~nkSD,DWASyA$yn(5Lvnv<O&8Dh$zP,m݉1:τp~N ą'9"Z3&ԝ| ϐm#8%|k!f?xZH2<|5 &hE<~s 4-1oA7LKv.ӆ #6.$!1~bGgI2N2%Ɣ-U$Yn9`Offt)?!h" 0qƻBCƒ⃘?xM`J̡byV0S1C&uE,DWXJ lG05}Ayڵ*!꩓/a%^y&k%8`-t/DɦX7|3Z&8\RL%aq461 ID¸ e٘s|,H9qAgϊuB,DWX({eb%/PzY$BteQYEd#y+g!wC=MB,DW$B Qb·!pp $BtE,ɳ]< !gR_9! ɳbp&g qgH3<CkWVV:u3 ! < !gBy>/^l]G,ɳbp&go@q-yˁY183-32LAq\zg:g,3d6_ikW yBY183t--5E.qQIr {_K1f9ɖPg,(p ܾ}d}w~_ݺu뗿͛7z-'X^zXBn2K.ڎY 򜀵B!Y!}JB+MヒK zJaȚ>%Hm-ϸ+M|LR~cMrbw$zN^DϘqb D'$B-Q#ݢֺ<c3UG:yF !:!yB N?y.ޤr -9ʆhY18NJ ϸ[,.~3FBY18`̮|W717 6~@)D{$B'P;׿o^])mI63Va-,遯gtm"(< !</g)"g!ysx!!yB K/eT݆̅Y18'gԑ< !gYYTy+\}ϟeB@,DWX9rʕU/裏'ڄSsQ'Hʵk /Uyҥkg!ɳ]< A18g! |ر'N<ӕg}-7+/ n<39y׿ʐ?q[oN;'X1"u7#EA!ɳ]YxypB={YL&𿱱6J Ԯ \,m^U^l fX<LY6 ba:ra|X#6? r49MF,DW^|SΫz6V1ErШm+X!{~uD13hE499pF&̜4<<O$ k_&A,DWAq9sӜrp寮>S} ժYH0;W Z˳keN@VylG7 0*1qĪ\/IBAfOJɳ]W3K :Ѧ5k!2m ȋo]__GMa {D.4¹FQp+N4`r:3f0F`6Č*Lfs֏`_q0_n'v];<N!y+g3@qLeX(j,H)Z40$4B#͡mX((#ۏnACE&ϰ8`p}Z&ٮ#:GSus<g 1NS؂㖻.tu yLMY,<} Pe4wQQʗ^ĸadbO*q"ucƋ/1}e>q}E@hs-1% cT-[$$ɐdS#x^N< W̬0q‡ 8F$nbE-yVč nH23.gSu.²U}MWjȤ$ĸ61.*lbS:KCca4еqb\] RhmB0K<\x(L!u|8gI_͡7&fCOI< ѕ7n,<_|ԩSW^T %:Z*)mn!0Y®x&Cj!fsk Hb>l1q]Tw,E+F$X ɱW`a>`49_n<1kCWNŝC,DW\~ .p*ZZ*,9 1m ,ԅƸ*Q911 e$L y^<1m4( BXKnwIV91ϐS XByFa-\Y@!..DMn+(`y{{{}}}PyF5) hQ#X=0X//yNb bcGDP"tMB%E'6~C ]8\˅0hdG \&(g!vH<SaMn+(`ɿx#)kh\%~iÛ0+MfMjU ,chd؜DWa $-Aǝ @ moncsx8N(`8=fNI WKPJ< O~‚T,ĮR \$y?(@E[]]e;q(2*#iSXIP mp AХ$ixNC۰ 7'#4ybve$Nx H t9 4g#2zHb9pl-wlrq'ܰfyHq_IN~#\((g!^dXeޖ7 i?埨X ߊr?Cɳ9x㺀JȿA_..B\}.Kvz*7"2L .)̉?9nooF=^Sh0ew.`/^ '(_E-vy:T% iOfjN' SU vO6XJʉ0S;~ <噪J5<w^|b=),m^\(u T]!J20M3k:C+y3J0S>5e!>#~\hoQMkjHm;cV@?XVLa[g@y5< !z7ͮlXB,%dU0is93J5u*,ب=ǡ$ sQ[(&v yBŅ9RşB,+c#Qh3f $B6eY^P!RB=&DsmvyRXMe+ Hmf.Gr˖K @a.j3噪 LeK $B} 3ȕ f96*ĢadUǸj[a8g!D[mn_&^!RB1v\I6mg!D[6M3U5XکYB,1c10j(VՕ!yBſƛfjsd/XbY;Te@aQVإUB,hKuƵpj%~ ʀ (Ĕ®":>h)~IENDB`
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/EditorFeatures/Test2/IntelliSense/CSharpSignatureHelpCommandHandlerTests.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.CSharp Imports Microsoft.CodeAnalysis.Editor.Options Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class CSharpSignatureHelpCommandHandlerTests <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestCreateAndDismiss(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Goo() { Goo$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo()") state.SendTypeChars(")") Await state.AssertNoSignatureHelpSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TypingUpdatesParameters(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Goo(int i, string j) { Goo$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo(int i, string j)", selectedParameter:="int i") state.SendTypeChars("1,") Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo(int i, string j)", selectedParameter:="string j") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TypingChangeParameterByNavigating(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Goo(int i, string j) { Goo(1$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(",") Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo(int i, string j)", selectedParameter:="string j") state.SendLeftKey() Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo(int i, string j)", selectedParameter:="int i") state.SendRightKey() Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo(int i, string j)", selectedParameter:="string j") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function NavigatingOutOfSpanDismissesSignatureHelp(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Goo() { Goo($$) } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeSignatureHelp() Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo()") state.SendRightKey() Await state.AssertNoSignatureHelpSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestNestedCalls(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Bar() { } void Goo() { Goo$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo()") state.SendTypeChars("Bar(") Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Bar()") state.SendTypeChars(")") Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo()") End Using End Function <WorkItem(544547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544547")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestNoSigHelpOnGenericNamespace(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace global::F$$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("<") Await state.AssertNoSignatureHelpSession() End Using End Function <WorkItem(544547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544547")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestSigHelpOnExtraSpace(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class G&lt;S, T&gt; { }; class C { void Goo() { G&lt;int, $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeSignatureHelp() Await state.AssertSignatureHelpSession() End Using End Function <WorkItem(544551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544551")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestFilterOnNamedParameters1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { public void M(int first, int second) { } public void M(int third) { } } class Program { void Main() { new C().M(first$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeSignatureHelp() Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M(int third)") Assert.Equal(2, state.GetSignatureHelpItems().Count) state.SendTypeChars(":") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M(int first, int second)") Assert.Equal(1, state.GetSignatureHelpItems().Count) ' Now both items are available again, and we're sticking with last selection state.SendBackspace() Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M(int first, int second)") Assert.Equal(2, state.GetSignatureHelpItems().Count) End Using End Function <WorkItem(545488, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545488")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestUseBestOverload(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { static void Main(string[] args) { F$$ } static void F(int i) { } static void F(string s) { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) ' We don't have a definite symbol, so default to first state.SendTypeChars("(") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void Program.F(int i)") Assert.Equal(2, state.GetSignatureHelpItems().Count) Assert.Equal({"void Program.F(int i)", "void Program.F(string s)"}, state.GetSignatureHelpItems().Select(Function(i) i.ToString())) ' We now have a definite symbol (the string overload) state.SendTypeChars("""""") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void Program.F(string s)") Assert.Equal(2, state.GetSignatureHelpItems().Count) ' We stick with the last selection after deleting state.SendBackspace() state.SendBackspace() Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void Program.F(string s)") Assert.Equal(2, state.GetSignatureHelpItems().Count) ' We now have a definite symbol (the int overload) state.SendTypeChars("1") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void Program.F(int i)") Assert.Equal(2, state.GetSignatureHelpItems().Count) End Using End Function <WorkItem(545488, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545488")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestForgetSelectedItemWhenNoneAreViable(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { static void Main(string[] args) { F$$ } static void F(int i) { } static void F(string s) { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) ' We don't have a definite symbol, so default to first state.SendTypeChars("(") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void Program.F(int i)") Assert.Equal(2, state.GetSignatureHelpItems().Count) Assert.Equal({"void Program.F(int i)", "void Program.F(string s)"}, state.GetSignatureHelpItems().Select(Function(i) i.ToString())) ' We now have a definite symbol (the string overload) state.SendTypeChars("""""") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void Program.F(string s)") Assert.Equal(2, state.GetSignatureHelpItems().Count) ' We don't have a definite symbol again, so we stick with last selection state.SendTypeChars(",") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void Program.F(string s)") Assert.Equal(2, state.GetSignatureHelpItems().Count) End Using End Function <WorkItem(691648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/691648")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestKeepUserSelectedItem(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { M$$ } void M(int i) { } void M(int i, int j) { } void M(int i, int j, int k) { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M()") Assert.Equal(4, state.GetSignatureHelpItems().Count) If showCompletionInArgumentLists Then Await state.AssertCompletionSession() state.SendEscape() End If state.SendUpKey() Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j, int k)") state.SendTypeChars("1") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j, int k)") state.SendTypeChars(",") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j, int k)") state.SendTypeChars("2,") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j, int k)") End Using End Function <WorkItem(691648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/691648")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestKeepUserSelectedItem2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { M$$ } void M(int i) { } void M(int i, int j) { } void M(int i, string x) { } void M(int i, int j, int k) { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M()") Assert.Equal(5, state.GetSignatureHelpItems().Count) state.SendTypeChars("1, ") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j)") If showCompletionInArgumentLists Then Await state.AssertCompletionSession() state.SendEscape() End If state.SendDownKey() Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)") state.SendTypeChars("1") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)") End Using End Function <WorkItem(691648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/691648")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestKeepUserSelectedItem3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { M$$ } void M(int i) { } void M(int i, int j) { } void M(int i, string x) { } void M(int i, int j, int k) { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M()") Assert.Equal(5, state.GetSignatureHelpItems().Count) state.SendTypeChars("1, """" ") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)") state.SendUpKey() Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j)") state.SendTypeChars(",") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j, int k)") state.SendBackspace() Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)") End Using End Function <WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestPathIndependent(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { M$$ } void M(int i) { } void M(int i, int j) { } void M(int i, string x) { } void M(int i, int j, int k) { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M()") Assert.Equal(5, state.GetSignatureHelpItems().Count) Assert.Equal({"void C.M()", "void C.M(int i)", "void C.M(int i, int j)", "void C.M(int i, string x)", "void C.M(int i, int j, int k)"}, state.GetSignatureHelpItems().Select(Function(i) i.ToString())) state.SendTypeChars("1") Await state.AssertSelectedSignatureHelpItem("void C.M(int i)") state.SendTypeChars(",") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j)") state.SendTypeChars(" ""a"" ") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)") End Using End Function <WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestPathIndependent2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { M$$ } void M(int i) { } void M(int i, int j) { } void M(int i, string x) { } void M(int i, int j, int k) { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M()") Assert.Equal(5, state.GetSignatureHelpItems().Count) Assert.Equal({"void C.M()", "void C.M(int i)", "void C.M(int i, int j)", "void C.M(int i, string x)", "void C.M(int i, int j, int k)"}, state.GetSignatureHelpItems().Select(Function(i) i.ToString())) state.SendTypeChars("1, ""a"" ") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)") End Using End Function <WorkItem(819063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819063")> <WorkItem(843508, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843508")> <WorkItem(636117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636117")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestSessionMaintainedDuringIndexerErrorToleranceTransition(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { void M(int x) { string s = "Test"; s$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("[") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("char string[int index]") state.SendTypeChars("x") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("char string[int index]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestSigHelpInLinkedFiles(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"> class C { void M() { M2($$); } #if Proj1 void M2(int x) { } #endif #if Proj2 void M2(string x) { } #endif } </Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim documents = state.Workspace.Documents Dim linkDocument = documents.Single(Function(d) d.IsLinkFile) state.SendInvokeSignatureHelp() Await state.AssertSelectedSignatureHelpItem("void C.M2(int x)") state.SendEscape() state.Workspace.SetDocumentContext(linkDocument.Id) state.SendInvokeSignatureHelp() Await state.AssertSelectedSignatureHelpItem("void C.M2(string x)") End Using End Function <WorkItem(1060850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1060850")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestSigHelpNotDismissedAfterQuote(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { } void M(string s) { M($$); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeSignatureHelp() Await state.AssertSelectedSignatureHelpItem("void C.M()") state.SendTypeChars("""") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M(string s)") End Using End Function <WorkItem(1060850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1060850")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestSigHelpDismissedAfterComment(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { } void M(string s) { M($$); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeSignatureHelp() Await state.AssertSelectedSignatureHelpItem("void C.M()") state.SendTypeChars("//") Await state.AssertNoSignatureHelpSession() End Using End Function <WorkItem(1598, "https://github.com/dotnet/roslyn/issues/1598")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestGenericNameSigHelpInTypeParameterListAfterConditionalAccess(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Collections; using System.Collections.Generic; using System.Linq; class C { void M(object[] args) { var x = args?.OfType$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("<") Await state.AssertSelectedSignatureHelpItem($"({CSharpFeaturesResources.extension}) IEnumerable<TResult> IEnumerable.OfType<TResult>()") End Using End Function <WorkItem(1598, "https://github.com/dotnet/roslyn/issues/1598")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestGenericNameSigHelpInTypeParameterListAfterMultipleConditionalAccess(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Collections; using System.Collections.Generic; using System.Linq; class C { void M(object[] args) { var x = args?.Select(a => a)?.OfType$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("<") Await state.AssertSelectedSignatureHelpItem($"({CSharpFeaturesResources.extension}) IEnumerable<TResult> IEnumerable.OfType<TResult>()") End Using End Function <WorkItem(1598, "https://github.com/dotnet/roslyn/issues/1598")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestGenericNameSigHelpInTypeParameterListMuchAfterConditionalAccess(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Collections; using System.Collections.Generic; using System.Linq; class C { void M(object[] args) { var x = args?.Select(a => a).Where(_ => true).OfType$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("<") Await state.AssertSelectedSignatureHelpItem($"({CSharpFeaturesResources.extension}) IEnumerable<TResult> IEnumerable.OfType<TResult>()") End Using End Function <WorkItem(1598, "https://github.com/dotnet/roslyn/issues/1598")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestGenericNameSigHelpInTypeParameterListAfterConditionalAccessAndNullCoalesce(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Collections; using System.Collections.Generic; using System.Linq; class C { void M(object[] args) { var x = (args ?? args)?.OfType$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("<") Await state.AssertSelectedSignatureHelpItem($"({CSharpFeaturesResources.extension}) IEnumerable<TResult> IEnumerable.OfType<TResult>()") End Using End Function <WorkItem(5174, "https://github.com/dotnet/roslyn/issues/5174")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function DontShowSignatureHelpIfOptionIsTurnedOffUnlessExplicitlyInvoked(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void M(int i) { M$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) ' disable implicit sig help then type a trigger character -> no session should be available Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(SignatureHelpOptions.ShowSignatureHelp, "C#", False))) state.SendTypeChars("(") Await state.AssertNoSignatureHelpSession() ' force-invoke -> session should be available state.SendInvokeSignatureHelp() Await state.AssertSignatureHelpSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function MixedTupleNaming(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Goo() { (int, int x) t = (5$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(",") Await state.AssertSelectedSignatureHelpItem(displayText:="(int, int x)", selectedParameter:="int x") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function ParameterSelectionWhileParsedAsParenthesizedExpression(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Goo() { (int a, string b) x = (b$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeSignatureHelp() Await state.AssertSelectedSignatureHelpItem(displayText:="(int a, string b)", selectedParameter:="int a") End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CSharp Imports Microsoft.CodeAnalysis.Editor.Options Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class CSharpSignatureHelpCommandHandlerTests <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestCreateAndDismiss(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Goo() { Goo$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo()") state.SendTypeChars(")") Await state.AssertNoSignatureHelpSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TypingUpdatesParameters(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Goo(int i, string j) { Goo$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo(int i, string j)", selectedParameter:="int i") state.SendTypeChars("1,") Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo(int i, string j)", selectedParameter:="string j") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TypingChangeParameterByNavigating(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Goo(int i, string j) { Goo(1$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(",") Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo(int i, string j)", selectedParameter:="string j") state.SendLeftKey() Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo(int i, string j)", selectedParameter:="int i") state.SendRightKey() Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo(int i, string j)", selectedParameter:="string j") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function NavigatingOutOfSpanDismissesSignatureHelp(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Goo() { Goo($$) } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeSignatureHelp() Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo()") state.SendRightKey() Await state.AssertNoSignatureHelpSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestNestedCalls(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Bar() { } void Goo() { Goo$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo()") state.SendTypeChars("Bar(") Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Bar()") state.SendTypeChars(")") Await state.AssertSelectedSignatureHelpItem(displayText:="void C.Goo()") End Using End Function <WorkItem(544547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544547")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestNoSigHelpOnGenericNamespace(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace global::F$$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("<") Await state.AssertNoSignatureHelpSession() End Using End Function <WorkItem(544547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544547")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestSigHelpOnExtraSpace(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class G&lt;S, T&gt; { }; class C { void Goo() { G&lt;int, $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeSignatureHelp() Await state.AssertSignatureHelpSession() End Using End Function <WorkItem(544551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544551")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestFilterOnNamedParameters1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { public void M(int first, int second) { } public void M(int third) { } } class Program { void Main() { new C().M(first$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeSignatureHelp() Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M(int third)") Assert.Equal(2, state.GetSignatureHelpItems().Count) state.SendTypeChars(":") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M(int first, int second)") Assert.Equal(1, state.GetSignatureHelpItems().Count) ' Now both items are available again, and we're sticking with last selection state.SendBackspace() Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M(int first, int second)") Assert.Equal(2, state.GetSignatureHelpItems().Count) End Using End Function <WorkItem(545488, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545488")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestUseBestOverload(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { static void Main(string[] args) { F$$ } static void F(int i) { } static void F(string s) { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) ' We don't have a definite symbol, so default to first state.SendTypeChars("(") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void Program.F(int i)") Assert.Equal(2, state.GetSignatureHelpItems().Count) Assert.Equal({"void Program.F(int i)", "void Program.F(string s)"}, state.GetSignatureHelpItems().Select(Function(i) i.ToString())) ' We now have a definite symbol (the string overload) state.SendTypeChars("""""") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void Program.F(string s)") Assert.Equal(2, state.GetSignatureHelpItems().Count) ' We stick with the last selection after deleting state.SendBackspace() state.SendBackspace() Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void Program.F(string s)") Assert.Equal(2, state.GetSignatureHelpItems().Count) ' We now have a definite symbol (the int overload) state.SendTypeChars("1") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void Program.F(int i)") Assert.Equal(2, state.GetSignatureHelpItems().Count) End Using End Function <WorkItem(545488, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545488")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestForgetSelectedItemWhenNoneAreViable(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { static void Main(string[] args) { F$$ } static void F(int i) { } static void F(string s) { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) ' We don't have a definite symbol, so default to first state.SendTypeChars("(") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void Program.F(int i)") Assert.Equal(2, state.GetSignatureHelpItems().Count) Assert.Equal({"void Program.F(int i)", "void Program.F(string s)"}, state.GetSignatureHelpItems().Select(Function(i) i.ToString())) ' We now have a definite symbol (the string overload) state.SendTypeChars("""""") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void Program.F(string s)") Assert.Equal(2, state.GetSignatureHelpItems().Count) ' We don't have a definite symbol again, so we stick with last selection state.SendTypeChars(",") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void Program.F(string s)") Assert.Equal(2, state.GetSignatureHelpItems().Count) End Using End Function <WorkItem(691648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/691648")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestKeepUserSelectedItem(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { M$$ } void M(int i) { } void M(int i, int j) { } void M(int i, int j, int k) { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M()") Assert.Equal(4, state.GetSignatureHelpItems().Count) If showCompletionInArgumentLists Then Await state.AssertCompletionSession() state.SendEscape() End If state.SendUpKey() Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j, int k)") state.SendTypeChars("1") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j, int k)") state.SendTypeChars(",") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j, int k)") state.SendTypeChars("2,") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j, int k)") End Using End Function <WorkItem(691648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/691648")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestKeepUserSelectedItem2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { M$$ } void M(int i) { } void M(int i, int j) { } void M(int i, string x) { } void M(int i, int j, int k) { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M()") Assert.Equal(5, state.GetSignatureHelpItems().Count) state.SendTypeChars("1, ") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j)") If showCompletionInArgumentLists Then Await state.AssertCompletionSession() state.SendEscape() End If state.SendDownKey() Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)") state.SendTypeChars("1") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)") End Using End Function <WorkItem(691648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/691648")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestKeepUserSelectedItem3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { M$$ } void M(int i) { } void M(int i, int j) { } void M(int i, string x) { } void M(int i, int j, int k) { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M()") Assert.Equal(5, state.GetSignatureHelpItems().Count) state.SendTypeChars("1, """" ") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)") state.SendUpKey() Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j)") state.SendTypeChars(",") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j, int k)") state.SendBackspace() Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)") End Using End Function <WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestPathIndependent(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { M$$ } void M(int i) { } void M(int i, int j) { } void M(int i, string x) { } void M(int i, int j, int k) { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M()") Assert.Equal(5, state.GetSignatureHelpItems().Count) Assert.Equal({"void C.M()", "void C.M(int i)", "void C.M(int i, int j)", "void C.M(int i, string x)", "void C.M(int i, int j, int k)"}, state.GetSignatureHelpItems().Select(Function(i) i.ToString())) state.SendTypeChars("1") Await state.AssertSelectedSignatureHelpItem("void C.M(int i)") state.SendTypeChars(",") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, int j)") state.SendTypeChars(" ""a"" ") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)") End Using End Function <WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestPathIndependent2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { M$$ } void M(int i) { } void M(int i, int j) { } void M(int i, string x) { } void M(int i, int j, int k) { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M()") Assert.Equal(5, state.GetSignatureHelpItems().Count) Assert.Equal({"void C.M()", "void C.M(int i)", "void C.M(int i, int j)", "void C.M(int i, string x)", "void C.M(int i, int j, int k)"}, state.GetSignatureHelpItems().Select(Function(i) i.ToString())) state.SendTypeChars("1, ""a"" ") Await state.AssertSelectedSignatureHelpItem("void C.M(int i, string x)") End Using End Function <WorkItem(819063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819063")> <WorkItem(843508, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843508")> <WorkItem(636117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636117")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestSessionMaintainedDuringIndexerErrorToleranceTransition(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { void M(int x) { string s = "Test"; s$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("[") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("char string[int index]") state.SendTypeChars("x") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("char string[int index]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestSigHelpInLinkedFiles(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"> class C { void M() { M2($$); } #if Proj1 void M2(int x) { } #endif #if Proj2 void M2(string x) { } #endif } </Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim documents = state.Workspace.Documents Dim linkDocument = documents.Single(Function(d) d.IsLinkFile) state.SendInvokeSignatureHelp() Await state.AssertSelectedSignatureHelpItem("void C.M2(int x)") state.SendEscape() state.Workspace.SetDocumentContext(linkDocument.Id) state.SendInvokeSignatureHelp() Await state.AssertSelectedSignatureHelpItem("void C.M2(string x)") End Using End Function <WorkItem(1060850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1060850")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestSigHelpNotDismissedAfterQuote(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { } void M(string s) { M($$); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeSignatureHelp() Await state.AssertSelectedSignatureHelpItem("void C.M()") state.SendTypeChars("""") Await state.AssertSignatureHelpSession() Await state.AssertSelectedSignatureHelpItem("void C.M(string s)") End Using End Function <WorkItem(1060850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1060850")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestSigHelpDismissedAfterComment(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { } void M(string s) { M($$); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeSignatureHelp() Await state.AssertSelectedSignatureHelpItem("void C.M()") state.SendTypeChars("//") Await state.AssertNoSignatureHelpSession() End Using End Function <WorkItem(1598, "https://github.com/dotnet/roslyn/issues/1598")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestGenericNameSigHelpInTypeParameterListAfterConditionalAccess(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Collections; using System.Collections.Generic; using System.Linq; class C { void M(object[] args) { var x = args?.OfType$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("<") Await state.AssertSelectedSignatureHelpItem($"({CSharpFeaturesResources.extension}) IEnumerable<TResult> IEnumerable.OfType<TResult>()") End Using End Function <WorkItem(1598, "https://github.com/dotnet/roslyn/issues/1598")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestGenericNameSigHelpInTypeParameterListAfterMultipleConditionalAccess(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Collections; using System.Collections.Generic; using System.Linq; class C { void M(object[] args) { var x = args?.Select(a => a)?.OfType$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("<") Await state.AssertSelectedSignatureHelpItem($"({CSharpFeaturesResources.extension}) IEnumerable<TResult> IEnumerable.OfType<TResult>()") End Using End Function <WorkItem(1598, "https://github.com/dotnet/roslyn/issues/1598")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestGenericNameSigHelpInTypeParameterListMuchAfterConditionalAccess(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Collections; using System.Collections.Generic; using System.Linq; class C { void M(object[] args) { var x = args?.Select(a => a).Where(_ => true).OfType$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("<") Await state.AssertSelectedSignatureHelpItem($"({CSharpFeaturesResources.extension}) IEnumerable<TResult> IEnumerable.OfType<TResult>()") End Using End Function <WorkItem(1598, "https://github.com/dotnet/roslyn/issues/1598")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestGenericNameSigHelpInTypeParameterListAfterConditionalAccessAndNullCoalesce(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Collections; using System.Collections.Generic; using System.Linq; class C { void M(object[] args) { var x = (args ?? args)?.OfType$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("<") Await state.AssertSelectedSignatureHelpItem($"({CSharpFeaturesResources.extension}) IEnumerable<TResult> IEnumerable.OfType<TResult>()") End Using End Function <WorkItem(5174, "https://github.com/dotnet/roslyn/issues/5174")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function DontShowSignatureHelpIfOptionIsTurnedOffUnlessExplicitlyInvoked(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void M(int i) { M$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) ' disable implicit sig help then type a trigger character -> no session should be available Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(SignatureHelpOptions.ShowSignatureHelp, "C#", False))) state.SendTypeChars("(") Await state.AssertNoSignatureHelpSession() ' force-invoke -> session should be available state.SendInvokeSignatureHelp() Await state.AssertSignatureHelpSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function MixedTupleNaming(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Goo() { (int, int x) t = (5$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(",") Await state.AssertSelectedSignatureHelpItem(displayText:="(int, int x)", selectedParameter:="int x") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function ParameterSelectionWhileParsedAsParenthesizedExpression(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Goo() { (int a, string b) x = (b$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeSignatureHelp() Await state.AssertSelectedSignatureHelpItem(displayText:="(int a, string b)", selectedParameter:="int a") End Using End Function End Class End Namespace
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/CSharp/Test/Semantic/Semantics/PatternMatchingTests2.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.Patterns)] public class PatternMatchingTests2 : PatternMatchingTestBase { [Fact] public void Patterns2_00() { var source = @" using System; class Program { public static void Main() { Console.WriteLine(1 is int {} x ? x : -1); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"1"); } [Fact] public void Patterns2_01() { var source = @" using System; class Program { public static void Main() { Point p = new Point(); Check(true, p is Point(3, 4) { Length: 5 } q1 && Check(p, q1)); Check(false, p is Point(1, 4) { Length: 5 }); Check(false, p is Point(3, 1) { Length: 5 }); Check(false, p is Point(3, 4) { Length: 1 }); Check(true, p is (3, 4) { Length: 5 } q2 && Check(p, q2)); Check(false, p is (1, 4) { Length: 5 }); Check(false, p is (3, 1) { Length: 5 }); Check(false, p is (3, 4) { Length: 1 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } } public class Point { public void Deconstruct(out int X, out int Y) { X = 3; Y = 4; } public int Length => 5; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: ""); } [Fact] public void Patterns2_02() { var source = @" using System; class Program { public static void Main() { Point p = new Point(); Check(true, p is Point(3, 4) { Length: 5 } q1 && Check(p, q1)); Check(false, p is Point(1, 4) { Length: 5 }); Check(false, p is Point(3, 1) { Length: 5 }); Check(false, p is Point(3, 4) { Length: 1 }); Check(true, p is (3, 4) { Length: 5 } q2 && Check(p, q2)); Check(false, p is (1, 4) { Length: 5 }); Check(false, p is (3, 1) { Length: 5 }); Check(false, p is (3, 4) { Length: 1 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } } public class Point { public int Length => 5; } public static class PointExtensions { public static void Deconstruct(this Point p, out int X, out int Y) { X = 3; Y = 4; } } "; // We use a compilation profile that provides System.Runtime.CompilerServices.ExtensionAttribute needed for this test var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: ""); } [Fact] public void Patterns2_03() { var source = @" using System; class Program { public static void Main() { var p = (x: 3, y: 4); Check(true, p is (3, 4) q1 && Check(p, q1)); Check(false, p is (1, 4) { x: 3 }); Check(false, p is (3, 1) { y: 4 }); Check(false, p is (3, 4) { x: 1 }); Check(true, p is (3, 4) { x: 3 } q2 && Check(p, q2)); Check(false, p is (1, 4) { x: 3 }); Check(false, p is (3, 1) { x: 3 }); Check(false, p is (3, 4) { x: 1 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (9,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (1, 4) { x: 3 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (1, 4) { x: 3 }").WithArguments("(int x, int y)").WithLocation(9, 22), // (10,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (3, 1) { y: 4 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 1) { y: 4 }").WithArguments("(int x, int y)").WithLocation(10, 22), // (11,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (3, 4) { x: 1 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 4) { x: 1 }").WithArguments("(int x, int y)").WithLocation(11, 22), // (13,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (1, 4) { x: 3 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (1, 4) { x: 3 }").WithArguments("(int x, int y)").WithLocation(13, 22), // (15,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (3, 4) { x: 1 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 4) { x: 1 }").WithArguments("(int x, int y)").WithLocation(15, 22) ); } [Fact] public void Patterns2_04b() { var source = @" using System; class Program { public static void Main() { var p = (x: 3, y: 4); Check(true, p is (3, 4) q1 && Check(p, q1)); Check(true, p is (3, 4) { x: 3 } q2 && Check(p, q2)); Check(false, p is (3, 1) { x: 3 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: ""); } [Fact] public void Patterns2_DiscardPattern_01() { var source = @" using System; class Program { public static void Main() { Point p = new Point(); Check(true, p is Point(_, _) { Length: _ } q1 && Check(p, q1)); Check(false, p is Point(1, _) { Length: _ }); Check(false, p is Point(_, 1) { Length: _ }); Check(false, p is Point(_, _) { Length: 1 }); Check(true, p is (_, _) { Length: _ } q2 && Check(p, q2)); Check(false, p is (1, _) { Length: _ }); Check(false, p is (_, 1) { Length: _ }); Check(false, p is (_, _) { Length: 1 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } } public class Point { public void Deconstruct(out int X, out int Y) { X = 3; Y = 4; } public int Length => 5; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: ""); } [Fact] public void Patterns2_Switch01() { var sourceTemplate = @" class Program {{ public static void Main() {{ var p = (true, false); switch (p) {{ {0} {1} {2} case (_, _): // error - subsumed break; }} }} }}"; void testErrorCase(string s1, string s2, string s3) { var source = string.Format(sourceTemplate, s1, s2, s3); var compilation = CreatePatternCompilation(source); compilation.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 (_, _): // error - subsumed Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "(_, _)").WithLocation(12, 18) ); } void testGoodCase(string s1, string s2) { var source = string.Format(sourceTemplate, s1, s2, string.Empty); var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); } var c1 = "case (true, _):"; var c2 = "case (false, false):"; var c3 = "case (_, true):"; testErrorCase(c1, c2, c3); testErrorCase(c2, c3, c1); testErrorCase(c3, c1, c2); testErrorCase(c1, c3, c2); testErrorCase(c3, c2, c1); testErrorCase(c2, c1, c3); testGoodCase(c1, c2); testGoodCase(c1, c3); testGoodCase(c2, c3); testGoodCase(c2, c1); testGoodCase(c3, c1); testGoodCase(c3, c2); } [Fact] public void Patterns2_Switch02() { var source = @" class Program { public static void Main() { Point p = new Point(); switch (p) { case Point(3, 4) { Length: 5 }: System.Console.WriteLine(true); break; default: System.Console.WriteLine(false); break; } } } public class Point { public void Deconstruct(out int X, out int Y) { X = 3; Y = 4; } public int Length => 5; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: "True"); } [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 switch (i) { case default: break; } // error 3 switch (i) { case default when true: break; } // error 4 switch ((1, 2)) { case (1, default): break; } // error 5 if (i is < default) {} // error 6 switch (i) { case < default: break; } // error 7 if (i is < ((default))) {} // error 8 switch (i) { case < ((default)): break; } // error 9 if (i is default!) {} // error 10 if (i is (default!)) {} // error 11 if (i is < ((default)!)) {} // error 12 if (i is default!!) {} // error 13 if (i is (default!!)) {} // error 14 if (i is < ((default)!!)) {} // error 15 // These are not accepted by the parser. See https://github.com/dotnet/roslyn/issues/45387 if (i is (default)!) {} // error 16 if (i is ((default)!)) {} // error 17 } }"; var compilation = CreatePatternCompilation(source); 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,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 3 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(8, 27), // (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 when true: break; } // error 4 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(9, 27), // (10,36): 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 ((1, 2)) { case (1, default): break; } // error 5 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(10, 36), // (12,20): 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 6 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(12, 20), // (13,29): 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 7 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(13, 29), // (14,22): 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 8 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(14, 22), // (15,31): 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 9 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(15, 31), // (17,18): error CS8598: The suppression operator is not allowed in this context // if (i is default!) {} // error 10 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(17, 18), // (17,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 10 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(17, 18), // (18,19): error CS8598: The suppression operator is not allowed in this context // if (i is (default!)) {} // error 11 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(18, 19), // (18,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 11 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(18, 19), // (19,21): error CS8598: The suppression operator is not allowed in this context // if (i is < ((default)!)) {} // error 12 Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!").WithLocation(19, 21), // (19,22): 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 12 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(19, 22), // (20,18): error CS8598: The suppression operator is not allowed in this context // if (i is default!!) {} // error 13 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!!").WithLocation(20, 18), // (20,18): error CS8598: The suppression operator is not allowed in this context // if (i is default!!) {} // error 13 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(20, 18), // (20,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 13 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(20, 18), // (21,19): error CS8598: The suppression operator is not allowed in this context // if (i is (default!!)) {} // error 14 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!!").WithLocation(21, 19), // (21,19): error CS8598: The suppression operator is not allowed in this context // if (i is (default!!)) {} // error 14 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(21, 19), // (21,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 14 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(21, 19), // (22,21): error CS8598: The suppression operator is not allowed in this context // if (i is < ((default)!!)) {} // error 15 Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!!").WithLocation(22, 21), // (22,21): error CS8598: The suppression operator is not allowed in this context // if (i is < ((default)!!)) {} // error 15 Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!").WithLocation(22, 21), // (22,22): error CS8715: Duplicate null suppression operator ('!') // if (i is < ((default)!!)) {} // error 15 Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "default").WithLocation(22, 22), // (22,22): 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 15 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(22, 22), // (25,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 16 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(25, 19), // (25,27): error CS1026: ) expected // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_CloseParenExpected, "!").WithLocation(25, 27), // (25,28): error CS1525: Invalid expression term ')' // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(25, 28), // (25,28): error CS1002: ; expected // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(25, 28), // (25,28): error CS1513: } expected // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(25, 28), // (26,18): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'int', with 2 out parameters and a void return type. // if (i is ((default)!)) {} // error 17 Diagnostic(ErrorCode.ERR_MissingDeconstruct, "((default)!)").WithArguments("int", "2").WithLocation(26, 18), // (26,20): 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 17 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(26, 20), // (26,28): error CS1003: Syntax error, ',' expected // if (i is ((default)!)) {} // error 17 Diagnostic(ErrorCode.ERR_SyntaxError, "!").WithArguments(",", "!").WithLocation(26, 28), // (26,29): error CS1525: Invalid expression term ')' // if (i is ((default)!)) {} // error 17 Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(26, 29) ); } [Fact] public void SwitchExpression_01() { // test appropriate language version or feature flag var source = @"class Program { public static void Main() { var r = 1 switch { _ => 0, }; } }"; CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithoutRecursivePatterns).VerifyDiagnostics( // (5,17): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // var r = 1 switch { _ => 0, }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { _ => 0, }").WithArguments("recursive patterns", "8.0").WithLocation(5, 17) ); CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8).VerifyDiagnostics(); } [Fact] public void SwitchExpression_02() { // test switch expression's governing expression has no type // test switch expression's governing expression has type void var source = @"class Program { public static void Main() { var r1 = (1, null) switch { _ => 0 }; var r2 = System.Console.Write(1) switch { _ => 0 }; } }"; CreatePatternCompilation(source).VerifyDiagnostics( // (5,18): error CS8117: Invalid operand for pattern match; value required, but found '(int, <null>)'. // var r1 = (1, null) switch ( _ => 0 ); Diagnostic(ErrorCode.ERR_BadPatternExpression, "(1, null)").WithArguments("(int, <null>)").WithLocation(5, 18), // (6,18): error CS8117: Invalid operand for pattern match; value required, but found 'void'. // var r2 = System.Console.Write(1) switch ( _ => 0 ); Diagnostic(ErrorCode.ERR_BadPatternExpression, "System.Console.Write(1)").WithArguments("void").WithLocation(6, 18) ); } [Fact] public void SwitchExpression_03() { // test that a ternary expression is not at an appropriate precedence // for the constant expression of a constant pattern in a switch expression arm. var source = @"class Program { public static void Main() { bool b = true; var r1 = b switch { true ? true : true => true, false => false }; var r2 = b switch { (true ? true : true) => true, false => false }; } }"; // This is admittedly poor syntax error recovery (for the line declaring r2), // but this test demonstrates that it is a syntax error. CreatePatternCompilation(source).VerifyDiagnostics( // (6,34): error CS1003: Syntax error, '=>' expected // var r1 = b switch { true ? true : true => true, false => false }; Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments("=>", "?").WithLocation(6, 34), // (6,34): error CS1525: Invalid expression term '?' // var r1 = b switch { true ? true : true => true, false => false }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "?").WithArguments("?").WithLocation(6, 34), // (6,48): error CS1003: Syntax error, ',' expected // var r1 = b switch { true ? true : true => true, false => false }; Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(6, 48), // (6,48): error CS8504: Pattern missing // var r1 = b switch { true ? true : true => true, false => false }; Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(6, 48) ); } [Fact] public void SwitchExpression_04() { // test that a ternary expression is permitted as a constant pattern in recursive contexts and the case expression. var source = @"class Program { public static void Main() { var b = (true, false); var r1 = b switch { (true ? true : true, _) => true, _ => false, }; var r2 = b is (true ? true : true, _); switch (b.Item1) { case true ? true : true: break; } } }"; CreatePatternCompilation(source).VerifyDiagnostics( ); } [Fact] public void SwitchExpression_05() { // test throw expression in match arm. var source = @"class Program { public static void Main() { var x = 1 switch { 1 => 1, _ => throw null }; } }"; CreatePatternCompilation(source).VerifyDiagnostics( ); } [Fact] public void EmptySwitchExpression() { var source = @"class Program { public static void Main() { var r = 1 switch { }; } }"; CreatePatternCompilation(source).VerifyDiagnostics( // (5,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered. // var r = 1 switch { }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(5, 19), // (5,19): error CS8506: No best type was found for the switch expression. // var r = 1 switch { }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(5, 19)); } [Fact] public void SwitchExpression_06() { // test common type vs delegate in match expression var source = @"class Program { public static void Main() { var x = 1 switch { 0 => M, 1 => new D(M), 2 => M }; x(); } public static void M() {} public delegate void D(); }"; CreatePatternCompilation(source).VerifyDiagnostics( // (5,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '3' is not covered. // var x = 1 switch { 0 => M, 1 => new D(M), 2 => M }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("3").WithLocation(5, 19) ); } [Fact] public void SwitchExpression_07() { // test flow analysis of the switch expression var source = @"class Program { public static void Main() { int q = 1; int u; var x = q switch { 0 => u=0, 1 => u=1, _ => u=2 }; System.Console.WriteLine(u); } }"; CreatePatternCompilation(source).VerifyDiagnostics( ); } [Fact] public void SwitchExpression_08() { // test flow analysis of the switch expression var source = @"class Program { public static void Main() { int q = 1; int u; var x = q switch { 0 => u=0, 1 => 1, _ => u=2 }; System.Console.WriteLine(u); } static int M(int i) => i; }"; CreatePatternCompilation(source).VerifyDiagnostics( // (8,34): error CS0165: Use of unassigned local variable 'u' // System.Console.WriteLine(u); Diagnostic(ErrorCode.ERR_UseDefViolation, "u").WithArguments("u").WithLocation(8, 34) ); } [Fact] public void SwitchExpression_09() { // test flow analysis of the switch expression var source = @"class Program { public static void Main() { int q = 1; int u; var x = q switch { 0 => u=0, 1 => u=M(u), _ => u=2, }; System.Console.WriteLine(u); } static int M(int i) => i; }"; CreatePatternCompilation(source).VerifyDiagnostics( // (7,47): error CS0165: Use of unassigned local variable 'u' // var x = q switch { 0 => u=0, 1 => u=M(u), _ => u=2 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "u").WithArguments("u").WithLocation(7, 47) ); } [Fact] public void SwitchExpression_10() { // test lazily inferring variables in the pattern // test lazily inferring variables in the when clause // test lazily inferring variables in the arrow expression var source = @"class Program { public static void Main() { int a = 1; var b = a switch { var x1 => x1, }; var c = a switch { var x2 when x2 is var x3 => x3 }; var d = a switch { var x4 => x4 is var x5 ? x5 : 1, }; } static int M(int i) => i; }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): warning CS8846: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered. However, a pattern with a 'when' clause might successfully match this value. // var c = a switch { var x2 when x2 is var x3 => x3 }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveWithWhen, "switch").WithArguments("_").WithLocation(7, 19) ); var names = new[] { "x1", "x2", "x3", "x4", "x5" }; var tree = compilation.SyntaxTrees[0]; foreach (var designation in tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>()) { var model = compilation.GetSemanticModel(tree); var symbol = model.GetDeclaredSymbol(designation); Assert.Equal(SymbolKind.Local, symbol.Kind); Assert.Equal("int", ((ILocalSymbol)symbol).Type.ToDisplayString()); } foreach (var ident in tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>()) { var model = compilation.GetSemanticModel(tree); var typeInfo = model.GetTypeInfo(ident); Assert.Equal("int", typeInfo.Type.ToDisplayString()); } } [Fact] public void ShortDiscardInIsPattern() { // test that we forbid a short discard at the top level of an is-pattern expression var source = @"class Program { public static void Main() { int a = 1; if (a is _) { } } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // if (a is _) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(6, 18) ); } [Fact] public void Patterns2_04() { // Test that a single-element deconstruct pattern is an error if no further elements disambiguate. var source = @" using System; class Program { public static void Main() { var t = new System.ValueTuple<int>(1); if (t is (int x)) { } // error 1 switch (t) { case (_): break; } // error 2 var u = t switch { (int y) => y, _ => 2 }; // error 3 if (t is (int z1) _) { } // ok if (t is (Item1: int z2)) { } // ok if (t is (int z3) { }) { } // ok if (t is ValueTuple<int>(int z4)) { } // ok } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (8,18): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // if (t is (int x)) { } // error 1 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x)").WithArguments("parenthesized pattern", "9.0").WithLocation(8, 18), // (8,19): error CS8121: An expression of type 'ValueTuple<int>' cannot be handled by a pattern of type 'int'. // if (t is (int x)) { } // error 1 Diagnostic(ErrorCode.ERR_PatternWrongType, "int").WithArguments("System.ValueTuple<int>", "int").WithLocation(8, 19), // (9,27): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // switch (t) { case (_): break; } // error 2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(_)").WithArguments("parenthesized pattern", "9.0").WithLocation(9, 27), // (10,28): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // var u = t switch { (int y) => y, _ => 2 }; // error 3 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int y)").WithArguments("parenthesized pattern", "9.0").WithLocation(10, 28), // (10,29): error CS8121: An expression of type 'ValueTuple<int>' cannot be handled by a pattern of type 'int'. // var u = t switch { (int y) => y, _ => 2 }; // error 3 Diagnostic(ErrorCode.ERR_PatternWrongType, "int").WithArguments("System.ValueTuple<int>", "int").WithLocation(10, 29) ); } [Fact] public void Patterns2_05() { // Test parsing the var pattern // Test binding the var pattern // Test lowering the var pattern for the is-expression var source = @" using System; class Program { public static void Main() { var t = (1, 2); { Check(true, t is var (x, y) && x == 1 && y == 2); } { Check(false, t is var (x, y) && x == 1 && y == 3); } } private static void Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""Expected: '{expected}', Actual: '{actual}'""); } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @""); } [Fact] public void Patterns2_06() { // Test that 'var' does not bind to a type var source = @" using System; namespace N { class Program { public static void Main() { var t = (1, 2); { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1 { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2 { Check(true, t is var x); } // error 3 } private static void Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""Expected: '{expected}', Actual: '{actual}'""); } } class var { } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (9,21): error CS0029: Cannot implicitly convert type '(int, int)' to 'N.var' // var t = (1, 2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 2)").WithArguments("(int, int)", "N.var").WithLocation(9, 21), // (10,32): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here. // { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1 Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(10, 32), // (10,36): error CS1061: 'var' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'var' could be found (are you missing a using directive or an assembly reference?) // { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(x, y)").WithArguments("N.var", "Deconstruct").WithLocation(10, 36), // (10,36): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'var', with 2 out parameters and a void return type. // { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1 Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(x, y)").WithArguments("N.var", "2").WithLocation(10, 36), // (11,33): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here. // { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2 Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(11, 33), // (11,37): error CS1061: 'var' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'var' could be found (are you missing a using directive or an assembly reference?) // { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(x, y)").WithArguments("N.var", "Deconstruct").WithLocation(11, 37), // (11,37): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'var', with 2 out parameters and a void return type. // { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2 Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(x, y)").WithArguments("N.var", "2").WithLocation(11, 37), // (12,32): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here. // { Check(true, t is var x); } // error 3 Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(12, 32) ); } [Fact] public void Patterns2_10() { var source = @" using System; class Program { public static void Main() { Console.Write(M((false, false))); Console.Write(M((false, true))); Console.Write(M((true, false))); Console.Write(M((true, true))); } private static int M((bool, bool) t) { switch (t) { case (false, false): return 0; case (false, _): return 1; case (_, false): return 2; case var _: return 3; } } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"0123"); } [Fact] public void Patterns2_11() { var source = @" using System; class Program { public static void Main() { Console.Write(M((false, false))); Console.Write(M((false, true))); Console.Write(M((true, false))); Console.Write(M((true, true))); } private static int M((bool, bool) t) { switch (t) { case (false, false): return 0; case (false, _): return 1; case (_, false): return 2; case (true, true): return 3; case var _: return 4; } } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (20,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case var _: return 4; Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "var _").WithLocation(20, 18) ); } [Fact] public void Patterns2_12() { var source = @" using System; class Program { public static void Main() { Console.Write(M((false, false))); Console.Write(M((false, true))); Console.Write(M((true, false))); Console.Write(M((true, true))); } private static int M((bool, bool) t) { return t switch { (false, false) => 0, (false, _) => 1, (_, false) => 2, _ => 3 }; } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"0123"); } [Fact] public void SwitchArmSubsumed() { var source = @"public class X { public static void Main() { string s = string.Empty; string s2 = s switch { null => null, string t => t, ""foo"" => null }; } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,61): error CS8410: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match. // string s2 = s switch { null => null, string t => t, "foo" => null }; Diagnostic(ErrorCode.ERR_SwitchArmSubsumed, @"""foo""").WithLocation(6, 61) ); } [Fact] public void LongTuples() { var source = @"using System; public class X { public static void Main() { var t = (1, 2, 3, 4, 5, 6, 7, 8, 9); { Console.WriteLine(t is (_, _, _, _, _, _, _, _, var t9) ? t9 : 100); } switch (t) { case (_, _, _, _, _, _, _, _, var t9): Console.WriteLine(t9); break; } Console.WriteLine(t switch { (_, _, _, _, _, _, _, _, var t9) => t9 }); } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"9 9 9"); } [Fact] public void TypeCheckInPropertyPattern() { var source = @"using System; class Program2 { public static void Main() { object o = new Frog(1, 2); if (o is Frog(1, 2)) { Console.Write(1); } if (o is Frog { A: 1, B: 2 }) { Console.Write(2); } if (o is Frog(1, 2) { A: 1, B: 2, C: 3 }) { Console.Write(3); } if (o is Frog(9, 2) { A: 1, B: 2, C: 3 }) {} else { Console.Write(4); } if (o is Frog(1, 9) { A: 1, B: 2, C: 3 }) {} else { Console.Write(5); } if (o is Frog(1, 2) { A: 9, B: 2, C: 3 }) {} else { Console.Write(6); } if (o is Frog(1, 2) { A: 1, B: 9, C: 3 }) {} else { Console.Write(7); } if (o is Frog(1, 2) { A: 1, B: 2, C: 9 }) {} else { Console.Write(8); } } } class Frog { public object A, B; public object C => (int)A + (int)B; public Frog(object A, object B) => (this.A, this.B) = (A, B); public void Deconstruct(out object A, out object B) => (A, B) = (this.A, this.B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"12345678"); } [Fact] public void OvereagerSubsumption() { var source = @"class Program2 { public static int Main() => 0; public static void M(object o) { switch (o) { case (1, 2): break; case string s: break; } } } "; var compilation = CreateCompilationWithMscorlib45(source); // doesn't have ITuple // Two errors below instead of one due to https://github.com/dotnet/roslyn/issues/25533 compilation.VerifyDiagnostics( // (8,18): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // case (1, 2): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(1, 2)").WithArguments("object", "Deconstruct").WithLocation(8, 18), // (8,18): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 2 out parameters and a void return type. // case (1, 2): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(1, 2)").WithArguments("object", "2").WithLocation(8, 18) ); } [Fact] public void UnderscoreDeclaredAndDiscardPattern_01() { var source = @"class Program0 { static int Main() => 0; private const int _ = 1; bool M1(object o) => o is _; bool M2(object o) => o switch { 1 => true, _ => false }; } class Program1 { class _ {} bool M3(object o) => o is _; bool M4(object o) => o switch { 1 => true, _ => false }; } "; var expected = new[] { // (5,31): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // bool M1(object o) => o is _; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(5, 31), // (11,31): warning CS8513: The name '_' refers to the type 'Program1._', not the discard pattern. Use '@_' for the type, or 'var _' to discard. // bool M3(object o) => o is _; Diagnostic(ErrorCode.WRN_IsTypeNamedUnderscore, "_").WithArguments("Program1._").WithLocation(11, 31) }; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics(expected); compilation = CreateCompilation(source, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics(expected); expected = new[] { // (5,31): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // bool M1(object o) => o is _; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(5, 31), // (6,26): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // bool M2(object o) => o switch { 1 => true, _ => false }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "o switch { 1 => true, _ => false }").WithArguments("recursive patterns", "8.0").WithLocation(6, 26), // (12,26): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // bool M4(object o) => o switch { 1 => true, _ => false }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "o switch { 1 => true, _ => false }").WithArguments("recursive patterns", "8.0").WithLocation(12, 26) }; compilation = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics(expected); } [Fact] public void UnderscoreDeclaredAndDiscardPattern_02() { var source = @"class Program0 { static int Main() => 0; private const int _ = 1; } class Program1 : Program0 { bool M2(object o) => o switch { 1 => true, _ => false }; // ok, private member not inherited } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); } [Fact] public void UnderscoreDeclaredAndDiscardPattern_03() { var source = @"class Program0 { static int Main() => 0; protected const int _ = 1; } class Program1 : Program0 { bool M2(object o) => o switch { 1 => true, _ => false }; } class Program2 { bool _(object q) => true; bool M2(object o) => o switch { 1 => true, _ => false }; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); } [Fact] public void UnderscoreDeclaredAndDiscardPattern_04() { var source = @"using _ = System.Int32; class Program { static int Main() => 0; bool M2(object o) => o switch { 1 => true, _ => false }; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (1,1): hidden CS8019: Unnecessary using directive. // using _ = System.Int32; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using _ = System.Int32;").WithLocation(1, 1) ); } [Fact] public void EscapingUnderscoreDeclaredAndDiscardPattern_04() { var source = @"class Program0 { static int Main() => 0; private const int _ = 2; bool M1(object o) => o is @_; int M2(object o) => o switch { 1 => 1, @_ => 2, var _ => 3 }; } class Program1 { class _ {} bool M1(object o) => o is @_; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); } [Fact] public void ErroneousSwitchArmDefiniteAssignment() { // When a switch expression arm is erroneous, ensure that the expression is treated as unreachable (e.g. for definite assignment purposes). var source = @"class Program2 { public static int Main() => 0; public static void M(string s) { int i; int j = s switch { ""frog"" => 1, 0 => i, _ => 2 }; } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,41): error CS0029: Cannot implicitly convert type 'int' to 'string' // int j = s switch { "frog" => 1, 0 => i, _ => 2 }; Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "string").WithLocation(7, 41) ); } [Fact, WorkItem(9154, "https://github.com/dotnet/roslyn/issues/9154")] public void ErroneousIsPatternDefiniteAssignment() { var source = @"class Program2 { public static int Main() => 0; void Dummy(object o) {} void Test5() { Dummy((System.Func<object, object, bool>) ((o1, o2) => o1 is int x5 && o2 is int x5 && x5 > 0)); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (8,74): error CS0128: A local variable or function named 'x5' is already defined in this scope // o2 is int x5 && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(8, 74) ); } [Fact] public void ERR_IsPatternImpossible() { var source = @"class Program { public static void Main() { System.Console.WriteLine(""frog"" is string { Length: 4, Length: 5 }); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (5,34): error CS8415: An expression of type 'string' can never match the provided pattern. // System.Console.WriteLine("frog" is string { Length: 4, Length: 5 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, @"""frog"" is string { Length: 4, Length: 5 }").WithArguments("string").WithLocation(5, 34) ); } [Fact] public void WRN_GivenExpressionNeverMatchesPattern01() { var source = @"class Program { public static void Main() { System.Console.WriteLine(3 is 4); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (5,34): warning CS8416: The given expression never matches the provided pattern. // System.Console.WriteLine(3 is 4); Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "3 is 4").WithLocation(5, 34) ); } [Fact] public void WRN_GivenExpressionNeverMatchesPattern02() { var source = @"class Program { public static void Main() { const string s = null; System.Console.WriteLine(s is string { Length: 3 }); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,34): warning CS8416: The given expression never matches the provided pattern. // System.Console.WriteLine(s is string { Length: 3 }); Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "s is string { Length: 3 }").WithLocation(6, 34) ); } [Fact] public void DefiniteAssignmentForIsPattern01() { var source = @"class Program { public static void Main() { string s = 300.ToString(); System.Console.WriteLine(s is string { Length: int j }); System.Console.WriteLine(j); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,34): error CS0165: Use of unassigned local variable 'j' // System.Console.WriteLine(j); Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j").WithLocation(7, 34) ); } [Fact] public void DefiniteAssignmentForIsPattern02() { var source = @"class Program { public static void Main() { const string s = ""300""; System.Console.WriteLine(s is string { Length: int j }); System.Console.WriteLine(j); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns); compilation.VerifyDiagnostics(); var expectedOutput = @"True 3"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void DefiniteAssignmentForIsPattern03() { var source = @"class Program { public static void Main() { int j; const string s = null; if (s is string { Length: 3 }) { System.Console.WriteLine(j); } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,13): warning CS8416: The given expression never matches the provided pattern. // if (s is string { Length: 3 }) Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "s is string { Length: 3 }").WithLocation(7, 13) ); } [Fact] public void RefutableConstantPattern01() { var source = @"class Program { public static void Main() { int j; const int N = 3; const int M = 3; if (N is M) { } else { System.Console.WriteLine(j); } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (8,13): warning CS8417: The given expression always matches the provided constant. // if (N is M) Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "N is M").WithLocation(8, 13) ); } [Fact, WorkItem(25591, "https://github.com/dotnet/roslyn/issues/25591")] public void TupleSubsumptionError() { var source = @"class Program2 { public static void Main() { M(new Fox()); M(new Cat()); M(new Program2()); } static void M(object o) { switch ((o, 0)) { case (Fox fox, _): System.Console.Write(""Fox ""); break; case (Cat cat, _): System.Console.Write(""Cat""); break; } } } class Fox {} class Cat {} "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"Fox Cat"); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns01() { var source = @"class Program { static void Main() { switch (a: 1, b: 2) { case (c: 2, d: 3): // error: c and d not defined break; } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8416: The name 'c' does not identify tuple element 'Item1'. // case (c: 2, d: 3): // error: c and d not defined Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "c").WithArguments("c", "Item1").WithLocation(7, 19), // (7,25): error CS8416: The name 'd' does not identify tuple element 'Item2'. // case (c: 2, d: 3): // error: c and d not defined Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "d").WithArguments("d", "Item2").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns02() { var source = @"class Program { static void Main() { switch (a: 1, b: 2) { case (a: 2, a: 3): break; } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,25): error CS8416: The name 'a' does not identify tuple element 'Item2'. // case (a: 2, a: 3): Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "a").WithArguments("a", "Item2").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns03() { var source = @"class Program { static void Main() { switch (a: 1, b: 2) { case (a: 2, Item2: 3): System.Console.WriteLine(666); break; case (a: 1, Item2: 2): System.Console.WriteLine(111); break; } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"111"); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns04() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (c: 2, d: 3): break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); public void Deconstruct(out int a, out int b) => (a, b) = (A, B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8417: The name 'c' does not match the corresponding 'Deconstruct' parameter 'a'. // case (c: 2, d: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "c").WithArguments("c", "a").WithLocation(7, 19), // (7,25): error CS8417: The name 'd' does not match the corresponding 'Deconstruct' parameter 'b'. // case (c: 2, d: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "d").WithArguments("d", "b").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns05() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (c: 2, d: 3): break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); } static class Extensions { public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8417: The name 'c' does not match the corresponding 'Deconstruct' parameter 'a'. // case (c: 2, d: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "c").WithArguments("c", "a").WithLocation(7, 19), // (7,25): error CS8417: The name 'd' does not match the corresponding 'Deconstruct' parameter 'b'. // case (c: 2, d: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "d").WithArguments("d", "b").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns06() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (a: 2, a: 3): break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); public void Deconstruct(out int a, out int b) => (a, b) = (A, B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,25): error CS8417: The name 'a' does not match the corresponding 'Deconstruct' parameter 'b'. // case (a: 2, a: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "a").WithArguments("a", "b").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns07() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (a: 2, a: 3): break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); } static class Extensions { public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,25): error CS8417: The name 'a' does not match the corresponding 'Deconstruct' parameter 'b'. // case (a: 2, a: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "a").WithArguments("a", "b").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns08() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (a: 2, b: 3): System.Console.WriteLine(666); break; case (a: 1, b: 2): System.Console.WriteLine(111); break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); public void Deconstruct(out int a, out int b) => (a, b) = (A, B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"111"); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns09() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (a: 2, b: 3): System.Console.WriteLine(666); break; case (a: 1, b: 2): System.Console.WriteLine(111); break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); } static class Extensions { public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"111"); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns10() { var source = @"class Program { static void Main() { switch (a: 1, b: 2) { case (Item2: 1, 2): break; } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8416: The name 'Item2' does not identify tuple element 'Item1'. // case (Item2: 1, 2): Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "Item2").WithArguments("Item2", "Item1").WithLocation(7, 19) ); } [Fact] public void PropertyPatternMemberMissing01() { var source = @"class Program { static void Main(string[] args) { Blah b = null; if (b is Blah { X: int i }) { } } } class Blah { }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,25): error CS0117: 'Blah' does not contain a definition for 'X' // if (b is Blah { X: int i }) Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("Blah", "X").WithLocation(6, 25) ); } [Fact] public void PropertyPatternMemberMissing02() { var source = @"class Program { static void Main(string[] args) { Blah b = null; if (b is Blah { X: int i }) { } } } class Blah { public int X { set {} } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,25): error CS0154: The property or indexer 'Blah.X' cannot be used in this context because it lacks the get accessor // if (b is Blah { X: int i }) Diagnostic(ErrorCode.ERR_PropertyLacksGet, "X:").WithArguments("Blah.X").WithLocation(6, 25) ); } [Fact] public void PropertyPatternMemberMissing03() { var source = @"class Program { static void Main(string[] args) { Blah b = null; switch (b) { case Blah { X: int i }: break; } } } class Blah { }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (8,25): error CS0117: 'Blah' does not contain a definition for 'X' // case Blah { X: int i }: Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("Blah", "X").WithLocation(8, 25) ); } [Fact] public void PropertyPatternMemberMissing04() { var source = @"class Program { static void Main(string[] args) { Blah b = null; switch (b) { case Blah { X: int i }: break; } } } class Blah { public int X { set {} } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (8,25): error CS0154: The property or indexer 'Blah.X' cannot be used in this context because it lacks the get accessor // case Blah { X: int i }: Diagnostic(ErrorCode.ERR_PropertyLacksGet, "X:").WithArguments("Blah.X").WithLocation(8, 25) ); } [Fact] [WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")] [WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")] public void ConstantPatternVsUnconstrainedTypeParameter03() { var source = @"class C<T> { internal struct S { } static bool Test(S s) { return s is null; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (6,21): error CS0037: Cannot convert null to 'C<T>.S' because it is a non-nullable value type // return s is null; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("C<T>.S").WithLocation(6, 21) ); } [Fact] [WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")] [WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")] public void ConstantPatternVsUnconstrainedTypeParameter04() { var source = @"class C<T> { static bool Test(C<T> x) { return x is 1; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (5,21): error CS8121: An expression of type 'C<T>' cannot be handled by a pattern of type 'int'. // return x is 1; Diagnostic(ErrorCode.ERR_PatternWrongType, "1").WithArguments("C<T>", "int").WithLocation(5, 21) ); } [Fact] [WorkItem(20724, "https://github.com/dotnet/roslyn/issues/20724")] public void SpeculateWithNameConflict01() { var source = @"public class Class1 { int i = 1; public override int GetHashCode() => 1; public override bool Equals(object obj) { return obj is global::Class1 @class && this.i == @class.i; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( ); var tree = compilation.SyntaxTrees[0]; var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree); var returnStatement = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single(); Assert.Equal("return obj is global::Class1 @class && this.i == @class.i;", returnStatement.ToString()); var modifiedReturnStatement = (ReturnStatementSyntax)new RemoveAliasQualifiers().Visit(returnStatement); Assert.Equal("return obj is Class1 @class && this.i == @class.i;", modifiedReturnStatement.ToString()); var gotModel = model.TryGetSpeculativeSemanticModel(returnStatement.Location.SourceSpan.Start, modifiedReturnStatement, out var speculativeModel); Assert.True(gotModel); Assert.NotNull(speculativeModel); var typeInfo = speculativeModel.GetTypeInfo(modifiedReturnStatement.Expression); Assert.Equal(SpecialType.System_Boolean, typeInfo.Type.SpecialType); } /// <summary> /// Helper class to remove alias qualifications. /// </summary> class RemoveAliasQualifiers : CSharpSyntaxRewriter { public override SyntaxNode VisitAliasQualifiedName(AliasQualifiedNameSyntax node) { return node.Name; } } [Fact] [WorkItem(20724, "https://github.com/dotnet/roslyn/issues/20724")] public void SpeculateWithNameConflict02() { var source = @"public class Class1 { public override int GetHashCode() => 1; public override bool Equals(object obj) { return obj is global::Class1 @class; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( ); var tree = compilation.SyntaxTrees[0]; var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree); var returnStatement = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single(); Assert.Equal("return obj is global::Class1 @class;", returnStatement.ToString()); var modifiedReturnStatement = (ReturnStatementSyntax)new RemoveAliasQualifiers().Visit(returnStatement); Assert.Equal("return obj is Class1 @class;", modifiedReturnStatement.ToString()); var gotModel = model.TryGetSpeculativeSemanticModel(returnStatement.Location.SourceSpan.Start, modifiedReturnStatement, out var speculativeModel); Assert.True(gotModel); Assert.NotNull(speculativeModel); var typeInfo = speculativeModel.GetTypeInfo(modifiedReturnStatement.Expression); Assert.Equal(SpecialType.System_Boolean, typeInfo.Type.SpecialType); } [Fact] public void WrongArity() { var source = @"class Program { static void Main(string[] args) { Point p = new Point() { X = 3, Y = 4 }; if (p is Point()) { } } } class Point { public int X, Y; public void Deconstruct(out int X, out int Y) => (X, Y) = (this.X, this.Y); } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (6,23): error CS7036: There is no argument given that corresponds to the required formal parameter 'X' of 'Point.Deconstruct(out int, out int)' // if (p is Point()) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "()").WithArguments("X", "Point.Deconstruct(out int, out int)").WithLocation(6, 23), // (6,23): error CS8129: No suitable Deconstruct instance or extension method was found for type 'Point', with 0 out parameters and a void return type. // if (p is Point()) Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("Point", "0").WithLocation(6, 23) ); } [Fact] public void GetTypeInfo_01() { var source = @"class Program { static void Main(string[] args) { object o = null; Point p = null; if (o is Point(3, string { Length: 2 })) { } if (p is (_, { })) { } if (p is Point({ }, { }, { })) { } if (p is Point(, { })) { } } } class Point { public object X, Y; public void Deconstruct(out object X, out object Y) => (X, Y) = (this.X, this.Y); public Point(object X, object Y) => (this.X, this.Y) = (X, Y); } "; var expected = new[] { new { Source = "Point(3, string { Length: 2 })", Type = "System.Object", ConvertedType = "Point" }, new { Source = "3", Type = "System.Object", ConvertedType = "System.Int32" }, new { Source = "string { Length: 2 }", Type = "System.Object", ConvertedType = "System.String" }, new { Source = "2", Type = "System.Int32", ConvertedType = "System.Int32" }, new { Source = "(_, { })", Type = "Point", ConvertedType = "Point" }, new { Source = "_", Type = "System.Object", ConvertedType = "System.Object" }, new { Source = "{ }", Type = "System.Object", ConvertedType = "System.Object" }, new { Source = "Point({ }, { }, { })", Type = "Point", ConvertedType = "Point" }, new { Source = "{ }", Type = "?", ConvertedType = "?" }, new { Source = "{ }", Type = "?", ConvertedType = "?" }, new { Source = "{ }", Type = "?", ConvertedType = "?" }, new { Source = "Point(, { })", Type = "Point", ConvertedType = "Point" }, new { Source = "", Type = "System.Object", ConvertedType = "System.Object" }, new { Source = "{ }", Type = "System.Object", ConvertedType = "System.Object" }, }; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (10,24): error CS8504: Pattern missing // if (p is Point(, { })) { } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(10, 24), // (9,23): error CS1501: No overload for method 'Deconstruct' takes 3 arguments // if (p is Point({ }, { }, { })) { } Diagnostic(ErrorCode.ERR_BadArgCount, "({ }, { }, { })").WithArguments("Deconstruct", "3").WithLocation(9, 23), // (9,23): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'Point', with 3 out parameters and a void return type. // if (p is Point({ }, { }, { })) { } Diagnostic(ErrorCode.ERR_MissingDeconstruct, "({ }, { }, { })").WithArguments("Point", "3").WithLocation(9, 23) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); int i = 0; foreach (var pat in tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>()) { var typeInfo = model.GetTypeInfo(pat); var ex = expected[i++]; Assert.Equal(ex.Source, pat.ToString()); Assert.Equal(ex.Type, typeInfo.Type.ToTestDisplayString()); Assert.Equal(ex.ConvertedType, typeInfo.ConvertedType.ToTestDisplayString()); } Assert.Equal(expected.Length, i); } [Fact, WorkItem(26613, "https://github.com/dotnet/roslyn/issues/26613")] public void MissingDeconstruct_01() { var source = @"using System; public class C { public void M() { _ = this is (a: 1); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (4,21): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // _ = this is (a: 1); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(a: 1)").WithArguments("C", "Deconstruct").WithLocation(4, 21), // (4,21): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 1 out parameters and a void return type. // _ = this is (a: 1); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(a: 1)").WithArguments("C", "1").WithLocation(4, 21) ); } [Fact, WorkItem(26613, "https://github.com/dotnet/roslyn/issues/26613")] public void MissingDeconstruct_02() { var source = @"using System; public class C { public void M() { _ = this is C(a: 1); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (4,22): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // _ = this is C(a: 1); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(a: 1)").WithArguments("C", "Deconstruct").WithLocation(4, 22), // (4,22): error CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 1 out parameters and a void return type. // _ = this is C(a: 1); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(a: 1)").WithArguments("C", "1").WithLocation(4, 22) ); } [Fact] public void PatternTypeInfo_01() { var source = @" public class C { void M(T1 t1) { if (t1 is T2 (var t3, t4: T4 t4) { V5 : T6 t5 }) {} } } class T1 { } class T2 : T1 { public T5 V5 = null; public void Deconstruct(out T3 t3, out T4 t4) => throw null; } class T3 { } class T4 { } class T5 { } class T6 : T5 { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray(); Assert.Equal(4, patterns.Length); Assert.Equal("T2 (var t3, t4: T4 t4) { V5 : T6 t5 }", patterns[0].ToString()); var ti = model.GetTypeInfo(patterns[0]); Assert.Equal("T1", ti.Type.ToTestDisplayString()); Assert.Equal("T2", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("var t3", patterns[1].ToString()); ti = model.GetTypeInfo(patterns[1]); Assert.Equal("T3", ti.Type.ToTestDisplayString()); Assert.Equal("T3", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("T4 t4", patterns[2].ToString()); ti = model.GetTypeInfo(patterns[2]); Assert.Equal("T4", ti.Type.ToTestDisplayString()); Assert.Equal("T4", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("T6 t5", patterns[3].ToString()); ti = model.GetTypeInfo(patterns[3]); Assert.Equal("T5", ti.Type.ToTestDisplayString()); Assert.Equal("T6", ti.ConvertedType.ToTestDisplayString()); } [Fact] public void PatternTypeInfo_02() { var source = @" public class C { void M(object o) { if (o is Point(3, 4.0)) {} } } class Point { public void Deconstruct(out object o1, out System.IComparable o2) => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray(); Assert.Equal(3, patterns.Length); Assert.Equal("Point(3, 4.0)", patterns[0].ToString()); var ti = model.GetTypeInfo(patterns[0]); Assert.Equal("System.Object", ti.Type.ToTestDisplayString()); Assert.Equal("Point", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("3", patterns[1].ToString()); ti = model.GetTypeInfo(patterns[1]); Assert.Equal("System.Object", ti.Type.ToTestDisplayString()); Assert.Equal("System.Int32", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("4.0", patterns[2].ToString()); ti = model.GetTypeInfo(patterns[2]); Assert.Equal("System.IComparable", ti.Type.ToTestDisplayString()); Assert.Equal("System.Double", ti.ConvertedType.ToTestDisplayString()); } [Fact] public void PatternTypeInfo_03() { var source = @" public class C { void M(object o) { if (o is Point(3, 4.0) { Missing: Xyzzy }) {} if (o is Q7 t) {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0246: The type or namespace name 'Point' could not be found (are you missing a using directive or an assembly reference?) // if (o is Point(3, 4.0) { Missing: Xyzzy }) {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Point").WithArguments("Point").WithLocation(6, 18), // (6,43): error CS0103: The name 'Xyzzy' does not exist in the current context // if (o is Point(3, 4.0) { Missing: Xyzzy }) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "Xyzzy").WithArguments("Xyzzy").WithLocation(6, 43), // (7,18): error CS0246: The type or namespace name 'Q7' could not be found (are you missing a using directive or an assembly reference?) // if (o is Q7 t) {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Q7").WithArguments("Q7").WithLocation(7, 18) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray(); Assert.Equal(5, patterns.Length); Assert.Equal("Point(3, 4.0) { Missing: Xyzzy }", patterns[0].ToString()); var ti = model.GetTypeInfo(patterns[0]); Assert.Equal("System.Object", ti.Type.ToTestDisplayString()); Assert.Equal("Point", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("3", patterns[1].ToString()); ti = model.GetTypeInfo(patterns[1]); Assert.Equal("?", ti.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.Type.TypeKind); Assert.Equal("System.Int32", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("4.0", patterns[2].ToString()); ti = model.GetTypeInfo(patterns[2]); Assert.Equal("?", ti.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.Type.TypeKind); Assert.Equal("System.Double", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("Xyzzy", patterns[3].ToString()); ti = model.GetTypeInfo(patterns[3]); Assert.Equal("?", ti.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.Type.TypeKind); Assert.Equal("?", ti.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.ConvertedType.TypeKind); Assert.Equal("Q7 t", patterns[4].ToString()); ti = model.GetTypeInfo(patterns[4]); Assert.Equal("System.Object", ti.Type.ToTestDisplayString()); Assert.Equal("Q7", ti.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.ConvertedType.TypeKind); } [Fact] [WorkItem(34678, "https://github.com/dotnet/roslyn/issues/34678")] public void ConstantPatternVsUnconstrainedTypeParameter05() { var source = @"class C<T> { static bool Test1(T t) { return t is null; // 1 } static bool Test2(C<T> t) { return t is null; // ok } static bool Test3(T t) { return t is 1; // 2 } static bool Test4(T t) { return t is ""frog""; // 3 } }"; CreateCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(); CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (5,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type '<null>'. Please use language version '8.0' or greater to match an open type with a constant pattern. // return t is null; // 1 Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, "null").WithArguments("T", "<null>", "8.0").WithLocation(5, 21), // (13,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type 'int'. Please use language version '8.0' or greater to match an open type with a constant pattern. // return t is 1; // 2 Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, "1").WithArguments("T", "int", "8.0").WithLocation(13, 21), // (17,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type 'string'. Please use language version '8.0' or greater to match an open type with a constant pattern. // return t is "frog"; // 3 Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, @"""frog""").WithArguments("T", "string", "8.0").WithLocation(17, 21)); } [Fact] [WorkItem(34905, "https://github.com/dotnet/roslyn/issues/34905")] public void ConstantPatternVsUnconstrainedTypeParameter06() { var source = @"public class C<T> { public enum E { V1, V2 } public void M() { switch (default(E)) { case E.V1: break; } } } "; CreateCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(); CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(); } [Fact] public void WarnUnmatchedIsRelationalPattern() { var source = @"public class C { public void M() { _ = 1 is < 0; // 1 _ = 1 is < 1; // 2 _ = 1 is < 2; // 3 _ = 1 is <= 0; // 4 _ = 1 is <= 1; // 5 _ = 1 is <= 2; // 6 _ = 1 is > 0; // 7 _ = 1 is > 1; // 8 _ = 1 is > 2; // 9 _ = 1 is >= 0; // 10 _ = 1 is >= 1; // 11 _ = 1 is >= 2; // 12 } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (5,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is < 0; // 1 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is < 0").WithLocation(5, 13), // (6,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is < 1; // 2 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is < 1").WithLocation(6, 13), // (7,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is < 2; // 3 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is < 2").WithLocation(7, 13), // (8,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is <= 0; // 4 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is <= 0").WithLocation(8, 13), // (9,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is <= 1; // 5 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is <= 1").WithLocation(9, 13), // (10,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is <= 2; // 6 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is <= 2").WithLocation(10, 13), // (11,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is > 0; // 7 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is > 0").WithLocation(11, 13), // (12,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is > 1; // 8 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is > 1").WithLocation(12, 13), // (13,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is > 2; // 9 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is > 2").WithLocation(13, 13), // (14,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is >= 0; // 10 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is >= 0").WithLocation(14, 13), // (15,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is >= 1; // 11 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is >= 1").WithLocation(15, 13), // (16,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is >= 2; // 12 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is >= 2").WithLocation(16, 13) ); } [Fact] public void RelationalPatternInSwitchWithConstantControllingExpression() { var source = @"public class C { public void M() { switch (1) { case < 0: break; // 1 case < 1: break; // 2 case < 2: break; case < 3: break; // 3 } } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (7,23): warning CS0162: Unreachable code detected // case < 0: break; // 1 Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(7, 23), // (8,23): warning CS0162: Unreachable code detected // case < 1: break; // 2 Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(8, 23), // (10,23): warning CS0162: Unreachable code detected // case < 3: break; // 3 Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(10, 23) ); } [Fact] public void RelationalPatternInSwitchWithOutOfRangeComparand() { var source = @"public class C { public void M(int i) { switch (i) { case < int.MinValue: break; // 1 case <= int.MinValue: break; case > int.MaxValue: break; // 2 case >= int.MaxValue: break; } } public void M(uint i) { switch (i) { case < 0: break; // 3 case <= 0: break; case > uint.MaxValue: break; // 4 case >= uint.MaxValue: break; } } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (7,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.MinValue: break; // 1 Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "< int.MinValue").WithLocation(7, 18), // (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 > int.MaxValue: break; // 2 Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "> int.MaxValue").WithLocation(9, 18), // (17,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case < 0: break; // 3 Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "< 0").WithLocation(17, 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 > uint.MaxValue: break; // 4 Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "> uint.MaxValue").WithLocation(19, 18) ); } [Fact] public void IsRelationalPatternWithOutOfRangeComparand() { var source = @"public class C { public void M(int i) { _ = i is < int.MinValue; // 1 _ = i is <= int.MinValue; _ = i is > int.MaxValue; // 2 _ = i is >= int.MaxValue; } public void M(uint i) { _ = i is < 0; // 3 _ = i is <= 0; _ = i is > uint.MaxValue; // 4 _ = i is >= uint.MaxValue; } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (5,13): error CS8518: An expression of type 'int' can never match the provided pattern. // _ = i is < int.MinValue; // 1 Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is < int.MinValue").WithArguments("int").WithLocation(5, 13), // (7,13): error CS8518: An expression of type 'int' can never match the provided pattern. // _ = i is > int.MaxValue; // 2 Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is > int.MaxValue").WithArguments("int").WithLocation(7, 13), // (12,13): error CS8518: An expression of type 'uint' can never match the provided pattern. // _ = i is < 0; // 3 Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is < 0").WithArguments("uint").WithLocation(12, 13), // (14,13): error CS8518: An expression of type 'uint' can never match the provided pattern. // _ = i is > uint.MaxValue; // 4 Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is > uint.MaxValue").WithArguments("uint").WithLocation(14, 13) ); } [Fact] public void IsRelationalPatternWithAlwaysMatchingRange() { var source = @"public class C { public void M(int i) { _ = i is > int.MinValue; _ = i is >= int.MinValue; // 1 _ = i is < int.MaxValue; _ = i is <= int.MaxValue; // 2 } public void M(uint i) { _ = i is > 0; _ = i is >= 0; // 3 _ = i is < uint.MaxValue; _ = i is <= uint.MaxValue; // 4 } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (6,13): warning CS8794: An expression of type 'int' always matches the provided pattern. // _ = i is >= int.MinValue; // 1 Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is >= int.MinValue").WithArguments("int").WithLocation(6, 13), // (8,13): warning CS8794: An expression of type 'int' always matches the provided pattern. // _ = i is <= int.MaxValue; // 2 Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is <= int.MaxValue").WithArguments("int").WithLocation(8, 13), // (13,13): warning CS8794: An expression of type 'uint' always matches the provided pattern. // _ = i is >= 0; // 3 Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is >= 0").WithArguments("uint").WithLocation(13, 13), // (15,13): warning CS8794: An expression of type 'uint' always matches the provided pattern. // _ = i is <= uint.MaxValue; // 4 Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is <= uint.MaxValue").WithArguments("uint").WithLocation(15, 13) ); } [Fact] public void IsImpossiblePatternKinds() { var source = @"public class C { public void M(string s) { _ = s is (System.Delegate); // impossible parenthesized type pattern _ = s is not _; // impossible negated pattern _ = s is ""a"" and ""b""; // impossible conjunctive pattern } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (5,19): error CS8121: An expression of type 'string' cannot be handled by a pattern of type 'Delegate'. // _ = s is (System.Delegate); // impossible parenthesized type pattern Diagnostic(ErrorCode.ERR_PatternWrongType, "System.Delegate").WithArguments("string", "System.Delegate").WithLocation(5, 19), // (6,13): error CS8518: An expression of type 'string' can never match the provided pattern. // _ = s is not _; // impossible negated pattern Diagnostic(ErrorCode.ERR_IsPatternImpossible, "s is not _").WithArguments("string").WithLocation(6, 13), // (7,13): error CS8518: An expression of type 'string' can never match the provided pattern. // _ = s is "a" and "b"; // impossible conjunctive pattern Diagnostic(ErrorCode.ERR_IsPatternImpossible, @"s is ""a"" and ""b""").WithArguments("string").WithLocation(7, 13) ); } [Fact] public void IsNullableReferenceType_01() { var source = @"#nullable enable public class C { public void M1(object o) { var t = o is string? { }; } public void M2(object o) { var t = o is (string? { }); } public void M3(object o) { var t = o is string?; } public void M4(object o) { var t = o is string? _; } public void M5(object o) { var t = o is (string? _); } }"; CreateCompilation(source, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (4,22): error CS8116: It is not legal to use nullable type 'string?' in a pattern; use the underlying type 'string' instead. // var t = o is string? { }; Diagnostic(ErrorCode.ERR_PatternNullableType, "string?").WithArguments("string").WithLocation(4, 22), // (7,23): error CS8116: It is not legal to use nullable type 'string?' in a pattern; use the underlying type 'string' instead. // var t = o is (string? { }); Diagnostic(ErrorCode.ERR_PatternNullableType, "string?").WithArguments("string").WithLocation(7, 23), // (10,22): error CS8650: It is not legal to use nullable reference type 'string?' in an is-type expression; use the underlying type 'string' instead. // var t = o is string?; Diagnostic(ErrorCode.ERR_IsNullableType, "string?").WithArguments("string").WithLocation(10, 22), // (13,30): error CS0103: The name '_' does not exist in the current context // var t = o is string? _; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(13, 30), // (13,31): error CS1003: Syntax error, ':' expected // var t = o is string? _; Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(13, 31), // (13,31): error CS1525: Invalid expression term ';' // var t = o is string? _; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(13, 31), // (16,22): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'object', with 2 out parameters and a void return type. // var t = o is (string? _); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(string? _)").WithArguments("object", "2").WithLocation(16, 22), // (16,29): error CS1003: Syntax error, ',' expected // var t = o is (string? _); Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments(",", "?").WithLocation(16, 29), // (16,31): error CS1003: Syntax error, ',' expected // var t = o is (string? _); Diagnostic(ErrorCode.ERR_SyntaxError, "_").WithArguments(",", "").WithLocation(16, 31) ); } [Fact] public void IsAlwaysPatternKinds() { var source = @"public class C { public void M(string s) { _ = s is (_); // always parenthesized discard pattern _ = s is not System.Delegate; // always negated type pattern _ = s is string or null; // always disjunctive pattern } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (6,22): error CS8121: An expression of type 'string' cannot be handled by a pattern of type 'Delegate'. // _ = s is not System.Delegate; // always negated type pattern Diagnostic(ErrorCode.ERR_PatternWrongType, "System.Delegate").WithArguments("string", "System.Delegate").WithLocation(6, 22), // (7,13): warning CS8794: An expression of type 'string' always matches the provided pattern. // _ = s is string or null; // always disjunctive pattern Diagnostic(ErrorCode.WRN_IsPatternAlways, "s is string or null").WithArguments("string").WithLocation(7, 13) ); } [Fact] public void SemanticModelForSwitchExpression() { var source = @"public class C { void M(int i) { C x0 = i switch // 0 { 0 => new A(), 1 => new B(), _ => throw null, }; _ = i switch // 1 { 0 => new A(), 1 => new B(), _ => throw null, }; D x2 = i switch // 2 { 0 => new A(), 1 => new B(), _ => throw null, }; D x3 = i switch // 3 { 0 => new E(), // 3.1 1 => new F(), // 3.2 _ => throw null, }; C x4 = i switch // 4 { 0 => new A(), 1 => new B(), 2 => new C(), _ => throw null, }; D x5 = i switch // 5 { 0 => new A(), 1 => new B(), 2 => new C(), _ => throw null, }; D x6 = i switch // 6 { 0 => 1, 1 => 2, _ => throw null, }; _ = (C)(i switch // 7 { 0 => new A(), 1 => new B(), _ => throw null, }); _ = (D)(i switch // 8 { 0 => new A(), 1 => new B(), _ => throw null, }); _ = (D)(i switch // 9 { 0 => new E(), // 9.1 1 => new F(), // 9.2 _ => throw null, }); _ = (C)(i switch // 10 { 0 => new A(), 1 => new B(), 2 => new C(), _ => throw null, }); _ = (D)(i switch // 11 { 0 => new A(), 1 => new B(), 2 => new C(), _ => throw null, }); _ = (D)(i switch // 12 { 0 => 1, 1 => 2, _ => throw null, }); } } class A : C { } class B : C { } class D { public static implicit operator D(C c) => throw null; public static implicit operator D(short s) => throw null; } class E { public static implicit operator C(E c) => throw null; } class F { public static implicit operator C(F c) => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (11,15): error CS8506: No best type was found for the switch expression. // _ = i switch // 1 Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(11, 15), // (25,18): error CS0029: Cannot implicitly convert type 'E' to 'D' // 0 => new E(), // 3.1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new E()").WithArguments("E", "D").WithLocation(25, 18), // (26,18): error CS0029: Cannot implicitly convert type 'F' to 'D' // 1 => new F(), // 3.2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new F()").WithArguments("F", "D").WithLocation(26, 18), // (63,18): error CS0029: Cannot implicitly convert type 'E' to 'D' // 0 => new E(), // 9.1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new E()").WithArguments("E", "D").WithLocation(63, 18), // (64,18): error CS0029: Cannot implicitly convert type 'F' to 'D' // 1 => new F(), // 9.2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new F()").WithArguments("F", "D").WithLocation(64, 18) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); void checkType(ExpressionSyntax expr, string expectedNaturalType, string expectedConvertedType, ConversionKind expectedConversionKind) { var typeInfo = model.GetTypeInfo(expr); var conversion = model.GetConversion(expr); Assert.Equal(expectedNaturalType, typeInfo.Type?.ToTestDisplayString()); Assert.Equal(expectedConvertedType, typeInfo.ConvertedType?.ToTestDisplayString()); Assert.Equal(expectedConversionKind, conversion.Kind); } var switches = tree.GetRoot().DescendantNodes().OfType<SwitchExpressionSyntax>().ToArray(); for (int i = 0; i < switches.Length; i++) { var expr = switches[i]; switch (i) { case 0: checkType(expr, null, "C", ConversionKind.SwitchExpression); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, null, "C", ConversionKind.ImplicitThrow); break; case 1: checkType(expr, "?", "?", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "?", ConversionKind.NoConversion); checkType(expr.Arms[1].Expression, "B", "?", ConversionKind.NoConversion); checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow); break; case 2: checkType(expr, null, "D", ConversionKind.SwitchExpression); checkType(expr.Arms[0].Expression, "A", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[1].Expression, "B", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow); break; case 3: checkType(expr, "?", "D", ConversionKind.NoConversion); checkType(expr.Arms[0].Expression, "E", "?", ConversionKind.NoConversion); checkType(expr.Arms[1].Expression, "F", "?", ConversionKind.NoConversion); checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow); break; case 4: case 10: checkType(expr, "C", "C", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity); checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow); break; case 5: checkType(expr, "C", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity); checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow); break; case 11: checkType(expr, "C", "C", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity); checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow); break; case 6: checkType(expr, "System.Int32", "D", ConversionKind.SwitchExpression); checkType(expr.Arms[0].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[1].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow); break; case 7: checkType(expr, null, null, ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, null, "C", ConversionKind.ImplicitThrow); checkType((CastExpressionSyntax)expr.Parent.Parent, "C", "C", ConversionKind.Identity); break; case 8: checkType(expr, null, null, ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[1].Expression, "B", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow); checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity); break; case 9: checkType(expr, "?", "?", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "E", "?", ConversionKind.NoConversion); checkType(expr.Arms[1].Expression, "F", "?", ConversionKind.NoConversion); checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow); checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity); break; case 12: checkType(expr, "System.Int32", "System.Int32", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[1].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow); checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity); break; default: Assert.False(true); break; } } } [Fact, WorkItem(45946, "https://github.com/dotnet/roslyn/issues/45946")] public void VoidPattern_01() { var source = @" class C { void F(object o) { _ = is this.F(1); } }"; CreateCompilation(source).VerifyDiagnostics( // (6,13): error CS1525: Invalid expression term 'is' // _ = is this.F(1); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "is").WithArguments("is").WithLocation(6, 13) ); } [Fact, WorkItem(45946, "https://github.com/dotnet/roslyn/issues/45946")] public void VoidPattern_02() { var source = @" class C { void F(object o) { _ = switch { this.F(1) => 1 }; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,13): error CS1525: Invalid expression term 'switch' // _ = switch { this.F(1) => 1 }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "switch").WithArguments("switch").WithLocation(6, 13), // (6,13): warning CS8848: Operator 'switch' cannot be used here due to precedence. Use parentheses to disambiguate. // _ = switch { this.F(1) => 1 }; Diagnostic(ErrorCode.WRN_PrecedenceInversion, "switch").WithArguments("switch").WithLocation(6, 13) ); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypePattern() { var source = @" class C { void F(object o) { _ = o switch { (int?) => 1, _ => 0 }; _ = o switch { int? => 1, _ => 0 }; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,25): error CS8116: It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead. // _ = o switch { (int?) => 1, _ => 0 }; Diagnostic(ErrorCode.ERR_PatternNullableType, "int?").WithArguments("int").WithLocation(6, 25), // (7,24): error CS8116: It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead. // _ = o switch { int? => 1, _ => 0 }; Diagnostic(ErrorCode.ERR_PatternNullableType, "int?").WithArguments("int").WithLocation(7, 24) ); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.Patterns)] public class PatternMatchingTests2 : PatternMatchingTestBase { [Fact] public void Patterns2_00() { var source = @" using System; class Program { public static void Main() { Console.WriteLine(1 is int {} x ? x : -1); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"1"); } [Fact] public void Patterns2_01() { var source = @" using System; class Program { public static void Main() { Point p = new Point(); Check(true, p is Point(3, 4) { Length: 5 } q1 && Check(p, q1)); Check(false, p is Point(1, 4) { Length: 5 }); Check(false, p is Point(3, 1) { Length: 5 }); Check(false, p is Point(3, 4) { Length: 1 }); Check(true, p is (3, 4) { Length: 5 } q2 && Check(p, q2)); Check(false, p is (1, 4) { Length: 5 }); Check(false, p is (3, 1) { Length: 5 }); Check(false, p is (3, 4) { Length: 1 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } } public class Point { public void Deconstruct(out int X, out int Y) { X = 3; Y = 4; } public int Length => 5; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: ""); } [Fact] public void Patterns2_02() { var source = @" using System; class Program { public static void Main() { Point p = new Point(); Check(true, p is Point(3, 4) { Length: 5 } q1 && Check(p, q1)); Check(false, p is Point(1, 4) { Length: 5 }); Check(false, p is Point(3, 1) { Length: 5 }); Check(false, p is Point(3, 4) { Length: 1 }); Check(true, p is (3, 4) { Length: 5 } q2 && Check(p, q2)); Check(false, p is (1, 4) { Length: 5 }); Check(false, p is (3, 1) { Length: 5 }); Check(false, p is (3, 4) { Length: 1 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } } public class Point { public int Length => 5; } public static class PointExtensions { public static void Deconstruct(this Point p, out int X, out int Y) { X = 3; Y = 4; } } "; // We use a compilation profile that provides System.Runtime.CompilerServices.ExtensionAttribute needed for this test var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: ""); } [Fact] public void Patterns2_03() { var source = @" using System; class Program { public static void Main() { var p = (x: 3, y: 4); Check(true, p is (3, 4) q1 && Check(p, q1)); Check(false, p is (1, 4) { x: 3 }); Check(false, p is (3, 1) { y: 4 }); Check(false, p is (3, 4) { x: 1 }); Check(true, p is (3, 4) { x: 3 } q2 && Check(p, q2)); Check(false, p is (1, 4) { x: 3 }); Check(false, p is (3, 1) { x: 3 }); Check(false, p is (3, 4) { x: 1 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (9,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (1, 4) { x: 3 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (1, 4) { x: 3 }").WithArguments("(int x, int y)").WithLocation(9, 22), // (10,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (3, 1) { y: 4 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 1) { y: 4 }").WithArguments("(int x, int y)").WithLocation(10, 22), // (11,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (3, 4) { x: 1 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 4) { x: 1 }").WithArguments("(int x, int y)").WithLocation(11, 22), // (13,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (1, 4) { x: 3 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (1, 4) { x: 3 }").WithArguments("(int x, int y)").WithLocation(13, 22), // (15,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern. // Check(false, p is (3, 4) { x: 1 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 4) { x: 1 }").WithArguments("(int x, int y)").WithLocation(15, 22) ); } [Fact] public void Patterns2_04b() { var source = @" using System; class Program { public static void Main() { var p = (x: 3, y: 4); Check(true, p is (3, 4) q1 && Check(p, q1)); Check(true, p is (3, 4) { x: 3 } q2 && Check(p, q2)); Check(false, p is (3, 1) { x: 3 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: ""); } [Fact] public void Patterns2_DiscardPattern_01() { var source = @" using System; class Program { public static void Main() { Point p = new Point(); Check(true, p is Point(_, _) { Length: _ } q1 && Check(p, q1)); Check(false, p is Point(1, _) { Length: _ }); Check(false, p is Point(_, 1) { Length: _ }); Check(false, p is Point(_, _) { Length: 1 }); Check(true, p is (_, _) { Length: _ } q2 && Check(p, q2)); Check(false, p is (1, _) { Length: _ }); Check(false, p is (_, 1) { Length: _ }); Check(false, p is (_, _) { Length: 1 }); } private static bool Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}""); return true; } } public class Point { public void Deconstruct(out int X, out int Y) { X = 3; Y = 4; } public int Length => 5; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: ""); } [Fact] public void Patterns2_Switch01() { var sourceTemplate = @" class Program {{ public static void Main() {{ var p = (true, false); switch (p) {{ {0} {1} {2} case (_, _): // error - subsumed break; }} }} }}"; void testErrorCase(string s1, string s2, string s3) { var source = string.Format(sourceTemplate, s1, s2, s3); var compilation = CreatePatternCompilation(source); compilation.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 (_, _): // error - subsumed Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "(_, _)").WithLocation(12, 18) ); } void testGoodCase(string s1, string s2) { var source = string.Format(sourceTemplate, s1, s2, string.Empty); var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); } var c1 = "case (true, _):"; var c2 = "case (false, false):"; var c3 = "case (_, true):"; testErrorCase(c1, c2, c3); testErrorCase(c2, c3, c1); testErrorCase(c3, c1, c2); testErrorCase(c1, c3, c2); testErrorCase(c3, c2, c1); testErrorCase(c2, c1, c3); testGoodCase(c1, c2); testGoodCase(c1, c3); testGoodCase(c2, c3); testGoodCase(c2, c1); testGoodCase(c3, c1); testGoodCase(c3, c2); } [Fact] public void Patterns2_Switch02() { var source = @" class Program { public static void Main() { Point p = new Point(); switch (p) { case Point(3, 4) { Length: 5 }: System.Console.WriteLine(true); break; default: System.Console.WriteLine(false); break; } } } public class Point { public void Deconstruct(out int X, out int Y) { X = 3; Y = 4; } public int Length => 5; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: "True"); } [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 switch (i) { case default: break; } // error 3 switch (i) { case default when true: break; } // error 4 switch ((1, 2)) { case (1, default): break; } // error 5 if (i is < default) {} // error 6 switch (i) { case < default: break; } // error 7 if (i is < ((default))) {} // error 8 switch (i) { case < ((default)): break; } // error 9 if (i is default!) {} // error 10 if (i is (default!)) {} // error 11 if (i is < ((default)!)) {} // error 12 if (i is default!!) {} // error 13 if (i is (default!!)) {} // error 14 if (i is < ((default)!!)) {} // error 15 // These are not accepted by the parser. See https://github.com/dotnet/roslyn/issues/45387 if (i is (default)!) {} // error 16 if (i is ((default)!)) {} // error 17 } }"; var compilation = CreatePatternCompilation(source); 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,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 3 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(8, 27), // (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 when true: break; } // error 4 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(9, 27), // (10,36): 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 ((1, 2)) { case (1, default): break; } // error 5 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(10, 36), // (12,20): 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 6 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(12, 20), // (13,29): 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 7 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(13, 29), // (14,22): 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 8 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(14, 22), // (15,31): 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 9 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(15, 31), // (17,18): error CS8598: The suppression operator is not allowed in this context // if (i is default!) {} // error 10 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(17, 18), // (17,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 10 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(17, 18), // (18,19): error CS8598: The suppression operator is not allowed in this context // if (i is (default!)) {} // error 11 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(18, 19), // (18,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 11 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(18, 19), // (19,21): error CS8598: The suppression operator is not allowed in this context // if (i is < ((default)!)) {} // error 12 Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!").WithLocation(19, 21), // (19,22): 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 12 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(19, 22), // (20,18): error CS8598: The suppression operator is not allowed in this context // if (i is default!!) {} // error 13 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!!").WithLocation(20, 18), // (20,18): error CS8598: The suppression operator is not allowed in this context // if (i is default!!) {} // error 13 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(20, 18), // (20,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 13 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(20, 18), // (21,19): error CS8598: The suppression operator is not allowed in this context // if (i is (default!!)) {} // error 14 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!!").WithLocation(21, 19), // (21,19): error CS8598: The suppression operator is not allowed in this context // if (i is (default!!)) {} // error 14 Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(21, 19), // (21,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 14 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(21, 19), // (22,21): error CS8598: The suppression operator is not allowed in this context // if (i is < ((default)!!)) {} // error 15 Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!!").WithLocation(22, 21), // (22,21): error CS8598: The suppression operator is not allowed in this context // if (i is < ((default)!!)) {} // error 15 Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!").WithLocation(22, 21), // (22,22): error CS8715: Duplicate null suppression operator ('!') // if (i is < ((default)!!)) {} // error 15 Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "default").WithLocation(22, 22), // (22,22): 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 15 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(22, 22), // (25,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 16 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(25, 19), // (25,27): error CS1026: ) expected // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_CloseParenExpected, "!").WithLocation(25, 27), // (25,28): error CS1525: Invalid expression term ')' // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(25, 28), // (25,28): error CS1002: ; expected // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(25, 28), // (25,28): error CS1513: } expected // if (i is (default)!) {} // error 16 Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(25, 28), // (26,18): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'int', with 2 out parameters and a void return type. // if (i is ((default)!)) {} // error 17 Diagnostic(ErrorCode.ERR_MissingDeconstruct, "((default)!)").WithArguments("int", "2").WithLocation(26, 18), // (26,20): 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 17 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(26, 20), // (26,28): error CS1003: Syntax error, ',' expected // if (i is ((default)!)) {} // error 17 Diagnostic(ErrorCode.ERR_SyntaxError, "!").WithArguments(",", "!").WithLocation(26, 28), // (26,29): error CS1525: Invalid expression term ')' // if (i is ((default)!)) {} // error 17 Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(26, 29) ); } [Fact] public void SwitchExpression_01() { // test appropriate language version or feature flag var source = @"class Program { public static void Main() { var r = 1 switch { _ => 0, }; } }"; CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithoutRecursivePatterns).VerifyDiagnostics( // (5,17): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // var r = 1 switch { _ => 0, }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { _ => 0, }").WithArguments("recursive patterns", "8.0").WithLocation(5, 17) ); CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8).VerifyDiagnostics(); } [Fact] public void SwitchExpression_02() { // test switch expression's governing expression has no type // test switch expression's governing expression has type void var source = @"class Program { public static void Main() { var r1 = (1, null) switch { _ => 0 }; var r2 = System.Console.Write(1) switch { _ => 0 }; } }"; CreatePatternCompilation(source).VerifyDiagnostics( // (5,18): error CS8117: Invalid operand for pattern match; value required, but found '(int, <null>)'. // var r1 = (1, null) switch ( _ => 0 ); Diagnostic(ErrorCode.ERR_BadPatternExpression, "(1, null)").WithArguments("(int, <null>)").WithLocation(5, 18), // (6,18): error CS8117: Invalid operand for pattern match; value required, but found 'void'. // var r2 = System.Console.Write(1) switch ( _ => 0 ); Diagnostic(ErrorCode.ERR_BadPatternExpression, "System.Console.Write(1)").WithArguments("void").WithLocation(6, 18) ); } [Fact] public void SwitchExpression_03() { // test that a ternary expression is not at an appropriate precedence // for the constant expression of a constant pattern in a switch expression arm. var source = @"class Program { public static void Main() { bool b = true; var r1 = b switch { true ? true : true => true, false => false }; var r2 = b switch { (true ? true : true) => true, false => false }; } }"; // This is admittedly poor syntax error recovery (for the line declaring r2), // but this test demonstrates that it is a syntax error. CreatePatternCompilation(source).VerifyDiagnostics( // (6,34): error CS1003: Syntax error, '=>' expected // var r1 = b switch { true ? true : true => true, false => false }; Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments("=>", "?").WithLocation(6, 34), // (6,34): error CS1525: Invalid expression term '?' // var r1 = b switch { true ? true : true => true, false => false }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "?").WithArguments("?").WithLocation(6, 34), // (6,48): error CS1003: Syntax error, ',' expected // var r1 = b switch { true ? true : true => true, false => false }; Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(6, 48), // (6,48): error CS8504: Pattern missing // var r1 = b switch { true ? true : true => true, false => false }; Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(6, 48) ); } [Fact] public void SwitchExpression_04() { // test that a ternary expression is permitted as a constant pattern in recursive contexts and the case expression. var source = @"class Program { public static void Main() { var b = (true, false); var r1 = b switch { (true ? true : true, _) => true, _ => false, }; var r2 = b is (true ? true : true, _); switch (b.Item1) { case true ? true : true: break; } } }"; CreatePatternCompilation(source).VerifyDiagnostics( ); } [Fact] public void SwitchExpression_05() { // test throw expression in match arm. var source = @"class Program { public static void Main() { var x = 1 switch { 1 => 1, _ => throw null }; } }"; CreatePatternCompilation(source).VerifyDiagnostics( ); } [Fact] public void EmptySwitchExpression() { var source = @"class Program { public static void Main() { var r = 1 switch { }; } }"; CreatePatternCompilation(source).VerifyDiagnostics( // (5,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered. // var r = 1 switch { }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(5, 19), // (5,19): error CS8506: No best type was found for the switch expression. // var r = 1 switch { }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(5, 19)); } [Fact] public void SwitchExpression_06() { // test common type vs delegate in match expression var source = @"class Program { public static void Main() { var x = 1 switch { 0 => M, 1 => new D(M), 2 => M }; x(); } public static void M() {} public delegate void D(); }"; CreatePatternCompilation(source).VerifyDiagnostics( // (5,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '3' is not covered. // var x = 1 switch { 0 => M, 1 => new D(M), 2 => M }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("3").WithLocation(5, 19) ); } [Fact] public void SwitchExpression_07() { // test flow analysis of the switch expression var source = @"class Program { public static void Main() { int q = 1; int u; var x = q switch { 0 => u=0, 1 => u=1, _ => u=2 }; System.Console.WriteLine(u); } }"; CreatePatternCompilation(source).VerifyDiagnostics( ); } [Fact] public void SwitchExpression_08() { // test flow analysis of the switch expression var source = @"class Program { public static void Main() { int q = 1; int u; var x = q switch { 0 => u=0, 1 => 1, _ => u=2 }; System.Console.WriteLine(u); } static int M(int i) => i; }"; CreatePatternCompilation(source).VerifyDiagnostics( // (8,34): error CS0165: Use of unassigned local variable 'u' // System.Console.WriteLine(u); Diagnostic(ErrorCode.ERR_UseDefViolation, "u").WithArguments("u").WithLocation(8, 34) ); } [Fact] public void SwitchExpression_09() { // test flow analysis of the switch expression var source = @"class Program { public static void Main() { int q = 1; int u; var x = q switch { 0 => u=0, 1 => u=M(u), _ => u=2, }; System.Console.WriteLine(u); } static int M(int i) => i; }"; CreatePatternCompilation(source).VerifyDiagnostics( // (7,47): error CS0165: Use of unassigned local variable 'u' // var x = q switch { 0 => u=0, 1 => u=M(u), _ => u=2 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "u").WithArguments("u").WithLocation(7, 47) ); } [Fact] public void SwitchExpression_10() { // test lazily inferring variables in the pattern // test lazily inferring variables in the when clause // test lazily inferring variables in the arrow expression var source = @"class Program { public static void Main() { int a = 1; var b = a switch { var x1 => x1, }; var c = a switch { var x2 when x2 is var x3 => x3 }; var d = a switch { var x4 => x4 is var x5 ? x5 : 1, }; } static int M(int i) => i; }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): warning CS8846: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered. However, a pattern with a 'when' clause might successfully match this value. // var c = a switch { var x2 when x2 is var x3 => x3 }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveWithWhen, "switch").WithArguments("_").WithLocation(7, 19) ); var names = new[] { "x1", "x2", "x3", "x4", "x5" }; var tree = compilation.SyntaxTrees[0]; foreach (var designation in tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>()) { var model = compilation.GetSemanticModel(tree); var symbol = model.GetDeclaredSymbol(designation); Assert.Equal(SymbolKind.Local, symbol.Kind); Assert.Equal("int", ((ILocalSymbol)symbol).Type.ToDisplayString()); } foreach (var ident in tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>()) { var model = compilation.GetSemanticModel(tree); var typeInfo = model.GetTypeInfo(ident); Assert.Equal("int", typeInfo.Type.ToDisplayString()); } } [Fact] public void ShortDiscardInIsPattern() { // test that we forbid a short discard at the top level of an is-pattern expression var source = @"class Program { public static void Main() { int a = 1; if (a is _) { } } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // if (a is _) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(6, 18) ); } [Fact] public void Patterns2_04() { // Test that a single-element deconstruct pattern is an error if no further elements disambiguate. var source = @" using System; class Program { public static void Main() { var t = new System.ValueTuple<int>(1); if (t is (int x)) { } // error 1 switch (t) { case (_): break; } // error 2 var u = t switch { (int y) => y, _ => 2 }; // error 3 if (t is (int z1) _) { } // ok if (t is (Item1: int z2)) { } // ok if (t is (int z3) { }) { } // ok if (t is ValueTuple<int>(int z4)) { } // ok } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (8,18): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // if (t is (int x)) { } // error 1 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x)").WithArguments("parenthesized pattern", "9.0").WithLocation(8, 18), // (8,19): error CS8121: An expression of type 'ValueTuple<int>' cannot be handled by a pattern of type 'int'. // if (t is (int x)) { } // error 1 Diagnostic(ErrorCode.ERR_PatternWrongType, "int").WithArguments("System.ValueTuple<int>", "int").WithLocation(8, 19), // (9,27): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // switch (t) { case (_): break; } // error 2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(_)").WithArguments("parenthesized pattern", "9.0").WithLocation(9, 27), // (10,28): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // var u = t switch { (int y) => y, _ => 2 }; // error 3 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int y)").WithArguments("parenthesized pattern", "9.0").WithLocation(10, 28), // (10,29): error CS8121: An expression of type 'ValueTuple<int>' cannot be handled by a pattern of type 'int'. // var u = t switch { (int y) => y, _ => 2 }; // error 3 Diagnostic(ErrorCode.ERR_PatternWrongType, "int").WithArguments("System.ValueTuple<int>", "int").WithLocation(10, 29) ); } [Fact] public void Patterns2_05() { // Test parsing the var pattern // Test binding the var pattern // Test lowering the var pattern for the is-expression var source = @" using System; class Program { public static void Main() { var t = (1, 2); { Check(true, t is var (x, y) && x == 1 && y == 2); } { Check(false, t is var (x, y) && x == 1 && y == 3); } } private static void Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""Expected: '{expected}', Actual: '{actual}'""); } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @""); } [Fact] public void Patterns2_06() { // Test that 'var' does not bind to a type var source = @" using System; namespace N { class Program { public static void Main() { var t = (1, 2); { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1 { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2 { Check(true, t is var x); } // error 3 } private static void Check<T>(T expected, T actual) { if (!object.Equals(expected, actual)) throw new Exception($""Expected: '{expected}', Actual: '{actual}'""); } } class var { } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (9,21): error CS0029: Cannot implicitly convert type '(int, int)' to 'N.var' // var t = (1, 2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 2)").WithArguments("(int, int)", "N.var").WithLocation(9, 21), // (10,32): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here. // { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1 Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(10, 32), // (10,36): error CS1061: 'var' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'var' could be found (are you missing a using directive or an assembly reference?) // { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(x, y)").WithArguments("N.var", "Deconstruct").WithLocation(10, 36), // (10,36): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'var', with 2 out parameters and a void return type. // { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1 Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(x, y)").WithArguments("N.var", "2").WithLocation(10, 36), // (11,33): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here. // { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2 Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(11, 33), // (11,37): error CS1061: 'var' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'var' could be found (are you missing a using directive or an assembly reference?) // { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(x, y)").WithArguments("N.var", "Deconstruct").WithLocation(11, 37), // (11,37): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'var', with 2 out parameters and a void return type. // { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2 Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(x, y)").WithArguments("N.var", "2").WithLocation(11, 37), // (12,32): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here. // { Check(true, t is var x); } // error 3 Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(12, 32) ); } [Fact] public void Patterns2_10() { var source = @" using System; class Program { public static void Main() { Console.Write(M((false, false))); Console.Write(M((false, true))); Console.Write(M((true, false))); Console.Write(M((true, true))); } private static int M((bool, bool) t) { switch (t) { case (false, false): return 0; case (false, _): return 1; case (_, false): return 2; case var _: return 3; } } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"0123"); } [Fact] public void Patterns2_11() { var source = @" using System; class Program { public static void Main() { Console.Write(M((false, false))); Console.Write(M((false, true))); Console.Write(M((true, false))); Console.Write(M((true, true))); } private static int M((bool, bool) t) { switch (t) { case (false, false): return 0; case (false, _): return 1; case (_, false): return 2; case (true, true): return 3; case var _: return 4; } } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (20,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case var _: return 4; Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "var _").WithLocation(20, 18) ); } [Fact] public void Patterns2_12() { var source = @" using System; class Program { public static void Main() { Console.Write(M((false, false))); Console.Write(M((false, true))); Console.Write(M((true, false))); Console.Write(M((true, true))); } private static int M((bool, bool) t) { return t switch { (false, false) => 0, (false, _) => 1, (_, false) => 2, _ => 3 }; } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"0123"); } [Fact] public void SwitchArmSubsumed() { var source = @"public class X { public static void Main() { string s = string.Empty; string s2 = s switch { null => null, string t => t, ""foo"" => null }; } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,61): error CS8410: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match. // string s2 = s switch { null => null, string t => t, "foo" => null }; Diagnostic(ErrorCode.ERR_SwitchArmSubsumed, @"""foo""").WithLocation(6, 61) ); } [Fact] public void LongTuples() { var source = @"using System; public class X { public static void Main() { var t = (1, 2, 3, 4, 5, 6, 7, 8, 9); { Console.WriteLine(t is (_, _, _, _, _, _, _, _, var t9) ? t9 : 100); } switch (t) { case (_, _, _, _, _, _, _, _, var t9): Console.WriteLine(t9); break; } Console.WriteLine(t switch { (_, _, _, _, _, _, _, _, var t9) => t9 }); } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"9 9 9"); } [Fact] public void TypeCheckInPropertyPattern() { var source = @"using System; class Program2 { public static void Main() { object o = new Frog(1, 2); if (o is Frog(1, 2)) { Console.Write(1); } if (o is Frog { A: 1, B: 2 }) { Console.Write(2); } if (o is Frog(1, 2) { A: 1, B: 2, C: 3 }) { Console.Write(3); } if (o is Frog(9, 2) { A: 1, B: 2, C: 3 }) {} else { Console.Write(4); } if (o is Frog(1, 9) { A: 1, B: 2, C: 3 }) {} else { Console.Write(5); } if (o is Frog(1, 2) { A: 9, B: 2, C: 3 }) {} else { Console.Write(6); } if (o is Frog(1, 2) { A: 1, B: 9, C: 3 }) {} else { Console.Write(7); } if (o is Frog(1, 2) { A: 1, B: 2, C: 9 }) {} else { Console.Write(8); } } } class Frog { public object A, B; public object C => (int)A + (int)B; public Frog(object A, object B) => (this.A, this.B) = (A, B); public void Deconstruct(out object A, out object B) => (A, B) = (this.A, this.B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"12345678"); } [Fact] public void OvereagerSubsumption() { var source = @"class Program2 { public static int Main() => 0; public static void M(object o) { switch (o) { case (1, 2): break; case string s: break; } } } "; var compilation = CreateCompilationWithMscorlib45(source); // doesn't have ITuple // Two errors below instead of one due to https://github.com/dotnet/roslyn/issues/25533 compilation.VerifyDiagnostics( // (8,18): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // case (1, 2): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(1, 2)").WithArguments("object", "Deconstruct").WithLocation(8, 18), // (8,18): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 2 out parameters and a void return type. // case (1, 2): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(1, 2)").WithArguments("object", "2").WithLocation(8, 18) ); } [Fact] public void UnderscoreDeclaredAndDiscardPattern_01() { var source = @"class Program0 { static int Main() => 0; private const int _ = 1; bool M1(object o) => o is _; bool M2(object o) => o switch { 1 => true, _ => false }; } class Program1 { class _ {} bool M3(object o) => o is _; bool M4(object o) => o switch { 1 => true, _ => false }; } "; var expected = new[] { // (5,31): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // bool M1(object o) => o is _; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(5, 31), // (11,31): warning CS8513: The name '_' refers to the type 'Program1._', not the discard pattern. Use '@_' for the type, or 'var _' to discard. // bool M3(object o) => o is _; Diagnostic(ErrorCode.WRN_IsTypeNamedUnderscore, "_").WithArguments("Program1._").WithLocation(11, 31) }; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics(expected); compilation = CreateCompilation(source, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics(expected); expected = new[] { // (5,31): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // bool M1(object o) => o is _; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(5, 31), // (6,26): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // bool M2(object o) => o switch { 1 => true, _ => false }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "o switch { 1 => true, _ => false }").WithArguments("recursive patterns", "8.0").WithLocation(6, 26), // (12,26): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // bool M4(object o) => o switch { 1 => true, _ => false }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "o switch { 1 => true, _ => false }").WithArguments("recursive patterns", "8.0").WithLocation(12, 26) }; compilation = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics(expected); } [Fact] public void UnderscoreDeclaredAndDiscardPattern_02() { var source = @"class Program0 { static int Main() => 0; private const int _ = 1; } class Program1 : Program0 { bool M2(object o) => o switch { 1 => true, _ => false }; // ok, private member not inherited } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); } [Fact] public void UnderscoreDeclaredAndDiscardPattern_03() { var source = @"class Program0 { static int Main() => 0; protected const int _ = 1; } class Program1 : Program0 { bool M2(object o) => o switch { 1 => true, _ => false }; } class Program2 { bool _(object q) => true; bool M2(object o) => o switch { 1 => true, _ => false }; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); } [Fact] public void UnderscoreDeclaredAndDiscardPattern_04() { var source = @"using _ = System.Int32; class Program { static int Main() => 0; bool M2(object o) => o switch { 1 => true, _ => false }; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (1,1): hidden CS8019: Unnecessary using directive. // using _ = System.Int32; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using _ = System.Int32;").WithLocation(1, 1) ); } [Fact] public void EscapingUnderscoreDeclaredAndDiscardPattern_04() { var source = @"class Program0 { static int Main() => 0; private const int _ = 2; bool M1(object o) => o is @_; int M2(object o) => o switch { 1 => 1, @_ => 2, var _ => 3 }; } class Program1 { class _ {} bool M1(object o) => o is @_; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); } [Fact] public void ErroneousSwitchArmDefiniteAssignment() { // When a switch expression arm is erroneous, ensure that the expression is treated as unreachable (e.g. for definite assignment purposes). var source = @"class Program2 { public static int Main() => 0; public static void M(string s) { int i; int j = s switch { ""frog"" => 1, 0 => i, _ => 2 }; } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,41): error CS0029: Cannot implicitly convert type 'int' to 'string' // int j = s switch { "frog" => 1, 0 => i, _ => 2 }; Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "string").WithLocation(7, 41) ); } [Fact, WorkItem(9154, "https://github.com/dotnet/roslyn/issues/9154")] public void ErroneousIsPatternDefiniteAssignment() { var source = @"class Program2 { public static int Main() => 0; void Dummy(object o) {} void Test5() { Dummy((System.Func<object, object, bool>) ((o1, o2) => o1 is int x5 && o2 is int x5 && x5 > 0)); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (8,74): error CS0128: A local variable or function named 'x5' is already defined in this scope // o2 is int x5 && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(8, 74) ); } [Fact] public void ERR_IsPatternImpossible() { var source = @"class Program { public static void Main() { System.Console.WriteLine(""frog"" is string { Length: 4, Length: 5 }); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (5,34): error CS8415: An expression of type 'string' can never match the provided pattern. // System.Console.WriteLine("frog" is string { Length: 4, Length: 5 }); Diagnostic(ErrorCode.ERR_IsPatternImpossible, @"""frog"" is string { Length: 4, Length: 5 }").WithArguments("string").WithLocation(5, 34) ); } [Fact] public void WRN_GivenExpressionNeverMatchesPattern01() { var source = @"class Program { public static void Main() { System.Console.WriteLine(3 is 4); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (5,34): warning CS8416: The given expression never matches the provided pattern. // System.Console.WriteLine(3 is 4); Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "3 is 4").WithLocation(5, 34) ); } [Fact] public void WRN_GivenExpressionNeverMatchesPattern02() { var source = @"class Program { public static void Main() { const string s = null; System.Console.WriteLine(s is string { Length: 3 }); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,34): warning CS8416: The given expression never matches the provided pattern. // System.Console.WriteLine(s is string { Length: 3 }); Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "s is string { Length: 3 }").WithLocation(6, 34) ); } [Fact] public void DefiniteAssignmentForIsPattern01() { var source = @"class Program { public static void Main() { string s = 300.ToString(); System.Console.WriteLine(s is string { Length: int j }); System.Console.WriteLine(j); } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,34): error CS0165: Use of unassigned local variable 'j' // System.Console.WriteLine(j); Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j").WithLocation(7, 34) ); } [Fact] public void DefiniteAssignmentForIsPattern02() { var source = @"class Program { public static void Main() { const string s = ""300""; System.Console.WriteLine(s is string { Length: int j }); System.Console.WriteLine(j); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns); compilation.VerifyDiagnostics(); var expectedOutput = @"True 3"; var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void DefiniteAssignmentForIsPattern03() { var source = @"class Program { public static void Main() { int j; const string s = null; if (s is string { Length: 3 }) { System.Console.WriteLine(j); } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,13): warning CS8416: The given expression never matches the provided pattern. // if (s is string { Length: 3 }) Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "s is string { Length: 3 }").WithLocation(7, 13) ); } [Fact] public void RefutableConstantPattern01() { var source = @"class Program { public static void Main() { int j; const int N = 3; const int M = 3; if (N is M) { } else { System.Console.WriteLine(j); } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (8,13): warning CS8417: The given expression always matches the provided constant. // if (N is M) Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "N is M").WithLocation(8, 13) ); } [Fact, WorkItem(25591, "https://github.com/dotnet/roslyn/issues/25591")] public void TupleSubsumptionError() { var source = @"class Program2 { public static void Main() { M(new Fox()); M(new Cat()); M(new Program2()); } static void M(object o) { switch ((o, 0)) { case (Fox fox, _): System.Console.Write(""Fox ""); break; case (Cat cat, _): System.Console.Write(""Cat""); break; } } } class Fox {} class Cat {} "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"Fox Cat"); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns01() { var source = @"class Program { static void Main() { switch (a: 1, b: 2) { case (c: 2, d: 3): // error: c and d not defined break; } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8416: The name 'c' does not identify tuple element 'Item1'. // case (c: 2, d: 3): // error: c and d not defined Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "c").WithArguments("c", "Item1").WithLocation(7, 19), // (7,25): error CS8416: The name 'd' does not identify tuple element 'Item2'. // case (c: 2, d: 3): // error: c and d not defined Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "d").WithArguments("d", "Item2").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns02() { var source = @"class Program { static void Main() { switch (a: 1, b: 2) { case (a: 2, a: 3): break; } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,25): error CS8416: The name 'a' does not identify tuple element 'Item2'. // case (a: 2, a: 3): Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "a").WithArguments("a", "Item2").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns03() { var source = @"class Program { static void Main() { switch (a: 1, b: 2) { case (a: 2, Item2: 3): System.Console.WriteLine(666); break; case (a: 1, Item2: 2): System.Console.WriteLine(111); break; } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"111"); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns04() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (c: 2, d: 3): break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); public void Deconstruct(out int a, out int b) => (a, b) = (A, B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8417: The name 'c' does not match the corresponding 'Deconstruct' parameter 'a'. // case (c: 2, d: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "c").WithArguments("c", "a").WithLocation(7, 19), // (7,25): error CS8417: The name 'd' does not match the corresponding 'Deconstruct' parameter 'b'. // case (c: 2, d: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "d").WithArguments("d", "b").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns05() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (c: 2, d: 3): break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); } static class Extensions { public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8417: The name 'c' does not match the corresponding 'Deconstruct' parameter 'a'. // case (c: 2, d: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "c").WithArguments("c", "a").WithLocation(7, 19), // (7,25): error CS8417: The name 'd' does not match the corresponding 'Deconstruct' parameter 'b'. // case (c: 2, d: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "d").WithArguments("d", "b").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns06() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (a: 2, a: 3): break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); public void Deconstruct(out int a, out int b) => (a, b) = (A, B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,25): error CS8417: The name 'a' does not match the corresponding 'Deconstruct' parameter 'b'. // case (a: 2, a: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "a").WithArguments("a", "b").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns07() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (a: 2, a: 3): break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); } static class Extensions { public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,25): error CS8417: The name 'a' does not match the corresponding 'Deconstruct' parameter 'b'. // case (a: 2, a: 3): Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "a").WithArguments("a", "b").WithLocation(7, 25) ); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns08() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (a: 2, b: 3): System.Console.WriteLine(666); break; case (a: 1, b: 2): System.Console.WriteLine(111); break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); public void Deconstruct(out int a, out int b) => (a, b) = (A, B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"111"); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns09() { var source = @"class Program { static void Main() { switch (new T(a: 1, b: 2)) { case (a: 2, b: 3): System.Console.WriteLine(666); break; case (a: 1, b: 2): System.Console.WriteLine(111); break; } } } class T { public int A; public int B; public T(int a, int b) => (A, B) = (a, b); } static class Extensions { public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B); } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"111"); } [Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")] public void NamesInPositionalPatterns10() { var source = @"class Program { static void Main() { switch (a: 1, b: 2) { case (Item2: 1, 2): break; } } } "; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (7,19): error CS8416: The name 'Item2' does not identify tuple element 'Item1'. // case (Item2: 1, 2): Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "Item2").WithArguments("Item2", "Item1").WithLocation(7, 19) ); } [Fact] public void PropertyPatternMemberMissing01() { var source = @"class Program { static void Main(string[] args) { Blah b = null; if (b is Blah { X: int i }) { } } } class Blah { }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,25): error CS0117: 'Blah' does not contain a definition for 'X' // if (b is Blah { X: int i }) Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("Blah", "X").WithLocation(6, 25) ); } [Fact] public void PropertyPatternMemberMissing02() { var source = @"class Program { static void Main(string[] args) { Blah b = null; if (b is Blah { X: int i }) { } } } class Blah { public int X { set {} } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (6,25): error CS0154: The property or indexer 'Blah.X' cannot be used in this context because it lacks the get accessor // if (b is Blah { X: int i }) Diagnostic(ErrorCode.ERR_PropertyLacksGet, "X:").WithArguments("Blah.X").WithLocation(6, 25) ); } [Fact] public void PropertyPatternMemberMissing03() { var source = @"class Program { static void Main(string[] args) { Blah b = null; switch (b) { case Blah { X: int i }: break; } } } class Blah { }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (8,25): error CS0117: 'Blah' does not contain a definition for 'X' // case Blah { X: int i }: Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("Blah", "X").WithLocation(8, 25) ); } [Fact] public void PropertyPatternMemberMissing04() { var source = @"class Program { static void Main(string[] args) { Blah b = null; switch (b) { case Blah { X: int i }: break; } } } class Blah { public int X { set {} } }"; var compilation = CreatePatternCompilation(source); compilation.VerifyDiagnostics( // (8,25): error CS0154: The property or indexer 'Blah.X' cannot be used in this context because it lacks the get accessor // case Blah { X: int i }: Diagnostic(ErrorCode.ERR_PropertyLacksGet, "X:").WithArguments("Blah.X").WithLocation(8, 25) ); } [Fact] [WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")] [WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")] public void ConstantPatternVsUnconstrainedTypeParameter03() { var source = @"class C<T> { internal struct S { } static bool Test(S s) { return s is null; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (6,21): error CS0037: Cannot convert null to 'C<T>.S' because it is a non-nullable value type // return s is null; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("C<T>.S").WithLocation(6, 21) ); } [Fact] [WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")] [WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")] public void ConstantPatternVsUnconstrainedTypeParameter04() { var source = @"class C<T> { static bool Test(C<T> x) { return x is 1; } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (5,21): error CS8121: An expression of type 'C<T>' cannot be handled by a pattern of type 'int'. // return x is 1; Diagnostic(ErrorCode.ERR_PatternWrongType, "1").WithArguments("C<T>", "int").WithLocation(5, 21) ); } [Fact] [WorkItem(20724, "https://github.com/dotnet/roslyn/issues/20724")] public void SpeculateWithNameConflict01() { var source = @"public class Class1 { int i = 1; public override int GetHashCode() => 1; public override bool Equals(object obj) { return obj is global::Class1 @class && this.i == @class.i; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( ); var tree = compilation.SyntaxTrees[0]; var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree); var returnStatement = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single(); Assert.Equal("return obj is global::Class1 @class && this.i == @class.i;", returnStatement.ToString()); var modifiedReturnStatement = (ReturnStatementSyntax)new RemoveAliasQualifiers().Visit(returnStatement); Assert.Equal("return obj is Class1 @class && this.i == @class.i;", modifiedReturnStatement.ToString()); var gotModel = model.TryGetSpeculativeSemanticModel(returnStatement.Location.SourceSpan.Start, modifiedReturnStatement, out var speculativeModel); Assert.True(gotModel); Assert.NotNull(speculativeModel); var typeInfo = speculativeModel.GetTypeInfo(modifiedReturnStatement.Expression); Assert.Equal(SpecialType.System_Boolean, typeInfo.Type.SpecialType); } /// <summary> /// Helper class to remove alias qualifications. /// </summary> class RemoveAliasQualifiers : CSharpSyntaxRewriter { public override SyntaxNode VisitAliasQualifiedName(AliasQualifiedNameSyntax node) { return node.Name; } } [Fact] [WorkItem(20724, "https://github.com/dotnet/roslyn/issues/20724")] public void SpeculateWithNameConflict02() { var source = @"public class Class1 { public override int GetHashCode() => 1; public override bool Equals(object obj) { return obj is global::Class1 @class; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( ); var tree = compilation.SyntaxTrees[0]; var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree); var returnStatement = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single(); Assert.Equal("return obj is global::Class1 @class;", returnStatement.ToString()); var modifiedReturnStatement = (ReturnStatementSyntax)new RemoveAliasQualifiers().Visit(returnStatement); Assert.Equal("return obj is Class1 @class;", modifiedReturnStatement.ToString()); var gotModel = model.TryGetSpeculativeSemanticModel(returnStatement.Location.SourceSpan.Start, modifiedReturnStatement, out var speculativeModel); Assert.True(gotModel); Assert.NotNull(speculativeModel); var typeInfo = speculativeModel.GetTypeInfo(modifiedReturnStatement.Expression); Assert.Equal(SpecialType.System_Boolean, typeInfo.Type.SpecialType); } [Fact] public void WrongArity() { var source = @"class Program { static void Main(string[] args) { Point p = new Point() { X = 3, Y = 4 }; if (p is Point()) { } } } class Point { public int X, Y; public void Deconstruct(out int X, out int Y) => (X, Y) = (this.X, this.Y); } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (6,23): error CS7036: There is no argument given that corresponds to the required formal parameter 'X' of 'Point.Deconstruct(out int, out int)' // if (p is Point()) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "()").WithArguments("X", "Point.Deconstruct(out int, out int)").WithLocation(6, 23), // (6,23): error CS8129: No suitable Deconstruct instance or extension method was found for type 'Point', with 0 out parameters and a void return type. // if (p is Point()) Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("Point", "0").WithLocation(6, 23) ); } [Fact] public void GetTypeInfo_01() { var source = @"class Program { static void Main(string[] args) { object o = null; Point p = null; if (o is Point(3, string { Length: 2 })) { } if (p is (_, { })) { } if (p is Point({ }, { }, { })) { } if (p is Point(, { })) { } } } class Point { public object X, Y; public void Deconstruct(out object X, out object Y) => (X, Y) = (this.X, this.Y); public Point(object X, object Y) => (this.X, this.Y) = (X, Y); } "; var expected = new[] { new { Source = "Point(3, string { Length: 2 })", Type = "System.Object", ConvertedType = "Point" }, new { Source = "3", Type = "System.Object", ConvertedType = "System.Int32" }, new { Source = "string { Length: 2 }", Type = "System.Object", ConvertedType = "System.String" }, new { Source = "2", Type = "System.Int32", ConvertedType = "System.Int32" }, new { Source = "(_, { })", Type = "Point", ConvertedType = "Point" }, new { Source = "_", Type = "System.Object", ConvertedType = "System.Object" }, new { Source = "{ }", Type = "System.Object", ConvertedType = "System.Object" }, new { Source = "Point({ }, { }, { })", Type = "Point", ConvertedType = "Point" }, new { Source = "{ }", Type = "?", ConvertedType = "?" }, new { Source = "{ }", Type = "?", ConvertedType = "?" }, new { Source = "{ }", Type = "?", ConvertedType = "?" }, new { Source = "Point(, { })", Type = "Point", ConvertedType = "Point" }, new { Source = "", Type = "System.Object", ConvertedType = "System.Object" }, new { Source = "{ }", Type = "System.Object", ConvertedType = "System.Object" }, }; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (10,24): error CS8504: Pattern missing // if (p is Point(, { })) { } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(10, 24), // (9,23): error CS1501: No overload for method 'Deconstruct' takes 3 arguments // if (p is Point({ }, { }, { })) { } Diagnostic(ErrorCode.ERR_BadArgCount, "({ }, { }, { })").WithArguments("Deconstruct", "3").WithLocation(9, 23), // (9,23): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'Point', with 3 out parameters and a void return type. // if (p is Point({ }, { }, { })) { } Diagnostic(ErrorCode.ERR_MissingDeconstruct, "({ }, { }, { })").WithArguments("Point", "3").WithLocation(9, 23) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); int i = 0; foreach (var pat in tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>()) { var typeInfo = model.GetTypeInfo(pat); var ex = expected[i++]; Assert.Equal(ex.Source, pat.ToString()); Assert.Equal(ex.Type, typeInfo.Type.ToTestDisplayString()); Assert.Equal(ex.ConvertedType, typeInfo.ConvertedType.ToTestDisplayString()); } Assert.Equal(expected.Length, i); } [Fact, WorkItem(26613, "https://github.com/dotnet/roslyn/issues/26613")] public void MissingDeconstruct_01() { var source = @"using System; public class C { public void M() { _ = this is (a: 1); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (4,21): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // _ = this is (a: 1); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(a: 1)").WithArguments("C", "Deconstruct").WithLocation(4, 21), // (4,21): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 1 out parameters and a void return type. // _ = this is (a: 1); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(a: 1)").WithArguments("C", "1").WithLocation(4, 21) ); } [Fact, WorkItem(26613, "https://github.com/dotnet/roslyn/issues/26613")] public void MissingDeconstruct_02() { var source = @"using System; public class C { public void M() { _ = this is C(a: 1); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (4,22): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // _ = this is C(a: 1); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(a: 1)").WithArguments("C", "Deconstruct").WithLocation(4, 22), // (4,22): error CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 1 out parameters and a void return type. // _ = this is C(a: 1); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(a: 1)").WithArguments("C", "1").WithLocation(4, 22) ); } [Fact] public void PatternTypeInfo_01() { var source = @" public class C { void M(T1 t1) { if (t1 is T2 (var t3, t4: T4 t4) { V5 : T6 t5 }) {} } } class T1 { } class T2 : T1 { public T5 V5 = null; public void Deconstruct(out T3 t3, out T4 t4) => throw null; } class T3 { } class T4 { } class T5 { } class T6 : T5 { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray(); Assert.Equal(4, patterns.Length); Assert.Equal("T2 (var t3, t4: T4 t4) { V5 : T6 t5 }", patterns[0].ToString()); var ti = model.GetTypeInfo(patterns[0]); Assert.Equal("T1", ti.Type.ToTestDisplayString()); Assert.Equal("T2", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("var t3", patterns[1].ToString()); ti = model.GetTypeInfo(patterns[1]); Assert.Equal("T3", ti.Type.ToTestDisplayString()); Assert.Equal("T3", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("T4 t4", patterns[2].ToString()); ti = model.GetTypeInfo(patterns[2]); Assert.Equal("T4", ti.Type.ToTestDisplayString()); Assert.Equal("T4", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("T6 t5", patterns[3].ToString()); ti = model.GetTypeInfo(patterns[3]); Assert.Equal("T5", ti.Type.ToTestDisplayString()); Assert.Equal("T6", ti.ConvertedType.ToTestDisplayString()); } [Fact] public void PatternTypeInfo_02() { var source = @" public class C { void M(object o) { if (o is Point(3, 4.0)) {} } } class Point { public void Deconstruct(out object o1, out System.IComparable o2) => throw null; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray(); Assert.Equal(3, patterns.Length); Assert.Equal("Point(3, 4.0)", patterns[0].ToString()); var ti = model.GetTypeInfo(patterns[0]); Assert.Equal("System.Object", ti.Type.ToTestDisplayString()); Assert.Equal("Point", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("3", patterns[1].ToString()); ti = model.GetTypeInfo(patterns[1]); Assert.Equal("System.Object", ti.Type.ToTestDisplayString()); Assert.Equal("System.Int32", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("4.0", patterns[2].ToString()); ti = model.GetTypeInfo(patterns[2]); Assert.Equal("System.IComparable", ti.Type.ToTestDisplayString()); Assert.Equal("System.Double", ti.ConvertedType.ToTestDisplayString()); } [Fact] public void PatternTypeInfo_03() { var source = @" public class C { void M(object o) { if (o is Point(3, 4.0) { Missing: Xyzzy }) {} if (o is Q7 t) {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0246: The type or namespace name 'Point' could not be found (are you missing a using directive or an assembly reference?) // if (o is Point(3, 4.0) { Missing: Xyzzy }) {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Point").WithArguments("Point").WithLocation(6, 18), // (6,43): error CS0103: The name 'Xyzzy' does not exist in the current context // if (o is Point(3, 4.0) { Missing: Xyzzy }) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "Xyzzy").WithArguments("Xyzzy").WithLocation(6, 43), // (7,18): error CS0246: The type or namespace name 'Q7' could not be found (are you missing a using directive or an assembly reference?) // if (o is Q7 t) {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Q7").WithArguments("Q7").WithLocation(7, 18) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray(); Assert.Equal(5, patterns.Length); Assert.Equal("Point(3, 4.0) { Missing: Xyzzy }", patterns[0].ToString()); var ti = model.GetTypeInfo(patterns[0]); Assert.Equal("System.Object", ti.Type.ToTestDisplayString()); Assert.Equal("Point", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("3", patterns[1].ToString()); ti = model.GetTypeInfo(patterns[1]); Assert.Equal("?", ti.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.Type.TypeKind); Assert.Equal("System.Int32", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("4.0", patterns[2].ToString()); ti = model.GetTypeInfo(patterns[2]); Assert.Equal("?", ti.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.Type.TypeKind); Assert.Equal("System.Double", ti.ConvertedType.ToTestDisplayString()); Assert.Equal("Xyzzy", patterns[3].ToString()); ti = model.GetTypeInfo(patterns[3]); Assert.Equal("?", ti.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.Type.TypeKind); Assert.Equal("?", ti.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.ConvertedType.TypeKind); Assert.Equal("Q7 t", patterns[4].ToString()); ti = model.GetTypeInfo(patterns[4]); Assert.Equal("System.Object", ti.Type.ToTestDisplayString()); Assert.Equal("Q7", ti.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, ti.ConvertedType.TypeKind); } [Fact] [WorkItem(34678, "https://github.com/dotnet/roslyn/issues/34678")] public void ConstantPatternVsUnconstrainedTypeParameter05() { var source = @"class C<T> { static bool Test1(T t) { return t is null; // 1 } static bool Test2(C<T> t) { return t is null; // ok } static bool Test3(T t) { return t is 1; // 2 } static bool Test4(T t) { return t is ""frog""; // 3 } }"; CreateCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(); CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (5,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type '<null>'. Please use language version '8.0' or greater to match an open type with a constant pattern. // return t is null; // 1 Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, "null").WithArguments("T", "<null>", "8.0").WithLocation(5, 21), // (13,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type 'int'. Please use language version '8.0' or greater to match an open type with a constant pattern. // return t is 1; // 2 Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, "1").WithArguments("T", "int", "8.0").WithLocation(13, 21), // (17,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type 'string'. Please use language version '8.0' or greater to match an open type with a constant pattern. // return t is "frog"; // 3 Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, @"""frog""").WithArguments("T", "string", "8.0").WithLocation(17, 21)); } [Fact] [WorkItem(34905, "https://github.com/dotnet/roslyn/issues/34905")] public void ConstantPatternVsUnconstrainedTypeParameter06() { var source = @"public class C<T> { public enum E { V1, V2 } public void M() { switch (default(E)) { case E.V1: break; } } } "; CreateCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(); CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(); } [Fact] public void WarnUnmatchedIsRelationalPattern() { var source = @"public class C { public void M() { _ = 1 is < 0; // 1 _ = 1 is < 1; // 2 _ = 1 is < 2; // 3 _ = 1 is <= 0; // 4 _ = 1 is <= 1; // 5 _ = 1 is <= 2; // 6 _ = 1 is > 0; // 7 _ = 1 is > 1; // 8 _ = 1 is > 2; // 9 _ = 1 is >= 0; // 10 _ = 1 is >= 1; // 11 _ = 1 is >= 2; // 12 } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (5,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is < 0; // 1 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is < 0").WithLocation(5, 13), // (6,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is < 1; // 2 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is < 1").WithLocation(6, 13), // (7,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is < 2; // 3 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is < 2").WithLocation(7, 13), // (8,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is <= 0; // 4 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is <= 0").WithLocation(8, 13), // (9,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is <= 1; // 5 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is <= 1").WithLocation(9, 13), // (10,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is <= 2; // 6 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is <= 2").WithLocation(10, 13), // (11,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is > 0; // 7 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is > 0").WithLocation(11, 13), // (12,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is > 1; // 8 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is > 1").WithLocation(12, 13), // (13,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is > 2; // 9 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is > 2").WithLocation(13, 13), // (14,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is >= 0; // 10 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is >= 0").WithLocation(14, 13), // (15,13): error CS8793: The given expression always matches the provided pattern. // _ = 1 is >= 1; // 11 Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is >= 1").WithLocation(15, 13), // (16,13): warning CS8519: The given expression never matches the provided pattern. // _ = 1 is >= 2; // 12 Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is >= 2").WithLocation(16, 13) ); } [Fact] public void RelationalPatternInSwitchWithConstantControllingExpression() { var source = @"public class C { public void M() { switch (1) { case < 0: break; // 1 case < 1: break; // 2 case < 2: break; case < 3: break; // 3 } } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (7,23): warning CS0162: Unreachable code detected // case < 0: break; // 1 Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(7, 23), // (8,23): warning CS0162: Unreachable code detected // case < 1: break; // 2 Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(8, 23), // (10,23): warning CS0162: Unreachable code detected // case < 3: break; // 3 Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(10, 23) ); } [Fact] public void RelationalPatternInSwitchWithOutOfRangeComparand() { var source = @"public class C { public void M(int i) { switch (i) { case < int.MinValue: break; // 1 case <= int.MinValue: break; case > int.MaxValue: break; // 2 case >= int.MaxValue: break; } } public void M(uint i) { switch (i) { case < 0: break; // 3 case <= 0: break; case > uint.MaxValue: break; // 4 case >= uint.MaxValue: break; } } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (7,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.MinValue: break; // 1 Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "< int.MinValue").WithLocation(7, 18), // (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 > int.MaxValue: break; // 2 Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "> int.MaxValue").WithLocation(9, 18), // (17,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case < 0: break; // 3 Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "< 0").WithLocation(17, 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 > uint.MaxValue: break; // 4 Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "> uint.MaxValue").WithLocation(19, 18) ); } [Fact] public void IsRelationalPatternWithOutOfRangeComparand() { var source = @"public class C { public void M(int i) { _ = i is < int.MinValue; // 1 _ = i is <= int.MinValue; _ = i is > int.MaxValue; // 2 _ = i is >= int.MaxValue; } public void M(uint i) { _ = i is < 0; // 3 _ = i is <= 0; _ = i is > uint.MaxValue; // 4 _ = i is >= uint.MaxValue; } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (5,13): error CS8518: An expression of type 'int' can never match the provided pattern. // _ = i is < int.MinValue; // 1 Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is < int.MinValue").WithArguments("int").WithLocation(5, 13), // (7,13): error CS8518: An expression of type 'int' can never match the provided pattern. // _ = i is > int.MaxValue; // 2 Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is > int.MaxValue").WithArguments("int").WithLocation(7, 13), // (12,13): error CS8518: An expression of type 'uint' can never match the provided pattern. // _ = i is < 0; // 3 Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is < 0").WithArguments("uint").WithLocation(12, 13), // (14,13): error CS8518: An expression of type 'uint' can never match the provided pattern. // _ = i is > uint.MaxValue; // 4 Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is > uint.MaxValue").WithArguments("uint").WithLocation(14, 13) ); } [Fact] public void IsRelationalPatternWithAlwaysMatchingRange() { var source = @"public class C { public void M(int i) { _ = i is > int.MinValue; _ = i is >= int.MinValue; // 1 _ = i is < int.MaxValue; _ = i is <= int.MaxValue; // 2 } public void M(uint i) { _ = i is > 0; _ = i is >= 0; // 3 _ = i is < uint.MaxValue; _ = i is <= uint.MaxValue; // 4 } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (6,13): warning CS8794: An expression of type 'int' always matches the provided pattern. // _ = i is >= int.MinValue; // 1 Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is >= int.MinValue").WithArguments("int").WithLocation(6, 13), // (8,13): warning CS8794: An expression of type 'int' always matches the provided pattern. // _ = i is <= int.MaxValue; // 2 Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is <= int.MaxValue").WithArguments("int").WithLocation(8, 13), // (13,13): warning CS8794: An expression of type 'uint' always matches the provided pattern. // _ = i is >= 0; // 3 Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is >= 0").WithArguments("uint").WithLocation(13, 13), // (15,13): warning CS8794: An expression of type 'uint' always matches the provided pattern. // _ = i is <= uint.MaxValue; // 4 Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is <= uint.MaxValue").WithArguments("uint").WithLocation(15, 13) ); } [Fact] public void IsImpossiblePatternKinds() { var source = @"public class C { public void M(string s) { _ = s is (System.Delegate); // impossible parenthesized type pattern _ = s is not _; // impossible negated pattern _ = s is ""a"" and ""b""; // impossible conjunctive pattern } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (5,19): error CS8121: An expression of type 'string' cannot be handled by a pattern of type 'Delegate'. // _ = s is (System.Delegate); // impossible parenthesized type pattern Diagnostic(ErrorCode.ERR_PatternWrongType, "System.Delegate").WithArguments("string", "System.Delegate").WithLocation(5, 19), // (6,13): error CS8518: An expression of type 'string' can never match the provided pattern. // _ = s is not _; // impossible negated pattern Diagnostic(ErrorCode.ERR_IsPatternImpossible, "s is not _").WithArguments("string").WithLocation(6, 13), // (7,13): error CS8518: An expression of type 'string' can never match the provided pattern. // _ = s is "a" and "b"; // impossible conjunctive pattern Diagnostic(ErrorCode.ERR_IsPatternImpossible, @"s is ""a"" and ""b""").WithArguments("string").WithLocation(7, 13) ); } [Fact] public void IsNullableReferenceType_01() { var source = @"#nullable enable public class C { public void M1(object o) { var t = o is string? { }; } public void M2(object o) { var t = o is (string? { }); } public void M3(object o) { var t = o is string?; } public void M4(object o) { var t = o is string? _; } public void M5(object o) { var t = o is (string? _); } }"; CreateCompilation(source, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (4,22): error CS8116: It is not legal to use nullable type 'string?' in a pattern; use the underlying type 'string' instead. // var t = o is string? { }; Diagnostic(ErrorCode.ERR_PatternNullableType, "string?").WithArguments("string").WithLocation(4, 22), // (7,23): error CS8116: It is not legal to use nullable type 'string?' in a pattern; use the underlying type 'string' instead. // var t = o is (string? { }); Diagnostic(ErrorCode.ERR_PatternNullableType, "string?").WithArguments("string").WithLocation(7, 23), // (10,22): error CS8650: It is not legal to use nullable reference type 'string?' in an is-type expression; use the underlying type 'string' instead. // var t = o is string?; Diagnostic(ErrorCode.ERR_IsNullableType, "string?").WithArguments("string").WithLocation(10, 22), // (13,30): error CS0103: The name '_' does not exist in the current context // var t = o is string? _; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(13, 30), // (13,31): error CS1003: Syntax error, ':' expected // var t = o is string? _; Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(13, 31), // (13,31): error CS1525: Invalid expression term ';' // var t = o is string? _; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(13, 31), // (16,22): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'object', with 2 out parameters and a void return type. // var t = o is (string? _); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(string? _)").WithArguments("object", "2").WithLocation(16, 22), // (16,29): error CS1003: Syntax error, ',' expected // var t = o is (string? _); Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments(",", "?").WithLocation(16, 29), // (16,31): error CS1003: Syntax error, ',' expected // var t = o is (string? _); Diagnostic(ErrorCode.ERR_SyntaxError, "_").WithArguments(",", "").WithLocation(16, 31) ); } [Fact] public void IsAlwaysPatternKinds() { var source = @"public class C { public void M(string s) { _ = s is (_); // always parenthesized discard pattern _ = s is not System.Delegate; // always negated type pattern _ = s is string or null; // always disjunctive pattern } } "; CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (6,22): error CS8121: An expression of type 'string' cannot be handled by a pattern of type 'Delegate'. // _ = s is not System.Delegate; // always negated type pattern Diagnostic(ErrorCode.ERR_PatternWrongType, "System.Delegate").WithArguments("string", "System.Delegate").WithLocation(6, 22), // (7,13): warning CS8794: An expression of type 'string' always matches the provided pattern. // _ = s is string or null; // always disjunctive pattern Diagnostic(ErrorCode.WRN_IsPatternAlways, "s is string or null").WithArguments("string").WithLocation(7, 13) ); } [Fact] public void SemanticModelForSwitchExpression() { var source = @"public class C { void M(int i) { C x0 = i switch // 0 { 0 => new A(), 1 => new B(), _ => throw null, }; _ = i switch // 1 { 0 => new A(), 1 => new B(), _ => throw null, }; D x2 = i switch // 2 { 0 => new A(), 1 => new B(), _ => throw null, }; D x3 = i switch // 3 { 0 => new E(), // 3.1 1 => new F(), // 3.2 _ => throw null, }; C x4 = i switch // 4 { 0 => new A(), 1 => new B(), 2 => new C(), _ => throw null, }; D x5 = i switch // 5 { 0 => new A(), 1 => new B(), 2 => new C(), _ => throw null, }; D x6 = i switch // 6 { 0 => 1, 1 => 2, _ => throw null, }; _ = (C)(i switch // 7 { 0 => new A(), 1 => new B(), _ => throw null, }); _ = (D)(i switch // 8 { 0 => new A(), 1 => new B(), _ => throw null, }); _ = (D)(i switch // 9 { 0 => new E(), // 9.1 1 => new F(), // 9.2 _ => throw null, }); _ = (C)(i switch // 10 { 0 => new A(), 1 => new B(), 2 => new C(), _ => throw null, }); _ = (D)(i switch // 11 { 0 => new A(), 1 => new B(), 2 => new C(), _ => throw null, }); _ = (D)(i switch // 12 { 0 => 1, 1 => 2, _ => throw null, }); } } class A : C { } class B : C { } class D { public static implicit operator D(C c) => throw null; public static implicit operator D(short s) => throw null; } class E { public static implicit operator C(E c) => throw null; } class F { public static implicit operator C(F c) => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (11,15): error CS8506: No best type was found for the switch expression. // _ = i switch // 1 Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(11, 15), // (25,18): error CS0029: Cannot implicitly convert type 'E' to 'D' // 0 => new E(), // 3.1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new E()").WithArguments("E", "D").WithLocation(25, 18), // (26,18): error CS0029: Cannot implicitly convert type 'F' to 'D' // 1 => new F(), // 3.2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new F()").WithArguments("F", "D").WithLocation(26, 18), // (63,18): error CS0029: Cannot implicitly convert type 'E' to 'D' // 0 => new E(), // 9.1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new E()").WithArguments("E", "D").WithLocation(63, 18), // (64,18): error CS0029: Cannot implicitly convert type 'F' to 'D' // 1 => new F(), // 9.2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new F()").WithArguments("F", "D").WithLocation(64, 18) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); void checkType(ExpressionSyntax expr, string expectedNaturalType, string expectedConvertedType, ConversionKind expectedConversionKind) { var typeInfo = model.GetTypeInfo(expr); var conversion = model.GetConversion(expr); Assert.Equal(expectedNaturalType, typeInfo.Type?.ToTestDisplayString()); Assert.Equal(expectedConvertedType, typeInfo.ConvertedType?.ToTestDisplayString()); Assert.Equal(expectedConversionKind, conversion.Kind); } var switches = tree.GetRoot().DescendantNodes().OfType<SwitchExpressionSyntax>().ToArray(); for (int i = 0; i < switches.Length; i++) { var expr = switches[i]; switch (i) { case 0: checkType(expr, null, "C", ConversionKind.SwitchExpression); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, null, "C", ConversionKind.ImplicitThrow); break; case 1: checkType(expr, "?", "?", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "?", ConversionKind.NoConversion); checkType(expr.Arms[1].Expression, "B", "?", ConversionKind.NoConversion); checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow); break; case 2: checkType(expr, null, "D", ConversionKind.SwitchExpression); checkType(expr.Arms[0].Expression, "A", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[1].Expression, "B", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow); break; case 3: checkType(expr, "?", "D", ConversionKind.NoConversion); checkType(expr.Arms[0].Expression, "E", "?", ConversionKind.NoConversion); checkType(expr.Arms[1].Expression, "F", "?", ConversionKind.NoConversion); checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow); break; case 4: case 10: checkType(expr, "C", "C", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity); checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow); break; case 5: checkType(expr, "C", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity); checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow); break; case 11: checkType(expr, "C", "C", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity); checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow); break; case 6: checkType(expr, "System.Int32", "D", ConversionKind.SwitchExpression); checkType(expr.Arms[0].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[1].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow); break; case 7: checkType(expr, null, null, ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference); checkType(expr.Arms[2].Expression, null, "C", ConversionKind.ImplicitThrow); checkType((CastExpressionSyntax)expr.Parent.Parent, "C", "C", ConversionKind.Identity); break; case 8: checkType(expr, null, null, ConversionKind.Identity); checkType(expr.Arms[0].Expression, "A", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[1].Expression, "B", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow); checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity); break; case 9: checkType(expr, "?", "?", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "E", "?", ConversionKind.NoConversion); checkType(expr.Arms[1].Expression, "F", "?", ConversionKind.NoConversion); checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow); checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity); break; case 12: checkType(expr, "System.Int32", "System.Int32", ConversionKind.Identity); checkType(expr.Arms[0].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[1].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined); checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow); checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity); break; default: Assert.False(true); break; } } } [Fact, WorkItem(45946, "https://github.com/dotnet/roslyn/issues/45946")] public void VoidPattern_01() { var source = @" class C { void F(object o) { _ = is this.F(1); } }"; CreateCompilation(source).VerifyDiagnostics( // (6,13): error CS1525: Invalid expression term 'is' // _ = is this.F(1); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "is").WithArguments("is").WithLocation(6, 13) ); } [Fact, WorkItem(45946, "https://github.com/dotnet/roslyn/issues/45946")] public void VoidPattern_02() { var source = @" class C { void F(object o) { _ = switch { this.F(1) => 1 }; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,13): error CS1525: Invalid expression term 'switch' // _ = switch { this.F(1) => 1 }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "switch").WithArguments("switch").WithLocation(6, 13), // (6,13): warning CS8848: Operator 'switch' cannot be used here due to precedence. Use parentheses to disambiguate. // _ = switch { this.F(1) => 1 }; Diagnostic(ErrorCode.WRN_PrecedenceInversion, "switch").WithArguments("switch").WithLocation(6, 13) ); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypePattern() { var source = @" class C { void F(object o) { _ = o switch { (int?) => 1, _ => 0 }; _ = o switch { int? => 1, _ => 0 }; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,25): error CS8116: It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead. // _ = o switch { (int?) => 1, _ => 0 }; Diagnostic(ErrorCode.ERR_PatternNullableType, "int?").WithArguments("int").WithLocation(6, 25), // (7,24): error CS8116: It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead. // _ = o switch { int? => 1, _ => 0 }; Diagnostic(ErrorCode.ERR_PatternNullableType, "int?").WithArguments("int").WithLocation(7, 24) ); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/VisualBasic/Test/Syntax/Syntax/SerializationTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.IO Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SerializationTests Private Sub RoundTrip(text As String, Optional expectRecursive As Boolean = True) Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim root = tree.GetRoot() Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) End Sub <Fact> Public Sub TestRoundTripSyntaxNode() RoundTrip(<Goo> Public Class C End Class </Goo>.Value) End Sub <Fact> Public Sub TestRoundTripSyntaxNodeWithDiagnostics() Dim text = <Goo> Public Class C End </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim root = tree.GetVisualBasicRoot() Assert.True(root.HasErrors) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(DirectCast(droot, VisualBasicSyntaxNode).HasErrors) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) End Sub <Fact> Public Sub TestRoundTripSyntaxNodeWithAnnotation() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation = New SyntaxAnnotation() Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation) Assert.True(root.ContainsAnnotations) Assert.True(root.HasAnnotation(annotation)) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(droot.ContainsAnnotations) Assert.True(droot.HasAnnotation(annotation)) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) End Sub <Fact> Public Sub TestRoundTripSyntaxNodeWithMultipleInstancesOfTheSameAnnotation() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation = New SyntaxAnnotation() Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation, annotation) Assert.True(root.ContainsAnnotations) Assert.True(root.HasAnnotation(annotation)) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(droot.ContainsAnnotations) Assert.True(droot.HasAnnotation(annotation)) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) End Sub <Fact> Public Sub RoundTripSyntaxNodeWithAnnotationsRemoved() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation1 = New SyntaxAnnotation("annotation1") Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation1) Assert.Equal(True, root.ContainsAnnotations) Assert.Equal(True, root.HasAnnotation(annotation1)) Dim removedRoot = root.WithoutAnnotations(annotation1) Assert.Equal(False, removedRoot.ContainsAnnotations) Assert.Equal(False, removedRoot.HasAnnotation(annotation1)) Dim stream = New MemoryStream() removedRoot.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Assert.Equal(False, droot.ContainsAnnotations) Assert.Equal(False, droot.HasAnnotation(annotation1)) Dim annotation2 = New SyntaxAnnotation("annotation2") Dim doubleAnnoRoot = droot.WithAdditionalAnnotations(annotation1, annotation2) Assert.Equal(True, doubleAnnoRoot.ContainsAnnotations) Assert.Equal(True, doubleAnnoRoot.HasAnnotation(annotation1)) Assert.Equal(True, doubleAnnoRoot.HasAnnotation(annotation2)) Dim removedDoubleAnnoRoot = doubleAnnoRoot.WithoutAnnotations(annotation1, annotation2) Assert.Equal(False, removedDoubleAnnoRoot.ContainsAnnotations) Assert.Equal(False, removedDoubleAnnoRoot.HasAnnotation(annotation1)) Assert.Equal(False, removedDoubleAnnoRoot.HasAnnotation(annotation2)) stream = New MemoryStream() removedRoot.SerializeTo(stream) stream.Position = 0 droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Assert.Equal(False, droot.ContainsAnnotations) Assert.Equal(False, droot.HasAnnotation(annotation1)) Assert.Equal(False, droot.HasAnnotation(annotation2)) End Sub <Fact> Public Sub RoundTripSyntaxNodeWithAnnotationRemovedWithMultipleReference() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation1 = New SyntaxAnnotation("annotation1") Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation1, annotation1) Assert.Equal(True, root.ContainsAnnotations) Assert.Equal(True, root.HasAnnotation(annotation1)) Dim removedRoot = root.WithoutAnnotations(annotation1) Assert.Equal(False, removedRoot.ContainsAnnotations) Assert.Equal(False, removedRoot.HasAnnotation(annotation1)) Dim stream = New MemoryStream() removedRoot.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Assert.Equal(False, droot.ContainsAnnotations) Assert.Equal(False, droot.HasAnnotation(annotation1)) End Sub <Fact()> Public Sub TestRoundTripSyntaxNodeWithSpecialAnnotation() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation = New SyntaxAnnotation("TestAnnotation", "this is a test") Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation) Assert.True(root.ContainsAnnotations) Assert.True(root.HasAnnotation(annotation)) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(droot.ContainsAnnotations) Assert.True(droot.HasAnnotation(annotation)) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) Dim dannotation = droot.GetAnnotations("TestAnnotation").SingleOrDefault() Assert.NotNull(dannotation) Assert.NotSame(annotation, dannotation) ' not same instance Assert.Equal(annotation, dannotation) ' but are equivalent End Sub <Fact> <WorkItem(530374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530374")> Public Sub RoundtripSerializeDeepExpression() Dim text = <Goo><![CDATA[ Module Module15 Declare Function GetDesktopWindow Lib "User32" () As Integer Declare Function EnumChildWindows Lib "User32" (ByVal hw As Integer, ByVal lpWndProc As mydel, ByVal lp As Integer) As Integer Public intCounter As Integer Delegate Function mydel(ByVal hw As Integer, ByVal lp As Integer) As Integer Public d As mydel = New mydel(AddressOf EnumChildProc) Sub Main() Dim x As Object intCounter = 0 Dim hw As Integer hw = GetDesktopWindow() 'Call API passing ptr to callback x = EnumChildWindows(hw, d, 5) 'This should always be true, I would think If intCounter < 10 Then intcounter = 10 End If End Sub 'Callback function for EnumWindows Function EnumChildProc(ByVal hw As Integer, ByVal lp As Integer) As Integer intCounter = intCounter + 1 EnumChildProc = 1 End Function Sub Regression41614() Dim abc = "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" End Sub End Module ]]> </Goo>.Value RoundTrip(text, expectRecursive:=False) End Sub <Fact> <WorkItem(530374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530374")> Public Sub RoundtripSerializeDeepExpression2() Dim text = <Goo><![CDATA[ Module GroupJoin2 Sub Test1() q = From a In aa Group Join b As $ In bb On a Equals b End Sub End Module ]]> </Goo>.Value RoundTrip(text) End Sub <Fact> <WorkItem(1038237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1038237")> Public Sub RoundTripPragmaDirective() Dim text = <Goo><![CDATA[ #Disable Warning BC40000 ]]> </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim root = tree.GetRoot() Assert.True(root.ContainsDirectives) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim newRoot = VisualBasicSyntaxNode.DeserializeFrom(stream) Assert.True(newRoot.ContainsDirectives) 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 Imports System.IO Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SerializationTests Private Sub RoundTrip(text As String, Optional expectRecursive As Boolean = True) Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim root = tree.GetRoot() Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) End Sub <Fact> Public Sub TestRoundTripSyntaxNode() RoundTrip(<Goo> Public Class C End Class </Goo>.Value) End Sub <Fact> Public Sub TestRoundTripSyntaxNodeWithDiagnostics() Dim text = <Goo> Public Class C End </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim root = tree.GetVisualBasicRoot() Assert.True(root.HasErrors) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(DirectCast(droot, VisualBasicSyntaxNode).HasErrors) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) End Sub <Fact> Public Sub TestRoundTripSyntaxNodeWithAnnotation() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation = New SyntaxAnnotation() Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation) Assert.True(root.ContainsAnnotations) Assert.True(root.HasAnnotation(annotation)) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(droot.ContainsAnnotations) Assert.True(droot.HasAnnotation(annotation)) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) End Sub <Fact> Public Sub TestRoundTripSyntaxNodeWithMultipleInstancesOfTheSameAnnotation() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation = New SyntaxAnnotation() Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation, annotation) Assert.True(root.ContainsAnnotations) Assert.True(root.HasAnnotation(annotation)) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(droot.ContainsAnnotations) Assert.True(droot.HasAnnotation(annotation)) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) End Sub <Fact> Public Sub RoundTripSyntaxNodeWithAnnotationsRemoved() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation1 = New SyntaxAnnotation("annotation1") Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation1) Assert.Equal(True, root.ContainsAnnotations) Assert.Equal(True, root.HasAnnotation(annotation1)) Dim removedRoot = root.WithoutAnnotations(annotation1) Assert.Equal(False, removedRoot.ContainsAnnotations) Assert.Equal(False, removedRoot.HasAnnotation(annotation1)) Dim stream = New MemoryStream() removedRoot.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Assert.Equal(False, droot.ContainsAnnotations) Assert.Equal(False, droot.HasAnnotation(annotation1)) Dim annotation2 = New SyntaxAnnotation("annotation2") Dim doubleAnnoRoot = droot.WithAdditionalAnnotations(annotation1, annotation2) Assert.Equal(True, doubleAnnoRoot.ContainsAnnotations) Assert.Equal(True, doubleAnnoRoot.HasAnnotation(annotation1)) Assert.Equal(True, doubleAnnoRoot.HasAnnotation(annotation2)) Dim removedDoubleAnnoRoot = doubleAnnoRoot.WithoutAnnotations(annotation1, annotation2) Assert.Equal(False, removedDoubleAnnoRoot.ContainsAnnotations) Assert.Equal(False, removedDoubleAnnoRoot.HasAnnotation(annotation1)) Assert.Equal(False, removedDoubleAnnoRoot.HasAnnotation(annotation2)) stream = New MemoryStream() removedRoot.SerializeTo(stream) stream.Position = 0 droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Assert.Equal(False, droot.ContainsAnnotations) Assert.Equal(False, droot.HasAnnotation(annotation1)) Assert.Equal(False, droot.HasAnnotation(annotation2)) End Sub <Fact> Public Sub RoundTripSyntaxNodeWithAnnotationRemovedWithMultipleReference() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation1 = New SyntaxAnnotation("annotation1") Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation1, annotation1) Assert.Equal(True, root.ContainsAnnotations) Assert.Equal(True, root.HasAnnotation(annotation1)) Dim removedRoot = root.WithoutAnnotations(annotation1) Assert.Equal(False, removedRoot.ContainsAnnotations) Assert.Equal(False, removedRoot.HasAnnotation(annotation1)) Dim stream = New MemoryStream() removedRoot.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Assert.Equal(False, droot.ContainsAnnotations) Assert.Equal(False, droot.HasAnnotation(annotation1)) End Sub <Fact()> Public Sub TestRoundTripSyntaxNodeWithSpecialAnnotation() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation = New SyntaxAnnotation("TestAnnotation", "this is a test") Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation) Assert.True(root.ContainsAnnotations) Assert.True(root.HasAnnotation(annotation)) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(droot.ContainsAnnotations) Assert.True(droot.HasAnnotation(annotation)) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) Dim dannotation = droot.GetAnnotations("TestAnnotation").SingleOrDefault() Assert.NotNull(dannotation) Assert.NotSame(annotation, dannotation) ' not same instance Assert.Equal(annotation, dannotation) ' but are equivalent End Sub <Fact> <WorkItem(530374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530374")> Public Sub RoundtripSerializeDeepExpression() Dim text = <Goo><![CDATA[ Module Module15 Declare Function GetDesktopWindow Lib "User32" () As Integer Declare Function EnumChildWindows Lib "User32" (ByVal hw As Integer, ByVal lpWndProc As mydel, ByVal lp As Integer) As Integer Public intCounter As Integer Delegate Function mydel(ByVal hw As Integer, ByVal lp As Integer) As Integer Public d As mydel = New mydel(AddressOf EnumChildProc) Sub Main() Dim x As Object intCounter = 0 Dim hw As Integer hw = GetDesktopWindow() 'Call API passing ptr to callback x = EnumChildWindows(hw, d, 5) 'This should always be true, I would think If intCounter < 10 Then intcounter = 10 End If End Sub 'Callback function for EnumWindows Function EnumChildProc(ByVal hw As Integer, ByVal lp As Integer) As Integer intCounter = intCounter + 1 EnumChildProc = 1 End Function Sub Regression41614() Dim abc = "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" End Sub End Module ]]> </Goo>.Value RoundTrip(text, expectRecursive:=False) End Sub <Fact> <WorkItem(530374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530374")> Public Sub RoundtripSerializeDeepExpression2() Dim text = <Goo><![CDATA[ Module GroupJoin2 Sub Test1() q = From a In aa Group Join b As $ In bb On a Equals b End Sub End Module ]]> </Goo>.Value RoundTrip(text) End Sub <Fact> <WorkItem(1038237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1038237")> Public Sub RoundTripPragmaDirective() Dim text = <Goo><![CDATA[ #Disable Warning BC40000 ]]> </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim root = tree.GetRoot() Assert.True(root.ContainsDirectives) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim newRoot = VisualBasicSyntaxNode.DeserializeFrom(stream) Assert.True(newRoot.ContainsDirectives) End Sub End Class End Namespace
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/VisualStudio/CSharp/Impl/ProjectSystemShim/HACK_VariantStructure.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.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { /// <summary> /// This is a terrible, terrible hack around the C# project system in /// CCscMSBuildHostObject::SetDelaySign. To indicate a value of "unset" /// for boolean options, they create variant of type VT_BOOL with the boolean /// field being a value of "4". The CLR, if it marshals this variant, marshals /// it as a "true" which is indistinguishable from a real VARIANT_TRUE. So /// instead we define this structure of the same layout, and marshal the variant /// as this structure. We can then pick out this broken pattern, and convert /// it to null instead of true. /// </summary> internal struct HACK_VariantStructure { private readonly short _type; #pragma warning disable IDE0051 // Remove unused private members - padding bytes private readonly short _padding1; private readonly short _padding2; private readonly short _padding3; private readonly short _booleanValue; private readonly IntPtr _padding4; // this will be aligned to the IntPtr-sized address #pragma warning restore IDE0051 // Remove unused private members public unsafe object ConvertToObject() { if (_type == (short)VarEnum.VT_BOOL && _booleanValue == 4) { return null; } // Can't take an address of this since it might move, so.... var localCopy = this; return Marshal.GetObjectForNativeVariant((IntPtr)(&localCopy)); } } }
// Licensed to the .NET Foundation under one or more 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.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { /// <summary> /// This is a terrible, terrible hack around the C# project system in /// CCscMSBuildHostObject::SetDelaySign. To indicate a value of "unset" /// for boolean options, they create variant of type VT_BOOL with the boolean /// field being a value of "4". The CLR, if it marshals this variant, marshals /// it as a "true" which is indistinguishable from a real VARIANT_TRUE. So /// instead we define this structure of the same layout, and marshal the variant /// as this structure. We can then pick out this broken pattern, and convert /// it to null instead of true. /// </summary> internal struct HACK_VariantStructure { private readonly short _type; #pragma warning disable IDE0051 // Remove unused private members - padding bytes private readonly short _padding1; private readonly short _padding2; private readonly short _padding3; private readonly short _booleanValue; private readonly IntPtr _padding4; // this will be aligned to the IntPtr-sized address #pragma warning restore IDE0051 // Remove unused private members public unsafe object ConvertToObject() { if (_type == (short)VarEnum.VT_BOOL && _booleanValue == 4) { return null; } // Can't take an address of this since it might move, so.... var localCopy = this; return Marshal.GetObjectForNativeVariant((IntPtr)(&localCopy)); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicCodeGenerationHelpers.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Friend Module VisualBasicCodeGenerationHelpers Friend Sub AddAccessibilityModifiers( accessibility As Accessibility, tokens As ArrayBuilder(Of SyntaxToken), destination As CodeGenerationDestination, options As CodeGenerationOptions, nonStructureAccessibility As Accessibility) options = If(options, CodeGenerationOptions.Default) If Not options.GenerateDefaultAccessibility Then If destination = CodeGenerationDestination.StructType AndAlso accessibility = Accessibility.Public Then Return End If If destination <> CodeGenerationDestination.StructType AndAlso accessibility = nonStructureAccessibility Then Return End If End If Select Case accessibility Case Accessibility.Public tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) Case Accessibility.Protected tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.Private tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) Case Accessibility.Internal tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)) Case Accessibility.ProtectedAndInternal tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.ProtectedOrInternal tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)) End Select End Sub Public Function InsertAtIndex(members As SyntaxList(Of StatementSyntax), member As StatementSyntax, index As Integer) As SyntaxList(Of StatementSyntax) Dim result = New List(Of StatementSyntax)(members) ' then insert the new member. result.Insert(index, member) Return SyntaxFactory.List(result) End Function Public Function GenerateImplementsClause(explicitInterfaceOpt As ISymbol) As ImplementsClauseSyntax If explicitInterfaceOpt IsNot Nothing AndAlso explicitInterfaceOpt.ContainingType IsNot Nothing Then Dim type = explicitInterfaceOpt.ContainingType.GenerateTypeSyntax() If TypeOf type Is NameSyntax Then Return SyntaxFactory.ImplementsClause( interfaceMembers:=SyntaxFactory.SingletonSeparatedList( SyntaxFactory.QualifiedName( DirectCast(type, NameSyntax), explicitInterfaceOpt.Name.ToIdentifierName()))) End If End If Return Nothing End Function Public Function EnsureLastElasticTrivia(Of T As StatementSyntax)(statement As T) As T Dim lastToken = statement.GetLastToken(includeZeroWidth:=True) If lastToken.TrailingTrivia.Any(Function(trivia) trivia.IsElastic()) Then Return statement End If Return statement.WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker) End Function Public Function FirstMember(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.FirstOrDefault() End Function Public Function FirstMethod(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.LastOrDefault(Function(m) TypeOf m Is MethodBlockBaseSyntax OrElse TypeOf m Is MethodStatementSyntax) End Function Public Function LastField(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.LastOrDefault(Function(m) m.Kind = SyntaxKind.FieldDeclaration) End Function Public Function LastConstructor(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.LastOrDefault(Function(m) m.Kind = SyntaxKind.ConstructorBlock OrElse m.Kind = SyntaxKind.SubNewStatement) End Function Public Function LastMethod(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.LastOrDefault(Function(m) TypeOf m Is MethodBlockBaseSyntax OrElse TypeOf m Is MethodStatementSyntax) End Function Public Function LastOperator(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.LastOrDefault(Function(m) m.Kind = SyntaxKind.OperatorBlock OrElse m.Kind = SyntaxKind.OperatorStatement) End Function Private Function AfterDeclaration(Of TDeclaration As SyntaxNode)( options As CodeGenerationOptions, [next] As Func(Of SyntaxList(Of TDeclaration), TDeclaration)) As Func(Of SyntaxList(Of TDeclaration), TDeclaration) options = If(options, CodeGenerationOptions.Default) Return Function(list) If [next] IsNot Nothing Then Return [next](list) End If Return Nothing End Function End Function Private Function BeforeDeclaration(Of TDeclaration As SyntaxNode)( options As CodeGenerationOptions, [next] As Func(Of SyntaxList(Of TDeclaration), TDeclaration)) As Func(Of SyntaxList(Of TDeclaration), TDeclaration) options = If(options, CodeGenerationOptions.Default) Return Function(list) If [next] IsNot Nothing Then Return [next](list) End If Return Nothing End Function End Function Public Function Insert(Of TDeclaration As SyntaxNode)( declarationList As SyntaxList(Of TDeclaration), declaration As TDeclaration, options As CodeGenerationOptions, availableIndices As IList(Of Boolean), Optional after As Func(Of SyntaxList(Of TDeclaration), TDeclaration) = Nothing, Optional before As Func(Of SyntaxList(Of TDeclaration), TDeclaration) = Nothing) As SyntaxList(Of TDeclaration) after = AfterDeclaration(options, after) before = BeforeDeclaration(options, before) Dim index = GetInsertionIndex( declarationList, declaration, options, availableIndices, VisualBasicDeclarationComparer.WithoutNamesInstance, VisualBasicDeclarationComparer.WithNamesInstance, after, before) If availableIndices IsNot Nothing Then availableIndices.Insert(index, True) End If Return declarationList.Insert(index, declaration) End Function Public Function GetDestination(destination As SyntaxNode) As CodeGenerationDestination If destination IsNot Nothing Then Select Case destination.Kind Case SyntaxKind.ClassBlock Return CodeGenerationDestination.ClassType Case SyntaxKind.CompilationUnit Return CodeGenerationDestination.CompilationUnit Case SyntaxKind.EnumBlock Return CodeGenerationDestination.EnumType Case SyntaxKind.InterfaceBlock Return CodeGenerationDestination.InterfaceType Case SyntaxKind.ModuleBlock Return CodeGenerationDestination.ModuleType Case SyntaxKind.NamespaceBlock Return CodeGenerationDestination.Namespace Case SyntaxKind.StructureBlock Return CodeGenerationDestination.StructType Case Else Return CodeGenerationDestination.Unspecified End Select End If Return CodeGenerationDestination.Unspecified End Function Public Function ConditionallyAddDocumentationCommentTo(Of TSyntaxNode As SyntaxNode)( node As TSyntaxNode, symbol As ISymbol, options As CodeGenerationOptions, Optional cancellationToken As CancellationToken = Nothing) As TSyntaxNode If Not options.GenerateDocumentationComments OrElse node.GetLeadingTrivia().Any(Function(t) t.IsKind(SyntaxKind.DocumentationCommentTrivia)) Then Return node End If Dim comment As String = Nothing Dim result = If(TryGetDocumentationComment(symbol, "'''", comment, cancellationToken), node.WithPrependedLeadingTrivia(SyntaxFactory.ParseLeadingTrivia(comment)) _ .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker), node) Return result End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Friend Module VisualBasicCodeGenerationHelpers Friend Sub AddAccessibilityModifiers( accessibility As Accessibility, tokens As ArrayBuilder(Of SyntaxToken), destination As CodeGenerationDestination, options As CodeGenerationOptions, nonStructureAccessibility As Accessibility) options = If(options, CodeGenerationOptions.Default) If Not options.GenerateDefaultAccessibility Then If destination = CodeGenerationDestination.StructType AndAlso accessibility = Accessibility.Public Then Return End If If destination <> CodeGenerationDestination.StructType AndAlso accessibility = nonStructureAccessibility Then Return End If End If Select Case accessibility Case Accessibility.Public tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) Case Accessibility.Protected tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.Private tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) Case Accessibility.Internal tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)) Case Accessibility.ProtectedAndInternal tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.ProtectedOrInternal tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)) End Select End Sub Public Function InsertAtIndex(members As SyntaxList(Of StatementSyntax), member As StatementSyntax, index As Integer) As SyntaxList(Of StatementSyntax) Dim result = New List(Of StatementSyntax)(members) ' then insert the new member. result.Insert(index, member) Return SyntaxFactory.List(result) End Function Public Function GenerateImplementsClause(explicitInterfaceOpt As ISymbol) As ImplementsClauseSyntax If explicitInterfaceOpt IsNot Nothing AndAlso explicitInterfaceOpt.ContainingType IsNot Nothing Then Dim type = explicitInterfaceOpt.ContainingType.GenerateTypeSyntax() If TypeOf type Is NameSyntax Then Return SyntaxFactory.ImplementsClause( interfaceMembers:=SyntaxFactory.SingletonSeparatedList( SyntaxFactory.QualifiedName( DirectCast(type, NameSyntax), explicitInterfaceOpt.Name.ToIdentifierName()))) End If End If Return Nothing End Function Public Function EnsureLastElasticTrivia(Of T As StatementSyntax)(statement As T) As T Dim lastToken = statement.GetLastToken(includeZeroWidth:=True) If lastToken.TrailingTrivia.Any(Function(trivia) trivia.IsElastic()) Then Return statement End If Return statement.WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker) End Function Public Function FirstMember(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.FirstOrDefault() End Function Public Function FirstMethod(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.LastOrDefault(Function(m) TypeOf m Is MethodBlockBaseSyntax OrElse TypeOf m Is MethodStatementSyntax) End Function Public Function LastField(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.LastOrDefault(Function(m) m.Kind = SyntaxKind.FieldDeclaration) End Function Public Function LastConstructor(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.LastOrDefault(Function(m) m.Kind = SyntaxKind.ConstructorBlock OrElse m.Kind = SyntaxKind.SubNewStatement) End Function Public Function LastMethod(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.LastOrDefault(Function(m) TypeOf m Is MethodBlockBaseSyntax OrElse TypeOf m Is MethodStatementSyntax) End Function Public Function LastOperator(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.LastOrDefault(Function(m) m.Kind = SyntaxKind.OperatorBlock OrElse m.Kind = SyntaxKind.OperatorStatement) End Function Private Function AfterDeclaration(Of TDeclaration As SyntaxNode)( options As CodeGenerationOptions, [next] As Func(Of SyntaxList(Of TDeclaration), TDeclaration)) As Func(Of SyntaxList(Of TDeclaration), TDeclaration) options = If(options, CodeGenerationOptions.Default) Return Function(list) If [next] IsNot Nothing Then Return [next](list) End If Return Nothing End Function End Function Private Function BeforeDeclaration(Of TDeclaration As SyntaxNode)( options As CodeGenerationOptions, [next] As Func(Of SyntaxList(Of TDeclaration), TDeclaration)) As Func(Of SyntaxList(Of TDeclaration), TDeclaration) options = If(options, CodeGenerationOptions.Default) Return Function(list) If [next] IsNot Nothing Then Return [next](list) End If Return Nothing End Function End Function Public Function Insert(Of TDeclaration As SyntaxNode)( declarationList As SyntaxList(Of TDeclaration), declaration As TDeclaration, options As CodeGenerationOptions, availableIndices As IList(Of Boolean), Optional after As Func(Of SyntaxList(Of TDeclaration), TDeclaration) = Nothing, Optional before As Func(Of SyntaxList(Of TDeclaration), TDeclaration) = Nothing) As SyntaxList(Of TDeclaration) after = AfterDeclaration(options, after) before = BeforeDeclaration(options, before) Dim index = GetInsertionIndex( declarationList, declaration, options, availableIndices, VisualBasicDeclarationComparer.WithoutNamesInstance, VisualBasicDeclarationComparer.WithNamesInstance, after, before) If availableIndices IsNot Nothing Then availableIndices.Insert(index, True) End If Return declarationList.Insert(index, declaration) End Function Public Function GetDestination(destination As SyntaxNode) As CodeGenerationDestination If destination IsNot Nothing Then Select Case destination.Kind Case SyntaxKind.ClassBlock Return CodeGenerationDestination.ClassType Case SyntaxKind.CompilationUnit Return CodeGenerationDestination.CompilationUnit Case SyntaxKind.EnumBlock Return CodeGenerationDestination.EnumType Case SyntaxKind.InterfaceBlock Return CodeGenerationDestination.InterfaceType Case SyntaxKind.ModuleBlock Return CodeGenerationDestination.ModuleType Case SyntaxKind.NamespaceBlock Return CodeGenerationDestination.Namespace Case SyntaxKind.StructureBlock Return CodeGenerationDestination.StructType Case Else Return CodeGenerationDestination.Unspecified End Select End If Return CodeGenerationDestination.Unspecified End Function Public Function ConditionallyAddDocumentationCommentTo(Of TSyntaxNode As SyntaxNode)( node As TSyntaxNode, symbol As ISymbol, options As CodeGenerationOptions, Optional cancellationToken As CancellationToken = Nothing) As TSyntaxNode If Not options.GenerateDocumentationComments OrElse node.GetLeadingTrivia().Any(Function(t) t.IsKind(SyntaxKind.DocumentationCommentTrivia)) Then Return node End If Dim comment As String = Nothing Dim result = If(TryGetDocumentationComment(symbol, "'''", comment, cancellationToken), node.WithPrependedLeadingTrivia(SyntaxFactory.ParseLeadingTrivia(comment)) _ .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker), node) Return result End Function End Module End Namespace
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/VisualStudio/Core/Test/CodeModel/AbstractCodeNamespaceTests.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.VisualStudio.LanguageServices.UnitTests.CodeModel Public MustInherit Class AbstractCodeNamespaceTests Inherits AbstractCodeElementTests(Of EnvDTE.CodeNamespace) Protected Overrides Function GetStartPointFunc(codeElement As EnvDTE.CodeNamespace) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetStartPoint(part) End Function Protected Overrides Function GetEndPointFunc(codeElement As EnvDTE.CodeNamespace) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetEndPoint(part) End Function Protected Overrides Function GetComment(codeElement As EnvDTE.CodeNamespace) As String Return codeElement.Comment End Function Protected Overrides Function GetCommentSetter(codeElement As EnvDTE.CodeNamespace) As Action(Of String) Return Sub(value) codeElement.Comment = value End Function Protected Overrides Function GetDocComment(codeElement As EnvDTE.CodeNamespace) As String Return codeElement.DocComment End Function Protected Overrides Function GetDocCommentSetter(codeElement As EnvDTE.CodeNamespace) As Action(Of String) Return Sub(value) codeElement.DocComment = value End Function Protected Overrides Function GetFullName(codeElement As EnvDTE.CodeNamespace) As String Throw New NotImplementedException() End Function Protected Overrides Function GetKind(codeElement As EnvDTE.CodeNamespace) As EnvDTE.vsCMElement Return codeElement.Kind End Function Protected Overrides Function GetName(codeElement As EnvDTE.CodeNamespace) As String Return codeElement.Name End Function Protected Overrides Function GetNameSetter(codeElement As EnvDTE.CodeNamespace) As Action(Of String) Return Sub(name) codeElement.Name = name End Function Protected Overrides Function GetParent(codeElement As EnvDTE.CodeNamespace) As Object Return codeElement.Parent End Function Protected Overrides Sub RemoveChild(codeElement As EnvDTE.CodeNamespace, member As Object) codeElement.Remove(member) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Public MustInherit Class AbstractCodeNamespaceTests Inherits AbstractCodeElementTests(Of EnvDTE.CodeNamespace) Protected Overrides Function GetStartPointFunc(codeElement As EnvDTE.CodeNamespace) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetStartPoint(part) End Function Protected Overrides Function GetEndPointFunc(codeElement As EnvDTE.CodeNamespace) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetEndPoint(part) End Function Protected Overrides Function GetComment(codeElement As EnvDTE.CodeNamespace) As String Return codeElement.Comment End Function Protected Overrides Function GetCommentSetter(codeElement As EnvDTE.CodeNamespace) As Action(Of String) Return Sub(value) codeElement.Comment = value End Function Protected Overrides Function GetDocComment(codeElement As EnvDTE.CodeNamespace) As String Return codeElement.DocComment End Function Protected Overrides Function GetDocCommentSetter(codeElement As EnvDTE.CodeNamespace) As Action(Of String) Return Sub(value) codeElement.DocComment = value End Function Protected Overrides Function GetFullName(codeElement As EnvDTE.CodeNamespace) As String Throw New NotImplementedException() End Function Protected Overrides Function GetKind(codeElement As EnvDTE.CodeNamespace) As EnvDTE.vsCMElement Return codeElement.Kind End Function Protected Overrides Function GetName(codeElement As EnvDTE.CodeNamespace) As String Return codeElement.Name End Function Protected Overrides Function GetNameSetter(codeElement As EnvDTE.CodeNamespace) As Action(Of String) Return Sub(name) codeElement.Name = name End Function Protected Overrides Function GetParent(codeElement As EnvDTE.CodeNamespace) As Object Return codeElement.Parent End Function Protected Overrides Sub RemoveChild(codeElement As EnvDTE.CodeNamespace, member As Object) codeElement.Remove(member) End Sub End Class End Namespace
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/EditorFeatures/TestUtilities/EditAndContinue/ActiveStatementTestHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal static class ActiveStatementTestHelpers { public static ImmutableArray<ManagedActiveStatementDebugInfo> GetActiveStatementDebugInfosCSharp( string[] markedSources, string[]? filePaths = null, int[]? methodRowIds = null, Guid[]? modules = null, int[]? methodVersions = null, int[]? ilOffsets = null, ActiveStatementFlags[]? flags = null) { return ActiveStatementsDescription.GetActiveStatementDebugInfos( (source, path) => SyntaxFactory.ParseSyntaxTree(source, path: path), markedSources, filePaths, extension: ".cs", methodRowIds, modules, methodVersions, ilOffsets, flags); } public static string Delete(string src, string marker) { while (true) { var startStr = "/*delete" + marker; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var end = src.IndexOf(endStr, start + startStr.Length) + endStr.Length; src = src.Substring(0, start) + src.Substring(end); } } /// <summary> /// Inserts new lines into the text at the position indicated by /*insert<paramref name="marker"/>[{number-of-lines-to-insert}]*/. /// </summary> public static string InsertNewLines(string src, string marker) { while (true) { var startStr = "/*insert" + marker + "["; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var startOfLineCount = start + startStr.Length; var endOfLineCount = src.IndexOf(']', startOfLineCount); var lineCount = int.Parse(src.Substring(startOfLineCount, endOfLineCount - startOfLineCount)); var end = src.IndexOf(endStr, endOfLineCount) + endStr.Length; src = src.Substring(0, start) + string.Join("", Enumerable.Repeat(Environment.NewLine, lineCount)) + src.Substring(end); } } public static string Update(string src, string marker) => InsertNewLines(Delete(src, marker), marker); public static string InspectActiveStatement(ActiveStatement statement) => $"{statement.Ordinal}: {statement.FileSpan} flags=[{statement.Flags}]"; public static string InspectActiveStatementAndInstruction(ActiveStatement statement) => InspectActiveStatement(statement) + " " + statement.InstructionId.GetDebuggerDisplay(); public static string InspectActiveStatementAndInstruction(ActiveStatement statement, SourceText text) => InspectActiveStatementAndInstruction(statement) + $" '{GetFirstLineText(statement.Span, text)}'"; public static string InspectActiveStatementUpdate(ManagedActiveStatementUpdate update) => $"{update.Method.GetDebuggerDisplay()} IL_{update.ILOffset:X4}: {update.NewSpan.GetDebuggerDisplay()}"; public static IEnumerable<string> InspectNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> regions) => regions.OrderBy(r => r.Key.Token).Select(r => $"{r.Key.Method.GetDebuggerDisplay()} | {string.Join(", ", r.Value.Select(r => r.GetDebuggerDisplay()))}"); public static string InspectExceptionRegionUpdate(ManagedExceptionRegionUpdate r) => $"{r.Method.GetDebuggerDisplay()} | {r.NewSpan.GetDebuggerDisplay()} Delta={r.Delta}"; public static string GetFirstLineText(LinePositionSpan span, SourceText text) => text.Lines[span.Start.Line].ToString().Trim(); public static string InspectSequencePointUpdates(SequencePointUpdates updates) => $"{updates.FileName}: [{string.Join(", ", updates.LineUpdates.Select(u => $"{u.OldLine} -> {u.NewLine}"))}]"; public static IEnumerable<string> Inspect(this IEnumerable<SequencePointUpdates> updates) => updates.Select(InspectSequencePointUpdates); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal static class ActiveStatementTestHelpers { public static ImmutableArray<ManagedActiveStatementDebugInfo> GetActiveStatementDebugInfosCSharp( string[] markedSources, string[]? filePaths = null, int[]? methodRowIds = null, Guid[]? modules = null, int[]? methodVersions = null, int[]? ilOffsets = null, ActiveStatementFlags[]? flags = null) { return ActiveStatementsDescription.GetActiveStatementDebugInfos( (source, path) => SyntaxFactory.ParseSyntaxTree(source, path: path), markedSources, filePaths, extension: ".cs", methodRowIds, modules, methodVersions, ilOffsets, flags); } public static string Delete(string src, string marker) { while (true) { var startStr = "/*delete" + marker; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var end = src.IndexOf(endStr, start + startStr.Length) + endStr.Length; src = src.Substring(0, start) + src.Substring(end); } } /// <summary> /// Inserts new lines into the text at the position indicated by /*insert<paramref name="marker"/>[{number-of-lines-to-insert}]*/. /// </summary> public static string InsertNewLines(string src, string marker) { while (true) { var startStr = "/*insert" + marker + "["; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var startOfLineCount = start + startStr.Length; var endOfLineCount = src.IndexOf(']', startOfLineCount); var lineCount = int.Parse(src.Substring(startOfLineCount, endOfLineCount - startOfLineCount)); var end = src.IndexOf(endStr, endOfLineCount) + endStr.Length; src = src.Substring(0, start) + string.Join("", Enumerable.Repeat(Environment.NewLine, lineCount)) + src.Substring(end); } } public static string Update(string src, string marker) => InsertNewLines(Delete(src, marker), marker); public static string InspectActiveStatement(ActiveStatement statement) => $"{statement.Ordinal}: {statement.FileSpan} flags=[{statement.Flags}]"; public static string InspectActiveStatementAndInstruction(ActiveStatement statement) => InspectActiveStatement(statement) + " " + statement.InstructionId.GetDebuggerDisplay(); public static string InspectActiveStatementAndInstruction(ActiveStatement statement, SourceText text) => InspectActiveStatementAndInstruction(statement) + $" '{GetFirstLineText(statement.Span, text)}'"; public static string InspectActiveStatementUpdate(ManagedActiveStatementUpdate update) => $"{update.Method.GetDebuggerDisplay()} IL_{update.ILOffset:X4}: {update.NewSpan.GetDebuggerDisplay()}"; public static IEnumerable<string> InspectNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> regions) => regions.OrderBy(r => r.Key.Token).Select(r => $"{r.Key.Method.GetDebuggerDisplay()} | {string.Join(", ", r.Value.Select(r => r.GetDebuggerDisplay()))}"); public static string InspectExceptionRegionUpdate(ManagedExceptionRegionUpdate r) => $"{r.Method.GetDebuggerDisplay()} | {r.NewSpan.GetDebuggerDisplay()} Delta={r.Delta}"; public static string GetFirstLineText(LinePositionSpan span, SourceText text) => text.Lines[span.Start.Line].ToString().Trim(); public static string InspectSequencePointUpdates(SequencePointUpdates updates) => $"{updates.FileName}: [{string.Join(", ", updates.LineUpdates.Select(u => $"{u.OldLine} -> {u.NewLine}"))}]"; public static IEnumerable<string> Inspect(this IEnumerable<SequencePointUpdates> updates) => updates.Select(InspectSequencePointUpdates); } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/EditorFeatures/CSharpTest/ConvertAnonymousTypeToClass/ConvertAnonymousTypeToClassTests.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.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.ConvertAnonymousTypeToClass; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertAnonymousTypeToClass { public class ConvertAnonymousTypeToClassTests : AbstractCSharpCodeActionTest { private static readonly ParseOptions CSharp8 = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8); protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpConvertAnonymousTypeToClassCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousType() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousType_FileScopedNamespace() { var text = @" namespace N; class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } "; var expected = @" namespace N; class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousType_CSharp9() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(1, 2); } } internal record NewRecord(int A, int B); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousType_Explicit() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { int hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnEmptyAnonymousType() { await TestInRegularAndScriptAsync(@" class Test { void Method() { var t1 = [||]new { }; } } ", @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(); } } internal class NewClass { public NewClass() { } public override bool Equals(object obj) { return obj is NewClass other; } public override int GetHashCode() { return 0; } }", parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnEmptyAnonymousType_CSharp9() { await TestInRegularAndScriptAsync(@" class Test { void Method() { var t1 = [||]new { }; } } ", @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(); } } internal record NewRecord(); "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnSingleFieldAnonymousType() { await TestInRegularAndScriptAsync(@" class Test { void Method() { var t1 = [||]new { a = 1 }; } } ", @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1); } } internal class NewClass { public int A { get; } public NewClass(int a) { A = a; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A; } public override int GetHashCode() { return -862436692 + A.GetHashCode(); } }", parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnSingleFieldAnonymousType_CSharp9() { await TestInRegularAndScriptAsync(@" class Test { void Method() { var t1 = [||]new { a = 1 }; } } ", @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(1); } } internal record NewRecord(int A); "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeWithInferredName() { var text = @" class Test { void Method(int b) { var t1 = [||]new { a = 1, b }; } } "; var expected = @" class Test { void Method(int b) { var t1 = new {|Rename:NewClass|}(1, b); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeWithInferredName_CSharp9() { var text = @" class Test { void Method(int b) { var t1 = [||]new { a = 1, b }; } } "; var expected = @" class Test { void Method(int b) { var t1 = new {|Rename:NewRecord|}(1, b); } } internal record NewRecord(int A, int B); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertMultipleInstancesInSameMethod() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, 4); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertMultipleInstancesInSameMethod_CSharp9() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(1, 2); var t2 = new NewRecord(3, 4); } } internal record NewRecord(int A, int B); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertMultipleInstancesAcrossMethods() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } void Method2() { var t1 = new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, 4); } void Method2() { var t1 = new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnlyConvertMatchingTypesInSameMethod() { var text = @" class Test { void Method(int b) { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b }; var t3 = new { a = 4 }; var t4 = new { b = 5, a = 6 }; } } "; var expected = @" class Test { void Method(int b) { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, b); var t3 = new { a = 4 }; var t4 = new { b = 5, a = 6 }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestFixAllMatchesInSingleMethod() { var text = @" class Test { void Method(int b) { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b }; var t3 = new { a = 4 }; var t4 = new { b = 5, a = 6 }; } } "; var expected = @" class Test { void Method(int b) { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, b); var t3 = new { a = 4 }; var t4 = new { b = 5, a = 6 }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestFixNotAcrossMethods() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } void Method2() { var t1 = new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, 4); } void Method2() { var t1 = new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestTrivia() { var text = @" class Test { void Method() { var t1 = /*1*/ [||]new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ; } } "; var expected = @" class Test { void Method() { var t1 = /*1*/ new {|Rename:NewClass|}( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestTrivia2() { var text = @" class Test { void Method() { var t1 = /*1*/ [||]new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ; var t2 = /*1*/ new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ; } } "; var expected = @" class Test { void Method() { var t1 = /*1*/ new {|Rename:NewClass|}( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ; var t2 = /*1*/ new NewClass( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task NotIfReferencesAnonymousTypeInternally() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = new { c = 1, d = 2 } }; } } "; await TestMissingInRegularAndScriptAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertMultipleNestedInstancesInSameMethod() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = (object)new { a = 1, b = default(object) } }; } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, (object)new NewClass(1, default(object))); } } internal class NewClass { public int A { get; } public object B { get; } public NewClass(int a, object b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && EqualityComparer<object>.Default.Equals(B, other.B); } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(B); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task RenameAnnotationOnStartingPoint() { var text = @" class Test { void Method() { var t1 = new { a = 1, b = 2 }; var t2 = [||]new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new NewClass(1, 2); var t2 = new {|Rename:NewClass|}(3, 4); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task UpdateReferences() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; Console.WriteLine(t1.a + t1?.b); } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); Console.WriteLine(t1.A + t1?.B); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task CapturedTypeParameters() { var text = @" class Test<X> where X : struct { void Method<Y>(List<X> x, Y[] y) where Y : class, new() { var t1 = [||]new { a = x, b = y }; } } "; var expected = @" class Test<X> where X : struct { void Method<Y>(List<X> x, Y[] y) where Y : class, new() { var t1 = new {|Rename:NewClass|}<X, Y>(x, y); } } internal class NewClass<X, Y> where X : struct where Y : class, new() { public List<X> A { get; } public Y[] B { get; } public NewClass(List<X> a, Y[] b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass<X, Y> other && System.Collections.Generic.EqualityComparer<List<X>>.Default.Equals(A, other.A) && System.Collections.Generic.EqualityComparer<Y[]>.Default.Equals(B, other.B); } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<List<X>>.Default.GetHashCode(A); hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<Y[]>.Default.GetHashCode(B); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task CapturedTypeParameters_CSharp9() { var text = @" class Test<X> where X : struct { void Method<Y>(List<X> x, Y[] y) where Y : class, new() { var t1 = [||]new { a = x, b = y }; } } "; var expected = @" class Test<X> where X : struct { void Method<Y>(List<X> x, Y[] y) where Y : class, new() { var t1 = new {|Rename:NewRecord|}<X, Y>(x, y); } } internal record NewRecord<X, Y>(List<X> A, Y[] B) where X : struct where Y : class, new(); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task NewTypeNameCollision() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } class NewClass { } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass1|}(1, 2); } } class NewClass { } internal class NewClass1 { public int A { get; } public int B { get; } public NewClass1(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass1 other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestDuplicatedName() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, a = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int Item { get; } public NewClass(int a, int item) { A = a; Item = item; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && Item == other.Item; } public override int GetHashCode() { var hashCode = -335756622; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + Item.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestDuplicatedName_CSharp9() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, a = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(1, 2); } } internal record NewRecord(int A, int Item); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestNewSelection() { var text = @" class Test { void Method() { var t1 = [|new|] { a = 1, b = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestInLambda1() { var text = @" using System; class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; Action a = () => { var t2 = new { a = 3, b = 4 }; }; } } "; var expected = @" using System; class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); Action a = () => { var t2 = new NewClass(3, 4); }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestInLambda2() { var text = @" using System; class Test { void Method() { var t1 = new { a = 1, b = 2 }; Action a = () => { var t2 = [||]new { a = 3, b = 4 }; }; } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewClass(1, 2); Action a = () => { var t2 = new {|Rename:NewClass|}(3, 4); }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestInLocalFunction1() { var text = @" using System; class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; void Goo() { var t2 = new { a = 3, b = 4 }; } } } "; var expected = @" using System; class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); void Goo() { var t2 = new NewClass(3, 4); } } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestInLocalFunction2() { var text = @" using System; class Test { void Method() { var t1 = new { a = 1, b = 2 }; void Goo() { var t2 = [||]new { a = 3, b = 4 }; } } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewClass(1, 2); void Goo() { var t2 = new {|Rename:NewClass|}(3, 4); } } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeSelection1() { var text = @" class Test { void Method() { var t1 = [|new { a = 1, b = 2 }|]; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeSelection2() { var text = @" class Test { void Method() { [|var t1 = new { a = 1, b = 2 };|] } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeSelection3() { var text = @" class Test { void Method() { var t1 = [|new { a = 1, b = 2 };|] } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(45747, "https://github.com/dotnet/roslyn/issues/45747")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertOmittingTrailingComma() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2, }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}( 1, 2 ); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(45747, "https://github.com/dotnet/roslyn/issues/45747")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertOmittingTrailingCommaButPreservingTrivia() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 // and // more , }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}( 1, 2 // and // more ); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } } }
// Licensed to the .NET Foundation under one or more 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.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.ConvertAnonymousTypeToClass; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertAnonymousTypeToClass { public class ConvertAnonymousTypeToClassTests : AbstractCSharpCodeActionTest { private static readonly ParseOptions CSharp8 = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8); protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpConvertAnonymousTypeToClassCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousType() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousType_FileScopedNamespace() { var text = @" namespace N; class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } "; var expected = @" namespace N; class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousType_CSharp9() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(1, 2); } } internal record NewRecord(int A, int B); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousType_Explicit() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { int hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnEmptyAnonymousType() { await TestInRegularAndScriptAsync(@" class Test { void Method() { var t1 = [||]new { }; } } ", @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(); } } internal class NewClass { public NewClass() { } public override bool Equals(object obj) { return obj is NewClass other; } public override int GetHashCode() { return 0; } }", parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnEmptyAnonymousType_CSharp9() { await TestInRegularAndScriptAsync(@" class Test { void Method() { var t1 = [||]new { }; } } ", @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(); } } internal record NewRecord(); "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnSingleFieldAnonymousType() { await TestInRegularAndScriptAsync(@" class Test { void Method() { var t1 = [||]new { a = 1 }; } } ", @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1); } } internal class NewClass { public int A { get; } public NewClass(int a) { A = a; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A; } public override int GetHashCode() { return -862436692 + A.GetHashCode(); } }", parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnSingleFieldAnonymousType_CSharp9() { await TestInRegularAndScriptAsync(@" class Test { void Method() { var t1 = [||]new { a = 1 }; } } ", @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(1); } } internal record NewRecord(int A); "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeWithInferredName() { var text = @" class Test { void Method(int b) { var t1 = [||]new { a = 1, b }; } } "; var expected = @" class Test { void Method(int b) { var t1 = new {|Rename:NewClass|}(1, b); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeWithInferredName_CSharp9() { var text = @" class Test { void Method(int b) { var t1 = [||]new { a = 1, b }; } } "; var expected = @" class Test { void Method(int b) { var t1 = new {|Rename:NewRecord|}(1, b); } } internal record NewRecord(int A, int B); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertMultipleInstancesInSameMethod() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, 4); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertMultipleInstancesInSameMethod_CSharp9() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(1, 2); var t2 = new NewRecord(3, 4); } } internal record NewRecord(int A, int B); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertMultipleInstancesAcrossMethods() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } void Method2() { var t1 = new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, 4); } void Method2() { var t1 = new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnlyConvertMatchingTypesInSameMethod() { var text = @" class Test { void Method(int b) { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b }; var t3 = new { a = 4 }; var t4 = new { b = 5, a = 6 }; } } "; var expected = @" class Test { void Method(int b) { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, b); var t3 = new { a = 4 }; var t4 = new { b = 5, a = 6 }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestFixAllMatchesInSingleMethod() { var text = @" class Test { void Method(int b) { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b }; var t3 = new { a = 4 }; var t4 = new { b = 5, a = 6 }; } } "; var expected = @" class Test { void Method(int b) { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, b); var t3 = new { a = 4 }; var t4 = new { b = 5, a = 6 }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestFixNotAcrossMethods() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } void Method2() { var t1 = new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, 4); } void Method2() { var t1 = new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestTrivia() { var text = @" class Test { void Method() { var t1 = /*1*/ [||]new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ; } } "; var expected = @" class Test { void Method() { var t1 = /*1*/ new {|Rename:NewClass|}( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestTrivia2() { var text = @" class Test { void Method() { var t1 = /*1*/ [||]new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ; var t2 = /*1*/ new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ; } } "; var expected = @" class Test { void Method() { var t1 = /*1*/ new {|Rename:NewClass|}( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ; var t2 = /*1*/ new NewClass( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task NotIfReferencesAnonymousTypeInternally() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = new { c = 1, d = 2 } }; } } "; await TestMissingInRegularAndScriptAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertMultipleNestedInstancesInSameMethod() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = (object)new { a = 1, b = default(object) } }; } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, (object)new NewClass(1, default(object))); } } internal class NewClass { public int A { get; } public object B { get; } public NewClass(int a, object b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && EqualityComparer<object>.Default.Equals(B, other.B); } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(B); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task RenameAnnotationOnStartingPoint() { var text = @" class Test { void Method() { var t1 = new { a = 1, b = 2 }; var t2 = [||]new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new NewClass(1, 2); var t2 = new {|Rename:NewClass|}(3, 4); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task UpdateReferences() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; Console.WriteLine(t1.a + t1?.b); } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); Console.WriteLine(t1.A + t1?.B); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task CapturedTypeParameters() { var text = @" class Test<X> where X : struct { void Method<Y>(List<X> x, Y[] y) where Y : class, new() { var t1 = [||]new { a = x, b = y }; } } "; var expected = @" class Test<X> where X : struct { void Method<Y>(List<X> x, Y[] y) where Y : class, new() { var t1 = new {|Rename:NewClass|}<X, Y>(x, y); } } internal class NewClass<X, Y> where X : struct where Y : class, new() { public List<X> A { get; } public Y[] B { get; } public NewClass(List<X> a, Y[] b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass<X, Y> other && System.Collections.Generic.EqualityComparer<List<X>>.Default.Equals(A, other.A) && System.Collections.Generic.EqualityComparer<Y[]>.Default.Equals(B, other.B); } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<List<X>>.Default.GetHashCode(A); hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<Y[]>.Default.GetHashCode(B); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task CapturedTypeParameters_CSharp9() { var text = @" class Test<X> where X : struct { void Method<Y>(List<X> x, Y[] y) where Y : class, new() { var t1 = [||]new { a = x, b = y }; } } "; var expected = @" class Test<X> where X : struct { void Method<Y>(List<X> x, Y[] y) where Y : class, new() { var t1 = new {|Rename:NewRecord|}<X, Y>(x, y); } } internal record NewRecord<X, Y>(List<X> A, Y[] B) where X : struct where Y : class, new(); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task NewTypeNameCollision() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } class NewClass { } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass1|}(1, 2); } } class NewClass { } internal class NewClass1 { public int A { get; } public int B { get; } public NewClass1(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass1 other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestDuplicatedName() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, a = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int Item { get; } public NewClass(int a, int item) { A = a; Item = item; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && Item == other.Item; } public override int GetHashCode() { var hashCode = -335756622; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + Item.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestDuplicatedName_CSharp9() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, a = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(1, 2); } } internal record NewRecord(int A, int Item); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestNewSelection() { var text = @" class Test { void Method() { var t1 = [|new|] { a = 1, b = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestInLambda1() { var text = @" using System; class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; Action a = () => { var t2 = new { a = 3, b = 4 }; }; } } "; var expected = @" using System; class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); Action a = () => { var t2 = new NewClass(3, 4); }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestInLambda2() { var text = @" using System; class Test { void Method() { var t1 = new { a = 1, b = 2 }; Action a = () => { var t2 = [||]new { a = 3, b = 4 }; }; } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewClass(1, 2); Action a = () => { var t2 = new {|Rename:NewClass|}(3, 4); }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestInLocalFunction1() { var text = @" using System; class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; void Goo() { var t2 = new { a = 3, b = 4 }; } } } "; var expected = @" using System; class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); void Goo() { var t2 = new NewClass(3, 4); } } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestInLocalFunction2() { var text = @" using System; class Test { void Method() { var t1 = new { a = 1, b = 2 }; void Goo() { var t2 = [||]new { a = 3, b = 4 }; } } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewClass(1, 2); void Goo() { var t2 = new {|Rename:NewClass|}(3, 4); } } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeSelection1() { var text = @" class Test { void Method() { var t1 = [|new { a = 1, b = 2 }|]; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeSelection2() { var text = @" class Test { void Method() { [|var t1 = new { a = 1, b = 2 };|] } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeSelection3() { var text = @" class Test { void Method() { var t1 = [|new { a = 1, b = 2 };|] } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(45747, "https://github.com/dotnet/roslyn/issues/45747")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertOmittingTrailingComma() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2, }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}( 1, 2 ); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(45747, "https://github.com/dotnet/roslyn/issues/45747")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertOmittingTrailingCommaButPreservingTrivia() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 // and // more , }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}( 1, 2 // and // more ); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Features/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensHandler.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 Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens { /// <summary> /// Computes the semantic tokens for a whole document. /// </summary> /// <remarks> /// This handler is invoked when a user opens a file. Depending on the size of the file, the full token set may be /// slow to compute, so the <see cref="SemanticTokensRangeHandler"/> is also called when a file is opened in order /// to render UI results quickly until this handler finishes running. /// Unlike the range handler, the whole document handler may be called again if the LSP client finds an edit that /// is difficult to correctly apply to their tags cache. This allows for reliable recovery from errors and accounts /// for limitations in the edits application logic. /// </remarks> internal class SemanticTokensHandler : IRequestHandler<LSP.SemanticTokensParams, LSP.SemanticTokens> { private readonly SemanticTokensCache _tokensCache; public SemanticTokensHandler(SemanticTokensCache tokensCache) { _tokensCache = tokensCache; } public string Method => LSP.Methods.TextDocumentSemanticTokensFullName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.SemanticTokensParams request) { Contract.ThrowIfNull(request.TextDocument); return request.TextDocument; } public async Task<LSP.SemanticTokens> HandleRequestAsync( LSP.SemanticTokensParams request, RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(request.TextDocument, "TextDocument is null."); Contract.ThrowIfNull(context.Document, "Document is null."); var resultId = _tokensCache.GetNextResultId(); var tokensData = await SemanticTokensHelpers.ComputeSemanticTokensDataAsync( context.Document, SemanticTokensCache.TokenTypeToIndex, range: null, cancellationToken).ConfigureAwait(false); var tokens = new LSP.SemanticTokens { ResultId = resultId, Data = tokensData }; await _tokensCache.UpdateCacheAsync(request.TextDocument.Uri, tokens, cancellationToken).ConfigureAwait(false); return tokens; } } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens { /// <summary> /// Computes the semantic tokens for a whole document. /// </summary> /// <remarks> /// This handler is invoked when a user opens a file. Depending on the size of the file, the full token set may be /// slow to compute, so the <see cref="SemanticTokensRangeHandler"/> is also called when a file is opened in order /// to render UI results quickly until this handler finishes running. /// Unlike the range handler, the whole document handler may be called again if the LSP client finds an edit that /// is difficult to correctly apply to their tags cache. This allows for reliable recovery from errors and accounts /// for limitations in the edits application logic. /// </remarks> internal class SemanticTokensHandler : IRequestHandler<LSP.SemanticTokensParams, LSP.SemanticTokens> { private readonly SemanticTokensCache _tokensCache; public SemanticTokensHandler(SemanticTokensCache tokensCache) { _tokensCache = tokensCache; } public string Method => LSP.Methods.TextDocumentSemanticTokensFullName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.SemanticTokensParams request) { Contract.ThrowIfNull(request.TextDocument); return request.TextDocument; } public async Task<LSP.SemanticTokens> HandleRequestAsync( LSP.SemanticTokensParams request, RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(request.TextDocument, "TextDocument is null."); Contract.ThrowIfNull(context.Document, "Document is null."); var resultId = _tokensCache.GetNextResultId(); var tokensData = await SemanticTokensHelpers.ComputeSemanticTokensDataAsync( context.Document, SemanticTokensCache.TokenTypeToIndex, range: null, cancellationToken).ConfigureAwait(false); var tokens = new LSP.SemanticTokens { ResultId = resultId, Data = tokensData }; await _tokensCache.UpdateCacheAsync(request.TextDocument.Uri, tokens, cancellationToken).ConfigureAwait(false); return tokens; } } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/Test/Core/TestBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using static TestReferences.NetFx; using static Roslyn.Test.Utilities.TestMetadata; using Microsoft.CodeAnalysis.Test.Resources.Proprietary; namespace Roslyn.Test.Utilities { /// <summary> /// Base class for all unit test classes. /// </summary> public abstract class TestBase : IDisposable { private TempRoot _temp; protected TestBase() { } public static string GetUniqueName() { return Guid.NewGuid().ToString("D"); } public TempRoot Temp { get { if (_temp == null) { _temp = new TempRoot(); } return _temp; } } public virtual void Dispose() { if (_temp != null) { _temp.Dispose(); } } #region Metadata References /// <summary> /// Helper for atomically acquiring and saving a metadata reference. Necessary /// if the acquired reference will ever be used in object identity comparisons. /// </summary> private static MetadataReference GetOrCreateMetadataReference(ref MetadataReference field, Func<MetadataReference> getReference) { if (field == null) { Interlocked.CompareExchange(ref field, getReference(), null); } return field; } private static readonly Lazy<MetadataReference[]> s_lazyDefaultVbReferences = new Lazy<MetadataReference[]>( () => new[] { Net40.mscorlib, Net40.System, Net40.SystemCore, Net40.MicrosoftVisualBasic }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference[] DefaultVbReferences => s_lazyDefaultVbReferences.Value; private static readonly Lazy<MetadataReference[]> s_lazyLatestVbReferences = new Lazy<MetadataReference[]>( () => new[] { Net451.mscorlib, Net451.System, Net451.SystemCore, Net451.MicrosoftVisualBasic }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference[] LatestVbReferences => s_lazyLatestVbReferences.Value; public static readonly AssemblyName RuntimeCorLibName = RuntimeUtilities.IsCoreClrRuntime ? new AssemblyName("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51") : new AssemblyName("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); /// <summary> /// The array of 7 metadataimagereferences that are required to compile /// against windows.winmd (including windows.winmd itself). /// </summary> private static readonly Lazy<MetadataReference[]> s_winRtRefs = new Lazy<MetadataReference[]>( () => { var winmd = AssemblyMetadata.CreateFromImage(TestResources.WinRt.Windows).GetReference(display: "Windows"); var windowsruntime = AssemblyMetadata.CreateFromImage(ProprietaryTestResources.v4_0_30319_17929.System_Runtime_WindowsRuntime).GetReference(display: "System.Runtime.WindowsRuntime.dll"); var runtime = AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemRuntime).GetReference(display: "System.Runtime.dll"); var objectModel = AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemObjectModel).GetReference(display: "System.ObjectModel.dll"); var uixaml = AssemblyMetadata.CreateFromImage(ProprietaryTestResources.v4_0_30319_17929.System_Runtime_WindowsRuntime_UI_Xaml). GetReference(display: "System.Runtime.WindowsRuntime.UI.Xaml.dll"); var interop = AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemRuntimeInteropServicesWindowsRuntime). GetReference(display: "System.Runtime.InteropServices.WindowsRuntime.dll"); //Not mentioned in the adapter doc but pointed to from System.Runtime, so we'll put it here. var system = AssemblyMetadata.CreateFromImage(ResourcesNet451.System).GetReference(display: "System.dll"); var mscor = AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display: "mscorlib"); return new MetadataReference[] { winmd, windowsruntime, runtime, objectModel, uixaml, interop, system, mscor }; }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference[] WinRtRefs => s_winRtRefs.Value; /// <summary> /// The array of minimal references for portable library (mscorlib.dll and System.Runtime.dll) /// </summary> private static readonly Lazy<MetadataReference[]> s_portableRefsMinimal = new Lazy<MetadataReference[]>( () => new MetadataReference[] { MscorlibPP7Ref, SystemRuntimePP7Ref }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference[] PortableRefsMinimal => s_portableRefsMinimal.Value; /// <summary> /// Reference to an assembly that defines LINQ operators. /// </summary> public static MetadataReference LinqAssemblyRef => SystemCoreRef; /// <summary> /// Reference to an assembly that defines ExtensionAttribute. /// </summary> public static MetadataReference ExtensionAssemblyRef => SystemCoreRef; private static readonly Lazy<MetadataReference> s_systemCoreRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference(display: "System.Core.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemCoreRef => s_systemCoreRef.Value; private static readonly Lazy<MetadataReference> s_systemCoreRef_v4_0_30319_17929 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference(display: "System.Core.v4_0_30319_17929.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemCoreRef_v4_0_30319_17929 => s_systemCoreRef_v4_0_30319_17929.Value; private static readonly Lazy<MetadataReference> s_systemCoreRef_v46 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet461.SystemCore).GetReference(display: "System.Core.v4_6_1038_0.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemCoreRef_v46 => s_systemCoreRef_v4_0_30319_17929.Value; private static readonly Lazy<MetadataReference> s_systemWindowsFormsRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemWindowsForms).GetReference(display: "System.Windows.Forms.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemWindowsFormsRef => s_systemWindowsFormsRef.Value; private static readonly Lazy<MetadataReference> s_systemDrawingRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemDrawing).GetReference(display: "System.Drawing.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemDrawingRef => s_systemDrawingRef.Value; private static readonly Lazy<MetadataReference> s_systemDataRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemData).GetReference(display: "System.Data.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemDataRef => s_systemDataRef.Value; private static readonly Lazy<MetadataReference> s_mscorlibRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display: "mscorlib.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibRef => s_mscorlibRef.Value; private static readonly Lazy<MetadataReference> s_mscorlibRefPortable = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.v4_0_30319.mscorlib_portable).GetReference(display: "mscorlib.v4_0_30319.portable.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibRefPortable => s_mscorlibRefPortable.Value; private static readonly Lazy<MetadataReference> s_aacorlibRef = new Lazy<MetadataReference>( () => { var source = TestResources.NetFX.aacorlib_v15_0_3928.aacorlib_v15_0_3928_cs; var syntaxTree = Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(source); var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); var compilation = CSharpCompilation.Create("aacorlib.v15.0.3928.dll", new[] { syntaxTree }, null, compilationOptions); Stream dllStream = new MemoryStream(); var emitResult = compilation.Emit(dllStream); if (!emitResult.Success) { emitResult.Diagnostics.Verify(); } dllStream.Seek(0, SeekOrigin.Begin); return AssemblyMetadata.CreateFromStream(dllStream).GetReference(display: "mscorlib.v4_0_30319.dll"); }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference AacorlibRef => s_aacorlibRef.Value; public static MetadataReference MscorlibRef_v20 => Net20.mscorlib; public static MetadataReference MscorlibRef_v4_0_30316_17626 => Net451.mscorlib; private static readonly Lazy<MetadataReference> s_mscorlibRef_v46 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet461.mscorlib).GetReference(display: "mscorlib.v4_6_1038_0.dll", filePath: @"Z:\FxReferenceAssembliesUri"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibRef_v46 => s_mscorlibRef_v46.Value; /// <summary> /// Reference to an mscorlib silverlight assembly in which the System.Array does not contain the special member LongLength. /// </summary> private static readonly Lazy<MetadataReference> s_mscorlibRef_silverlight = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.silverlight_v5_0_5_0.mscorlib_v5_0_5_0_silverlight).GetReference(display: "mscorlib.v5.0.5.0_silverlight.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibRefSilverlight => s_mscorlibRef_silverlight.Value; public static MetadataReference MinCorlibRef => TestReferences.NetFx.Minimal.mincorlib; public static MetadataReference MinAsyncCorlibRef => TestReferences.NetFx.Minimal.minasynccorlib; public static MetadataReference ValueTupleRef => TestReferences.NetFx.ValueTuple.tuplelib; public static MetadataReference MsvbRef => Net451.MicrosoftVisualBasic; public static MetadataReference MsvbRef_v4_0_30319_17929 => Net451.MicrosoftVisualBasic; public static MetadataReference CSharpRef => CSharpDesktopRef; private static readonly Lazy<MetadataReference> s_desktopCSharpRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.MicrosoftCSharp).GetReference(display: "Microsoft.CSharp.v4.0.30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference CSharpDesktopRef => s_desktopCSharpRef.Value; private static readonly Lazy<MetadataReference> s_std20Ref = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNetStandard20.netstandard).GetReference(display: "netstandard20.netstandard.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference NetStandard20Ref => s_std20Ref.Value; private static readonly Lazy<MetadataReference> s_46NetStandardFacade = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesBuildExtensions.NetStandardToNet461).GetReference(display: "netstandard20.netstandard.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference Net46StandardFacade => s_46NetStandardFacade.Value; private static readonly Lazy<MetadataReference> s_systemDynamicRuntimeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.netstandard13.System_Dynamic_Runtime).GetReference(display: "System.Dynamic.Runtime.dll (netstandard 1.3 ref)"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemDynamicRuntimeRef => s_systemDynamicRuntimeRef.Value; private static readonly Lazy<MetadataReference> s_systemRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.System).GetReference(display: "System.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRef => s_systemRef.Value; private static readonly Lazy<MetadataReference> s_systemRef_v46 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet461.System).GetReference(display: "System.v4_6_1038_0.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRef_v46 => s_systemRef_v46.Value; private static readonly Lazy<MetadataReference> s_systemRef_v4_0_30319_17929 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.System).GetReference(display: "System.v4_0_30319_17929.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRef_v4_0_30319_17929 => s_systemRef_v4_0_30319_17929.Value; private static readonly Lazy<MetadataReference> s_systemRef_v20 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet20.System).GetReference(display: "System.v2_0_50727.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRef_v20 => s_systemRef_v20.Value; private static readonly Lazy<MetadataReference> s_systemXmlRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemXml).GetReference(display: "System.Xml.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemXmlRef => s_systemXmlRef.Value; private static readonly Lazy<MetadataReference> s_systemXmlLinqRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemXmlLinq).GetReference(display: "System.Xml.Linq.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemXmlLinqRef => s_systemXmlLinqRef.Value; private static readonly Lazy<MetadataReference> s_mscorlibFacadeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display: "mscorlib.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibFacadeRef => s_mscorlibFacadeRef.Value; private static readonly Lazy<MetadataReference> s_systemRuntimeFacadeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemRuntime).GetReference(display: "System.Runtime.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRuntimeFacadeRef => s_systemRuntimeFacadeRef.Value; private static readonly Lazy<MetadataReference> s_systemThreadingFacadeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemThreading).GetReference(display: "System.Threading.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemThreadingFacadeRef => s_systemThreadingTasksFacadeRef.Value; private static readonly Lazy<MetadataReference> s_systemThreadingTasksFacadeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemThreadingTasks).GetReference(display: "System.Threading.Tasks.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemThreadingTaskFacadeRef => s_systemThreadingTasksFacadeRef.Value; private static readonly Lazy<MetadataReference> s_mscorlibPP7Ref = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.ReferenceAssemblies_PortableProfile7.mscorlib).GetReference(display: "mscorlib.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibPP7Ref => s_mscorlibPP7Ref.Value; private static readonly Lazy<MetadataReference> s_systemRuntimePP7Ref = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.ReferenceAssemblies_PortableProfile7.System_Runtime).GetReference(display: "System.Runtime.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRuntimePP7Ref => s_systemRuntimePP7Ref.Value; private static readonly Lazy<MetadataReference> s_FSharpTestLibraryRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.FSharpTestLibrary).GetReference(display: "FSharpTestLibrary.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference FSharpTestLibraryRef => s_FSharpTestLibraryRef.Value; public static readonly MetadataReference InvalidRef = new TestMetadataReference(fullPath: @"R:\Invalid.dll"); #endregion #region Diagnostics internal static DiagnosticDescription Diagnostic( object code, string squiggledText = null, object[] arguments = null, LinePosition? startLocation = null, Func<SyntaxNode, bool> syntaxNodePredicate = null, bool argumentOrderDoesNotMatter = false, bool isSuppressed = false) { return TestHelpers.Diagnostic( code, squiggledText, arguments, startLocation, syntaxNodePredicate, argumentOrderDoesNotMatter, isSuppressed: isSuppressed); } internal static DiagnosticDescription Diagnostic( object code, XCData squiggledText, object[] arguments = null, LinePosition? startLocation = null, Func<SyntaxNode, bool> syntaxNodePredicate = null, bool argumentOrderDoesNotMatter = false, bool isSuppressed = false) { return TestHelpers.Diagnostic( code, squiggledText, arguments, startLocation, syntaxNodePredicate, argumentOrderDoesNotMatter, isSuppressed: isSuppressed); } #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.Diagnostics; using System.IO; using System.Reflection; using System.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using static TestReferences.NetFx; using static Roslyn.Test.Utilities.TestMetadata; using Microsoft.CodeAnalysis.Test.Resources.Proprietary; namespace Roslyn.Test.Utilities { /// <summary> /// Base class for all unit test classes. /// </summary> public abstract class TestBase : IDisposable { private TempRoot _temp; protected TestBase() { } public static string GetUniqueName() { return Guid.NewGuid().ToString("D"); } public TempRoot Temp { get { if (_temp == null) { _temp = new TempRoot(); } return _temp; } } public virtual void Dispose() { if (_temp != null) { _temp.Dispose(); } } #region Metadata References /// <summary> /// Helper for atomically acquiring and saving a metadata reference. Necessary /// if the acquired reference will ever be used in object identity comparisons. /// </summary> private static MetadataReference GetOrCreateMetadataReference(ref MetadataReference field, Func<MetadataReference> getReference) { if (field == null) { Interlocked.CompareExchange(ref field, getReference(), null); } return field; } private static readonly Lazy<MetadataReference[]> s_lazyDefaultVbReferences = new Lazy<MetadataReference[]>( () => new[] { Net40.mscorlib, Net40.System, Net40.SystemCore, Net40.MicrosoftVisualBasic }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference[] DefaultVbReferences => s_lazyDefaultVbReferences.Value; private static readonly Lazy<MetadataReference[]> s_lazyLatestVbReferences = new Lazy<MetadataReference[]>( () => new[] { Net451.mscorlib, Net451.System, Net451.SystemCore, Net451.MicrosoftVisualBasic }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference[] LatestVbReferences => s_lazyLatestVbReferences.Value; public static readonly AssemblyName RuntimeCorLibName = RuntimeUtilities.IsCoreClrRuntime ? new AssemblyName("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51") : new AssemblyName("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); /// <summary> /// The array of 7 metadataimagereferences that are required to compile /// against windows.winmd (including windows.winmd itself). /// </summary> private static readonly Lazy<MetadataReference[]> s_winRtRefs = new Lazy<MetadataReference[]>( () => { var winmd = AssemblyMetadata.CreateFromImage(TestResources.WinRt.Windows).GetReference(display: "Windows"); var windowsruntime = AssemblyMetadata.CreateFromImage(ProprietaryTestResources.v4_0_30319_17929.System_Runtime_WindowsRuntime).GetReference(display: "System.Runtime.WindowsRuntime.dll"); var runtime = AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemRuntime).GetReference(display: "System.Runtime.dll"); var objectModel = AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemObjectModel).GetReference(display: "System.ObjectModel.dll"); var uixaml = AssemblyMetadata.CreateFromImage(ProprietaryTestResources.v4_0_30319_17929.System_Runtime_WindowsRuntime_UI_Xaml). GetReference(display: "System.Runtime.WindowsRuntime.UI.Xaml.dll"); var interop = AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemRuntimeInteropServicesWindowsRuntime). GetReference(display: "System.Runtime.InteropServices.WindowsRuntime.dll"); //Not mentioned in the adapter doc but pointed to from System.Runtime, so we'll put it here. var system = AssemblyMetadata.CreateFromImage(ResourcesNet451.System).GetReference(display: "System.dll"); var mscor = AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display: "mscorlib"); return new MetadataReference[] { winmd, windowsruntime, runtime, objectModel, uixaml, interop, system, mscor }; }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference[] WinRtRefs => s_winRtRefs.Value; /// <summary> /// The array of minimal references for portable library (mscorlib.dll and System.Runtime.dll) /// </summary> private static readonly Lazy<MetadataReference[]> s_portableRefsMinimal = new Lazy<MetadataReference[]>( () => new MetadataReference[] { MscorlibPP7Ref, SystemRuntimePP7Ref }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference[] PortableRefsMinimal => s_portableRefsMinimal.Value; /// <summary> /// Reference to an assembly that defines LINQ operators. /// </summary> public static MetadataReference LinqAssemblyRef => SystemCoreRef; /// <summary> /// Reference to an assembly that defines ExtensionAttribute. /// </summary> public static MetadataReference ExtensionAssemblyRef => SystemCoreRef; private static readonly Lazy<MetadataReference> s_systemCoreRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference(display: "System.Core.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemCoreRef => s_systemCoreRef.Value; private static readonly Lazy<MetadataReference> s_systemCoreRef_v4_0_30319_17929 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference(display: "System.Core.v4_0_30319_17929.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemCoreRef_v4_0_30319_17929 => s_systemCoreRef_v4_0_30319_17929.Value; private static readonly Lazy<MetadataReference> s_systemCoreRef_v46 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet461.SystemCore).GetReference(display: "System.Core.v4_6_1038_0.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemCoreRef_v46 => s_systemCoreRef_v4_0_30319_17929.Value; private static readonly Lazy<MetadataReference> s_systemWindowsFormsRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemWindowsForms).GetReference(display: "System.Windows.Forms.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemWindowsFormsRef => s_systemWindowsFormsRef.Value; private static readonly Lazy<MetadataReference> s_systemDrawingRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemDrawing).GetReference(display: "System.Drawing.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemDrawingRef => s_systemDrawingRef.Value; private static readonly Lazy<MetadataReference> s_systemDataRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemData).GetReference(display: "System.Data.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemDataRef => s_systemDataRef.Value; private static readonly Lazy<MetadataReference> s_mscorlibRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display: "mscorlib.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibRef => s_mscorlibRef.Value; private static readonly Lazy<MetadataReference> s_mscorlibRefPortable = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.v4_0_30319.mscorlib_portable).GetReference(display: "mscorlib.v4_0_30319.portable.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibRefPortable => s_mscorlibRefPortable.Value; private static readonly Lazy<MetadataReference> s_aacorlibRef = new Lazy<MetadataReference>( () => { var source = TestResources.NetFX.aacorlib_v15_0_3928.aacorlib_v15_0_3928_cs; var syntaxTree = Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(source); var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); var compilation = CSharpCompilation.Create("aacorlib.v15.0.3928.dll", new[] { syntaxTree }, null, compilationOptions); Stream dllStream = new MemoryStream(); var emitResult = compilation.Emit(dllStream); if (!emitResult.Success) { emitResult.Diagnostics.Verify(); } dllStream.Seek(0, SeekOrigin.Begin); return AssemblyMetadata.CreateFromStream(dllStream).GetReference(display: "mscorlib.v4_0_30319.dll"); }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference AacorlibRef => s_aacorlibRef.Value; public static MetadataReference MscorlibRef_v20 => Net20.mscorlib; public static MetadataReference MscorlibRef_v4_0_30316_17626 => Net451.mscorlib; private static readonly Lazy<MetadataReference> s_mscorlibRef_v46 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet461.mscorlib).GetReference(display: "mscorlib.v4_6_1038_0.dll", filePath: @"Z:\FxReferenceAssembliesUri"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibRef_v46 => s_mscorlibRef_v46.Value; /// <summary> /// Reference to an mscorlib silverlight assembly in which the System.Array does not contain the special member LongLength. /// </summary> private static readonly Lazy<MetadataReference> s_mscorlibRef_silverlight = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.silverlight_v5_0_5_0.mscorlib_v5_0_5_0_silverlight).GetReference(display: "mscorlib.v5.0.5.0_silverlight.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibRefSilverlight => s_mscorlibRef_silverlight.Value; public static MetadataReference MinCorlibRef => TestReferences.NetFx.Minimal.mincorlib; public static MetadataReference MinAsyncCorlibRef => TestReferences.NetFx.Minimal.minasynccorlib; public static MetadataReference ValueTupleRef => TestReferences.NetFx.ValueTuple.tuplelib; public static MetadataReference MsvbRef => Net451.MicrosoftVisualBasic; public static MetadataReference MsvbRef_v4_0_30319_17929 => Net451.MicrosoftVisualBasic; public static MetadataReference CSharpRef => CSharpDesktopRef; private static readonly Lazy<MetadataReference> s_desktopCSharpRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.MicrosoftCSharp).GetReference(display: "Microsoft.CSharp.v4.0.30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference CSharpDesktopRef => s_desktopCSharpRef.Value; private static readonly Lazy<MetadataReference> s_std20Ref = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNetStandard20.netstandard).GetReference(display: "netstandard20.netstandard.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference NetStandard20Ref => s_std20Ref.Value; private static readonly Lazy<MetadataReference> s_46NetStandardFacade = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesBuildExtensions.NetStandardToNet461).GetReference(display: "netstandard20.netstandard.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference Net46StandardFacade => s_46NetStandardFacade.Value; private static readonly Lazy<MetadataReference> s_systemDynamicRuntimeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.netstandard13.System_Dynamic_Runtime).GetReference(display: "System.Dynamic.Runtime.dll (netstandard 1.3 ref)"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemDynamicRuntimeRef => s_systemDynamicRuntimeRef.Value; private static readonly Lazy<MetadataReference> s_systemRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.System).GetReference(display: "System.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRef => s_systemRef.Value; private static readonly Lazy<MetadataReference> s_systemRef_v46 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet461.System).GetReference(display: "System.v4_6_1038_0.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRef_v46 => s_systemRef_v46.Value; private static readonly Lazy<MetadataReference> s_systemRef_v4_0_30319_17929 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.System).GetReference(display: "System.v4_0_30319_17929.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRef_v4_0_30319_17929 => s_systemRef_v4_0_30319_17929.Value; private static readonly Lazy<MetadataReference> s_systemRef_v20 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet20.System).GetReference(display: "System.v2_0_50727.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRef_v20 => s_systemRef_v20.Value; private static readonly Lazy<MetadataReference> s_systemXmlRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemXml).GetReference(display: "System.Xml.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemXmlRef => s_systemXmlRef.Value; private static readonly Lazy<MetadataReference> s_systemXmlLinqRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemXmlLinq).GetReference(display: "System.Xml.Linq.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemXmlLinqRef => s_systemXmlLinqRef.Value; private static readonly Lazy<MetadataReference> s_mscorlibFacadeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display: "mscorlib.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibFacadeRef => s_mscorlibFacadeRef.Value; private static readonly Lazy<MetadataReference> s_systemRuntimeFacadeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemRuntime).GetReference(display: "System.Runtime.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRuntimeFacadeRef => s_systemRuntimeFacadeRef.Value; private static readonly Lazy<MetadataReference> s_systemThreadingFacadeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemThreading).GetReference(display: "System.Threading.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemThreadingFacadeRef => s_systemThreadingTasksFacadeRef.Value; private static readonly Lazy<MetadataReference> s_systemThreadingTasksFacadeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemThreadingTasks).GetReference(display: "System.Threading.Tasks.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemThreadingTaskFacadeRef => s_systemThreadingTasksFacadeRef.Value; private static readonly Lazy<MetadataReference> s_mscorlibPP7Ref = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.ReferenceAssemblies_PortableProfile7.mscorlib).GetReference(display: "mscorlib.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibPP7Ref => s_mscorlibPP7Ref.Value; private static readonly Lazy<MetadataReference> s_systemRuntimePP7Ref = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.ReferenceAssemblies_PortableProfile7.System_Runtime).GetReference(display: "System.Runtime.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRuntimePP7Ref => s_systemRuntimePP7Ref.Value; private static readonly Lazy<MetadataReference> s_FSharpTestLibraryRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.FSharpTestLibrary).GetReference(display: "FSharpTestLibrary.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference FSharpTestLibraryRef => s_FSharpTestLibraryRef.Value; public static readonly MetadataReference InvalidRef = new TestMetadataReference(fullPath: @"R:\Invalid.dll"); #endregion #region Diagnostics internal static DiagnosticDescription Diagnostic( object code, string squiggledText = null, object[] arguments = null, LinePosition? startLocation = null, Func<SyntaxNode, bool> syntaxNodePredicate = null, bool argumentOrderDoesNotMatter = false, bool isSuppressed = false) { return TestHelpers.Diagnostic( code, squiggledText, arguments, startLocation, syntaxNodePredicate, argumentOrderDoesNotMatter, isSuppressed: isSuppressed); } internal static DiagnosticDescription Diagnostic( object code, XCData squiggledText, object[] arguments = null, LinePosition? startLocation = null, Func<SyntaxNode, bool> syntaxNodePredicate = null, bool argumentOrderDoesNotMatter = false, bool isSuppressed = false) { return TestHelpers.Diagnostic( code, squiggledText, arguments, startLocation, syntaxNodePredicate, argumentOrderDoesNotMatter, isSuppressed: isSuppressed); } #endregion } }
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Compilers/VisualBasic/Portable/BoundTree/BoundQueryableSource.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 BoundQueryableSource #If DEBUG Then Private Sub Validate() Debug.Assert(RangeVariables.Length = 1) End Sub #End If Public Overrides ReadOnly Property ExpressionSymbol As Symbol Get Return Source.ExpressionSymbol End Get End Property Public Overrides ReadOnly Property ResultKind As LookupResultKind Get Return Source.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 BoundQueryableSource #If DEBUG Then Private Sub Validate() Debug.Assert(RangeVariables.Length = 1) End Sub #End If Public Overrides ReadOnly Property ExpressionSymbol As Symbol Get Return Source.ExpressionSymbol End Get End Property Public Overrides ReadOnly Property ResultKind As LookupResultKind Get Return Source.ResultKind End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,876
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime
Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
davidwengier
2021-08-25T03:54:26Z
2021-08-25T23:32:55Z
cb18669598e9b49e5cba0ef6439e1c9ac3df97ac
18556e82c3c4e4a861987b4cb5379764d6c17422
EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676 Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/AggregatedFormattingResult.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.Threading; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal class AggregatedFormattingResult : AbstractAggregatedFormattingResult { public AggregatedFormattingResult(SyntaxNode node, IList<AbstractFormattingResult> results, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? formattingSpans) : base(node, results, formattingSpans) { } protected override SyntaxNode Rewriter(Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData> map, CancellationToken cancellationToken) { var rewriter = new TriviaRewriter(this.Node, GetFormattingSpans(), map, cancellationToken); return rewriter.Transform(); } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal class AggregatedFormattingResult : AbstractAggregatedFormattingResult { public AggregatedFormattingResult(SyntaxNode node, IList<AbstractFormattingResult> results, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? formattingSpans) : base(node, results, formattingSpans) { } protected override SyntaxNode Rewriter(Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData> map, CancellationToken cancellationToken) { var rewriter = new TriviaRewriter(this.Node, GetFormattingSpans(), map, cancellationToken); return rewriter.Transform(); } } }
-1