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 > General options page.</source>
<target state="translated">Параметры цветовой схемы редактора доступны только при использовании цветовой темы, поставляемой вместе с Visual Studio. Цветовую тему можно настроить на странице "Среда" > "Общие параметры".</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 > Fonts and Colors options page. Choose `Use Defaults` in the Fonts and Colors page to revert all customizations.</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="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 >= 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><Unknown></source>
<target state="translated"><нет данных></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><Unknown></source>
<target state="translated"><нет данных></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><Unknown Parameters></source>
<target state="translated"><Неизвестные параметры></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 > General options page.</source>
<target state="translated">Параметры цветовой схемы редактора доступны только при использовании цветовой темы, поставляемой вместе с Visual Studio. Цветовую тему можно настроить на странице "Среда" > "Общие параметры".</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 > Fonts and Colors options page. Choose `Use Defaults` in the Fonts and Colors page to revert all customizations.</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="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 >= 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><Unknown></source>
<target state="translated"><нет данных></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><Unknown></source>
<target state="translated"><нет данных></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><Unknown Parameters></source>
<target state="translated"><Неизвестные параметры></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: < > <= >= is as == !=</source>
<target state="translated">Dans les opérateurs relationnels : < > <= >= 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: * / % + - << >> & ^ |</source>
<target state="translated">Dans les opérateurs arithmétiques : * / % + - << >> & ^ |</target>
<note />
</trans-unit>
<trans-unit id="In_other_binary_operators">
<source>In other binary operators: && || ?? and or</source>
<target state="translated">Dans d'autres opérateurs binaires : && || ?? 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: < > <= >= is as == !=</source>
<target state="translated">Dans les opérateurs relationnels : < > <= >= 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: * / % + - << >> & ^ |</source>
<target state="translated">Dans les opérateurs arithmétiques : * / % + - << >> & ^ |</target>
<note />
</trans-unit>
<trans-unit id="In_other_binary_operators">
<source>In other binary operators: && || ?? and or</source>
<target state="translated">Dans d'autres opérateurs binaires : && || ?? 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.
$ PE L [L ! ~# @ @ @ ,# O @ ` H .text `.rsrc @ @ @.reloc `
@ B `# H t
*(
*(
*(
*(
* BSJB v4.0.30319 l @ #~ #Strings d #US l #GUID | < |