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
unknown
date_merged
unknown
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,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Analyzers/CSharp/Analyzers/UseTupleSwap/CSharpUseTupleSwapDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more 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.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.UseTupleSwap { /// <summary> /// Looks for code of the form: /// /// <code> /// var temp = expr_a; /// expr_a = expr_b; /// expr_b = temp; /// </code> /// /// and converts it to: /// /// <code> /// (expr_b, expr_a) = (expr_a, expr_b); /// </code> /// /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpUseTupleSwapDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public CSharpUseTupleSwapDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseTupleSwapDiagnosticId, EnforceOnBuildValues.UseTupleSwap, CSharpCodeStyleOptions.PreferTupleSwap, LanguageNames.CSharp, new LocalizableResourceString( nameof(CSharpAnalyzersResources.Use_tuple_to_swap_values), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(context => { // Tuples are only available in C# 7 and above. var compilation = context.Compilation; if (compilation.LanguageVersion() < LanguageVersion.CSharp7) return; context.RegisterSyntaxNodeAction( AnalyzeLocalDeclarationStatement, SyntaxKind.LocalDeclarationStatement); }); } private void AnalyzeLocalDeclarationStatement(SyntaxNodeAnalysisContext syntaxContext) { var styleOption = syntaxContext.GetCSharpAnalyzerOptions().PreferTupleSwap; if (!styleOption.Value) return; var severity = styleOption.Notification.Severity; // `var expr_temp = expr_a`; var localDeclarationStatement = (LocalDeclarationStatementSyntax)syntaxContext.Node; if (localDeclarationStatement.UsingKeyword != default || localDeclarationStatement.AwaitKeyword != default) { return; } if (localDeclarationStatement.Declaration.Variables.Count != 1) return; var variableDeclarator = localDeclarationStatement.Declaration.Variables.First(); var localDeclarationExprA = variableDeclarator.Initializer?.Value.WalkDownParentheses(); if (localDeclarationExprA == null) return; // `expr_a = expr_b`; var firstAssignmentStatement = localDeclarationStatement.GetNextStatement(); if (!IsSimpleAssignment(firstAssignmentStatement, out var firstAssignmentExprA, out var firstAssignmentExprB)) return; // `expr_b = expr_temp;` var secondAssignmentStatement = firstAssignmentStatement.GetNextStatement(); if (!IsSimpleAssignment(secondAssignmentStatement, out var secondAssignmentExprB, out var secondAssignmentExprTemp)) return; if (!localDeclarationExprA.IsEquivalentTo(firstAssignmentExprA, topLevel: false)) return; if (!firstAssignmentExprB.IsEquivalentTo(secondAssignmentExprB, topLevel: false)) return; if (secondAssignmentExprTemp is not IdentifierNameSyntax { Identifier: var secondAssignmentExprTempIdentifier }) return; if (variableDeclarator.Identifier.ValueText != secondAssignmentExprTempIdentifier.ValueText) return; var additionalLocations = ImmutableArray.Create( localDeclarationStatement.GetLocation(), firstAssignmentStatement.GetLocation(), secondAssignmentStatement.GetLocation()); // If the diagnostic is not hidden, then just place the user visible part // on the local being initialized with the lambda. syntaxContext.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, localDeclarationStatement.GetFirstToken().GetLocation(), severity, additionalLocations, properties: null)); } private static bool IsSimpleAssignment( [NotNullWhen(true)] StatementSyntax? assignmentStatement, [NotNullWhen(true)] out ExpressionSyntax? left, [NotNullWhen(true)] out ExpressionSyntax? right) { left = null; right = null; if (assignmentStatement == null) return false; if (assignmentStatement is not ExpressionStatementSyntax { Expression: AssignmentExpressionSyntax(SyntaxKind.SimpleAssignmentExpression) assignment }) return false; left = assignment.Left.WalkDownParentheses(); right = assignment.Right.WalkDownParentheses(); return left is not RefExpressionSyntax && right is not RefExpressionSyntax; } } }
// Licensed to the .NET Foundation under one or more 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.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.UseTupleSwap { /// <summary> /// Looks for code of the form: /// /// <code> /// var temp = expr_a; /// expr_a = expr_b; /// expr_b = temp; /// </code> /// /// and converts it to: /// /// <code> /// (expr_b, expr_a) = (expr_a, expr_b); /// </code> /// /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpUseTupleSwapDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public CSharpUseTupleSwapDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseTupleSwapDiagnosticId, EnforceOnBuildValues.UseTupleSwap, CSharpCodeStyleOptions.PreferTupleSwap, LanguageNames.CSharp, new LocalizableResourceString( nameof(CSharpAnalyzersResources.Use_tuple_to_swap_values), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(context => { // Tuples are only available in C# 7 and above. var compilation = context.Compilation; if (compilation.LanguageVersion() < LanguageVersion.CSharp7) return; context.RegisterSyntaxNodeAction( AnalyzeLocalDeclarationStatement, SyntaxKind.LocalDeclarationStatement); }); } private void AnalyzeLocalDeclarationStatement(SyntaxNodeAnalysisContext syntaxContext) { var styleOption = syntaxContext.GetCSharpAnalyzerOptions().PreferTupleSwap; if (!styleOption.Value) return; var severity = styleOption.Notification.Severity; // `var expr_temp = expr_a`; var localDeclarationStatement = (LocalDeclarationStatementSyntax)syntaxContext.Node; if (localDeclarationStatement.UsingKeyword != default || localDeclarationStatement.AwaitKeyword != default) { return; } if (localDeclarationStatement.Declaration.Variables.Count != 1) return; var variableDeclarator = localDeclarationStatement.Declaration.Variables.First(); var localDeclarationExprA = variableDeclarator.Initializer?.Value.WalkDownParentheses(); if (localDeclarationExprA == null) return; // `expr_a = expr_b`; var firstAssignmentStatement = localDeclarationStatement.GetNextStatement(); if (!IsSimpleAssignment(firstAssignmentStatement, out var firstAssignmentExprA, out var firstAssignmentExprB)) return; // `expr_b = expr_temp;` var secondAssignmentStatement = firstAssignmentStatement.GetNextStatement(); if (!IsSimpleAssignment(secondAssignmentStatement, out var secondAssignmentExprB, out var secondAssignmentExprTemp)) return; if (!localDeclarationExprA.IsEquivalentTo(firstAssignmentExprA, topLevel: false)) return; if (!firstAssignmentExprB.IsEquivalentTo(secondAssignmentExprB, topLevel: false)) return; if (secondAssignmentExprTemp is not IdentifierNameSyntax { Identifier: var secondAssignmentExprTempIdentifier }) return; if (variableDeclarator.Identifier.ValueText != secondAssignmentExprTempIdentifier.ValueText) return; var additionalLocations = ImmutableArray.Create( localDeclarationStatement.GetLocation(), firstAssignmentStatement.GetLocation(), secondAssignmentStatement.GetLocation()); // If the diagnostic is not hidden, then just place the user visible part // on the local being initialized with the lambda. syntaxContext.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, localDeclarationStatement.GetFirstToken().GetLocation(), severity, additionalLocations, properties: null)); } private static bool IsSimpleAssignment( [NotNullWhen(true)] StatementSyntax? assignmentStatement, [NotNullWhen(true)] out ExpressionSyntax? left, [NotNullWhen(true)] out ExpressionSyntax? right) { left = null; right = null; if (assignmentStatement == null) return false; if (assignmentStatement is not ExpressionStatementSyntax { Expression: AssignmentExpressionSyntax(SyntaxKind.SimpleAssignmentExpression) assignment }) return false; left = assignment.Left.WalkDownParentheses(); right = assignment.Right.WalkDownParentheses(); return left is not RefExpressionSyntax && right is not RefExpressionSyntax; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/VSTypeScriptPredefinedCommandHandlerNames.cs
// Licensed to the .NET Foundation under one or more 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.Editor; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal static class VSTypeScriptPredefinedCommandHandlerNames { public const string SignatureHelpAfterCompletion = PredefinedCommandHandlerNames.SignatureHelpAfterCompletion; } }
// Licensed to the .NET Foundation under one or more 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.Editor; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal static class VSTypeScriptPredefinedCommandHandlerNames { public const string SignatureHelpAfterCompletion = PredefinedCommandHandlerNames.SignatureHelpAfterCompletion; } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/IOptionWithGroup.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Group/sub-feature associated with an <see cref="IOption2"/>. /// </summary> internal interface IOptionWithGroup : IOption2 { /// <summary> /// Group/sub-feature for this option. /// </summary> OptionGroup Group { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Group/sub-feature associated with an <see cref="IOption2"/>. /// </summary> internal interface IOptionWithGroup : IOption2 { /// <summary> /// Group/sub-feature for this option. /// </summary> OptionGroup Group { get; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/ProjectFile.cs
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.MSBuild.Build; using Microsoft.CodeAnalysis.MSBuild.Logging; using Roslyn.Utilities; using MSB = Microsoft.Build; namespace Microsoft.CodeAnalysis.MSBuild { internal abstract class ProjectFile : IProjectFile { private readonly ProjectFileLoader _loader; private readonly MSB.Evaluation.Project? _loadedProject; private readonly ProjectBuildManager _buildManager; private readonly string _projectDirectory; public DiagnosticLog Log { get; } public virtual string FilePath => _loadedProject?.FullPath ?? string.Empty; public string Language => _loader.Language; protected ProjectFile(ProjectFileLoader loader, MSB.Evaluation.Project? loadedProject, ProjectBuildManager buildManager, DiagnosticLog log) { _loader = loader; _loadedProject = loadedProject; _buildManager = buildManager; var directory = loadedProject?.DirectoryPath ?? string.Empty; _projectDirectory = PathUtilities.EnsureTrailingSeparator(directory); Log = log; } protected abstract SourceCodeKind GetSourceCodeKind(string documentFileName); public abstract string GetDocumentExtension(SourceCodeKind kind); protected abstract IEnumerable<MSB.Framework.ITaskItem> GetCompilerCommandLineArgs(MSB.Execution.ProjectInstance executedProject); protected abstract ImmutableArray<string> ReadCommandLineArgs(MSB.Execution.ProjectInstance project); public async Task<ImmutableArray<ProjectFileInfo>> GetProjectFileInfosAsync(CancellationToken cancellationToken) { if (_loadedProject is null) { return ImmutableArray.Create(ProjectFileInfo.CreateEmpty(Language, _loadedProject?.FullPath, Log)); } var targetFrameworkValue = _loadedProject.GetPropertyValue(PropertyNames.TargetFramework); var targetFrameworksValue = _loadedProject.GetPropertyValue(PropertyNames.TargetFrameworks); if (RoslynString.IsNullOrEmpty(targetFrameworkValue) && !RoslynString.IsNullOrEmpty(targetFrameworksValue)) { // This project has a <TargetFrameworks> property, but does not specify a <TargetFramework>. // In this case, we need to iterate through the <TargetFrameworks>, set <TargetFramework> with // each value, and build the project. var targetFrameworks = targetFrameworksValue.Split(';'); var results = ImmutableArray.CreateBuilder<ProjectFileInfo>(targetFrameworks.Length); if (!_loadedProject.GlobalProperties.TryGetValue(PropertyNames.TargetFramework, out var initialGlobalTargetFrameworkValue)) initialGlobalTargetFrameworkValue = null; foreach (var targetFramework in targetFrameworks) { _loadedProject.SetGlobalProperty(PropertyNames.TargetFramework, targetFramework); _loadedProject.ReevaluateIfNecessary(); var projectFileInfo = await BuildProjectFileInfoAsync(cancellationToken).ConfigureAwait(false); results.Add(projectFileInfo); } if (initialGlobalTargetFrameworkValue is null) { _loadedProject.RemoveGlobalProperty(PropertyNames.TargetFramework); } else { _loadedProject.SetGlobalProperty(PropertyNames.TargetFramework, initialGlobalTargetFrameworkValue); } _loadedProject.ReevaluateIfNecessary(); return results.ToImmutable(); } else { var projectFileInfo = await BuildProjectFileInfoAsync(cancellationToken).ConfigureAwait(false); projectFileInfo ??= ProjectFileInfo.CreateEmpty(Language, _loadedProject?.FullPath, Log); return ImmutableArray.Create(projectFileInfo); } } private async Task<ProjectFileInfo> BuildProjectFileInfoAsync(CancellationToken cancellationToken) { if (_loadedProject is null) { return ProjectFileInfo.CreateEmpty(Language, _loadedProject?.FullPath, Log); } var project = await _buildManager.BuildProjectAsync(_loadedProject, Log, cancellationToken).ConfigureAwait(false); return project != null ? CreateProjectFileInfo(project) : ProjectFileInfo.CreateEmpty(Language, _loadedProject.FullPath, Log); } private ProjectFileInfo CreateProjectFileInfo(MSB.Execution.ProjectInstance project) { var commandLineArgs = GetCommandLineArgs(project); var outputFilePath = project.ReadPropertyString(PropertyNames.TargetPath); if (!RoslynString.IsNullOrWhiteSpace(outputFilePath)) { outputFilePath = GetAbsolutePathRelativeToProject(outputFilePath); } var outputRefFilePath = project.ReadPropertyString(PropertyNames.TargetRefPath); if (!RoslynString.IsNullOrWhiteSpace(outputRefFilePath)) { outputRefFilePath = GetAbsolutePathRelativeToProject(outputRefFilePath); } // Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace // by assigning the value of the project's root namespace to it. So various feature can choose to // use it for their own purpose. // In the future, we might consider officially exposing "default namespace" for VB project // (e.g. through a <defaultnamespace> msbuild property) var defaultNamespace = project.ReadPropertyString(PropertyNames.RootNamespace) ?? string.Empty; var targetFramework = project.ReadPropertyString(PropertyNames.TargetFramework); if (RoslynString.IsNullOrWhiteSpace(targetFramework)) { targetFramework = null; } var docs = project.GetDocuments() .Where(IsNotTemporaryGeneratedFile) .Select(MakeDocumentFileInfo) .ToImmutableArray(); var additionalDocs = project.GetAdditionalFiles() .Select(MakeNonSourceFileDocumentFileInfo) .ToImmutableArray(); var analyzerConfigDocs = project.GetEditorConfigFiles() .Select(MakeNonSourceFileDocumentFileInfo) .ToImmutableArray(); return ProjectFileInfo.Create( Language, project.FullPath, outputFilePath, outputRefFilePath, defaultNamespace, targetFramework, commandLineArgs, docs, additionalDocs, analyzerConfigDocs, project.GetProjectReferences().ToImmutableArray(), Log); } private ImmutableArray<string> GetCommandLineArgs(MSB.Execution.ProjectInstance project) { var commandLineArgs = GetCompilerCommandLineArgs(project) .Select(item => item.ItemSpec) .ToImmutableArray(); if (commandLineArgs.Length == 0) { // We didn't get any command-line args, which likely means that the build // was not successful. In that case, try to read the command-line args from // the ProjectInstance that we have. This is a best effort to provide something // meaningful for the user, though it will likely be incomplete. commandLineArgs = ReadCommandLineArgs(project); } return commandLineArgs; } protected static bool IsNotTemporaryGeneratedFile(MSB.Framework.ITaskItem item) => !Path.GetFileName(item.ItemSpec).StartsWith("TemporaryGeneratedFile_", StringComparison.Ordinal); private DocumentFileInfo MakeDocumentFileInfo(MSB.Framework.ITaskItem documentItem) { var filePath = GetDocumentFilePath(documentItem); var logicalPath = GetDocumentLogicalPath(documentItem, _projectDirectory); var isLinked = IsDocumentLinked(documentItem); var isGenerated = IsDocumentGenerated(documentItem); var sourceCodeKind = GetSourceCodeKind(filePath); return new DocumentFileInfo(filePath, logicalPath, isLinked, isGenerated, sourceCodeKind); } private DocumentFileInfo MakeNonSourceFileDocumentFileInfo(MSB.Framework.ITaskItem documentItem) { var filePath = GetDocumentFilePath(documentItem); var logicalPath = GetDocumentLogicalPath(documentItem, _projectDirectory); var isLinked = IsDocumentLinked(documentItem); var isGenerated = IsDocumentGenerated(documentItem); return new DocumentFileInfo(filePath, logicalPath, isLinked, isGenerated, SourceCodeKind.Regular); } /// <summary> /// Resolves the given path that is possibly relative to the project directory. /// </summary> /// <remarks> /// The resulting path is absolute but might not be normalized. /// </remarks> private string GetAbsolutePathRelativeToProject(string path) { // TODO (tomat): should we report an error when drive-relative path (e.g. "C:goo.cs") is encountered? var absolutePath = FileUtilities.ResolveRelativePath(path, _projectDirectory) ?? path; return FileUtilities.TryNormalizeAbsolutePath(absolutePath) ?? absolutePath; } private string GetDocumentFilePath(MSB.Framework.ITaskItem documentItem) => GetAbsolutePathRelativeToProject(documentItem.ItemSpec); private static bool IsDocumentLinked(MSB.Framework.ITaskItem documentItem) => !RoslynString.IsNullOrEmpty(documentItem.GetMetadata(MetadataNames.Link)); private IDictionary<string, MSB.Evaluation.ProjectItem>? _documents; protected bool IsDocumentGenerated(MSB.Framework.ITaskItem documentItem) { if (_documents == null) { _documents = new Dictionary<string, MSB.Evaluation.ProjectItem>(); if (_loadedProject is null) { return false; } foreach (var item in _loadedProject.GetItems(ItemNames.Compile)) { _documents[GetAbsolutePathRelativeToProject(item.EvaluatedInclude)] = item; } } return !_documents.ContainsKey(GetAbsolutePathRelativeToProject(documentItem.ItemSpec)); } protected static string GetDocumentLogicalPath(MSB.Framework.ITaskItem documentItem, string projectDirectory) { var link = documentItem.GetMetadata(MetadataNames.Link); if (!RoslynString.IsNullOrEmpty(link)) { // if a specific link is specified in the project file then use it to form the logical path. return link; } else { var filePath = documentItem.ItemSpec; if (!PathUtilities.IsAbsolute(filePath)) { return filePath; } var normalizedPath = FileUtilities.TryNormalizeAbsolutePath(filePath); if (normalizedPath == null) { return filePath; } // If the document is within the current project directory (or subdirectory), then the logical path is the relative path // from the project's directory. if (normalizedPath.StartsWith(projectDirectory, StringComparison.OrdinalIgnoreCase)) { return normalizedPath[projectDirectory.Length..]; } else { // if the document lies outside the project's directory (or subdirectory) then place it logically at the root of the project. // if more than one document ends up with the same logical name then so be it (the workspace will survive.) return PathUtilities.GetFileName(normalizedPath); } } } public void AddDocument(string filePath, string? logicalPath = null) { if (_loadedProject is null) { return; } var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath); Dictionary<string, string>? metadata = null; if (logicalPath != null && relativePath != logicalPath) { metadata = new Dictionary<string, string> { { MetadataNames.Link, logicalPath } }; relativePath = filePath; // link to full path } _loadedProject.AddItem(ItemNames.Compile, relativePath, metadata); } public void RemoveDocument(string filePath) { if (_loadedProject is null) { return; } var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath); var items = _loadedProject.GetItems(ItemNames.Compile); var item = items.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) || PathUtilities.PathsEqual(it.EvaluatedInclude, filePath)); if (item != null) { _loadedProject.RemoveItem(item); } } public void AddMetadataReference(MetadataReference reference, AssemblyIdentity identity) { if (_loadedProject is null) { return; } if (reference is PortableExecutableReference peRef && peRef.FilePath != null) { var metadata = new Dictionary<string, string>(); if (!peRef.Properties.Aliases.IsEmpty) { metadata.Add(MetadataNames.Aliases, string.Join(",", peRef.Properties.Aliases)); } if (IsInGAC(peRef.FilePath) && identity != null) { // Since the location of the reference is in GAC, need to use full identity name to find it again. // This typically happens when you base the reference off of a reflection assembly location. _loadedProject.AddItem(ItemNames.Reference, identity.GetDisplayName(), metadata); } else if (IsFrameworkReferenceAssembly(peRef.FilePath)) { // just use short name since this will be resolved by msbuild relative to the known framework reference assemblies. var fileName = identity != null ? identity.Name : Path.GetFileNameWithoutExtension(peRef.FilePath); _loadedProject.AddItem(ItemNames.Reference, fileName, metadata); } else // other location -- need hint to find correct assembly { var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, peRef.FilePath); var fileName = Path.GetFileNameWithoutExtension(peRef.FilePath); metadata.Add(MetadataNames.HintPath, relativePath); _loadedProject.AddItem(ItemNames.Reference, fileName, metadata); } } } private static bool IsInGAC(string filePath) { return GlobalAssemblyCacheLocation.RootLocations.Any(static (gloc, filePath) => PathUtilities.IsChildPath(gloc, filePath), filePath); } private static string? s_frameworkRoot; private static string FrameworkRoot { get { if (RoslynString.IsNullOrEmpty(s_frameworkRoot)) { var runtimeDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(); s_frameworkRoot = Path.GetDirectoryName(runtimeDir); // back out one directory level to be root path of all framework versions } return s_frameworkRoot ?? throw new InvalidOperationException($"Unable to get {nameof(FrameworkRoot)}"); } } private static bool IsFrameworkReferenceAssembly(string filePath) { return PathUtilities.IsChildPath(FrameworkRoot, filePath); } public void RemoveMetadataReference(MetadataReference reference, AssemblyIdentity identity) { if (_loadedProject is null) { return; } if (reference is PortableExecutableReference peRef && peRef.FilePath != null) { var item = FindReferenceItem(identity, peRef.FilePath); if (item != null) { _loadedProject.RemoveItem(item); } } } private MSB.Evaluation.ProjectItem FindReferenceItem(AssemblyIdentity identity, string filePath) { if (_loadedProject is null) { throw new InvalidOperationException($"Unable to find reference item '{identity?.Name}'"); } var references = _loadedProject.GetItems(ItemNames.Reference); MSB.Evaluation.ProjectItem? item = null; var fileName = Path.GetFileNameWithoutExtension(filePath); if (identity != null) { var shortAssemblyName = identity.Name; var fullAssemblyName = identity.GetDisplayName(); // check for short name match item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, shortAssemblyName, StringComparison.OrdinalIgnoreCase) == 0); // check for full name match item ??= references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, fullAssemblyName, StringComparison.OrdinalIgnoreCase) == 0); } // check for file path match if (item == null) { var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath); item = references.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, filePath) || PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) || PathUtilities.PathsEqual(GetHintPath(it), filePath) || PathUtilities.PathsEqual(GetHintPath(it), relativePath)); } // check for partial name match if (item == null && identity != null) { var partialName = identity.Name + ","; var items = references.Where(it => it.EvaluatedInclude.StartsWith(partialName, StringComparison.OrdinalIgnoreCase)).ToList(); if (items.Count == 1) { item = items[0]; } } return item ?? throw new InvalidOperationException($"Unable to find reference item '{identity?.Name}'"); } private static string GetHintPath(MSB.Evaluation.ProjectItem item) => item.Metadata.FirstOrDefault(m => string.Equals(m.Name, MetadataNames.HintPath, StringComparison.OrdinalIgnoreCase))?.EvaluatedValue ?? string.Empty; public void AddProjectReference(string projectName, ProjectFileReference reference) { if (_loadedProject is null) { return; } var metadata = new Dictionary<string, string> { { MetadataNames.Name, projectName } }; if (!reference.Aliases.IsEmpty) { metadata.Add(MetadataNames.Aliases, string.Join(",", reference.Aliases)); } var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, reference.Path); _loadedProject.AddItem(ItemNames.ProjectReference, relativePath, metadata); } public void RemoveProjectReference(string projectName, string projectFilePath) { if (_loadedProject is null) { return; } var item = FindProjectReferenceItem(projectName, projectFilePath); if (item != null) { _loadedProject.RemoveItem(item); } } private MSB.Evaluation.ProjectItem? FindProjectReferenceItem(string projectName, string projectFilePath) { if (_loadedProject is null) { return null; } var references = _loadedProject.GetItems(ItemNames.ProjectReference); var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath); MSB.Evaluation.ProjectItem? item = null; // find by project file path item = references.First(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) || PathUtilities.PathsEqual(it.EvaluatedInclude, projectFilePath)); // try to find by project name item ??= references.First(it => string.Compare(projectName, it.GetMetadataValue(MetadataNames.Name), StringComparison.OrdinalIgnoreCase) == 0); return item; } public void AddAnalyzerReference(AnalyzerReference reference) { if (_loadedProject is null) { return; } if (reference is AnalyzerFileReference fileRef) { var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath); _loadedProject.AddItem(ItemNames.Analyzer, relativePath); } } public void RemoveAnalyzerReference(AnalyzerReference reference) { if (_loadedProject is null) { return; } if (reference is AnalyzerFileReference fileRef) { var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath); var analyzers = _loadedProject.GetItems(ItemNames.Analyzer); var item = analyzers.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) || PathUtilities.PathsEqual(it.EvaluatedInclude, fileRef.FullPath)); if (item != null) { _loadedProject.RemoveItem(item); } } } public void Save() { if (_loadedProject is null) { return; } _loadedProject.Save(); } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.MSBuild.Build; using Microsoft.CodeAnalysis.MSBuild.Logging; using Roslyn.Utilities; using MSB = Microsoft.Build; namespace Microsoft.CodeAnalysis.MSBuild { internal abstract class ProjectFile : IProjectFile { private readonly ProjectFileLoader _loader; private readonly MSB.Evaluation.Project? _loadedProject; private readonly ProjectBuildManager _buildManager; private readonly string _projectDirectory; public DiagnosticLog Log { get; } public virtual string FilePath => _loadedProject?.FullPath ?? string.Empty; public string Language => _loader.Language; protected ProjectFile(ProjectFileLoader loader, MSB.Evaluation.Project? loadedProject, ProjectBuildManager buildManager, DiagnosticLog log) { _loader = loader; _loadedProject = loadedProject; _buildManager = buildManager; var directory = loadedProject?.DirectoryPath ?? string.Empty; _projectDirectory = PathUtilities.EnsureTrailingSeparator(directory); Log = log; } protected abstract SourceCodeKind GetSourceCodeKind(string documentFileName); public abstract string GetDocumentExtension(SourceCodeKind kind); protected abstract IEnumerable<MSB.Framework.ITaskItem> GetCompilerCommandLineArgs(MSB.Execution.ProjectInstance executedProject); protected abstract ImmutableArray<string> ReadCommandLineArgs(MSB.Execution.ProjectInstance project); public async Task<ImmutableArray<ProjectFileInfo>> GetProjectFileInfosAsync(CancellationToken cancellationToken) { if (_loadedProject is null) { return ImmutableArray.Create(ProjectFileInfo.CreateEmpty(Language, _loadedProject?.FullPath, Log)); } var targetFrameworkValue = _loadedProject.GetPropertyValue(PropertyNames.TargetFramework); var targetFrameworksValue = _loadedProject.GetPropertyValue(PropertyNames.TargetFrameworks); if (RoslynString.IsNullOrEmpty(targetFrameworkValue) && !RoslynString.IsNullOrEmpty(targetFrameworksValue)) { // This project has a <TargetFrameworks> property, but does not specify a <TargetFramework>. // In this case, we need to iterate through the <TargetFrameworks>, set <TargetFramework> with // each value, and build the project. var targetFrameworks = targetFrameworksValue.Split(';'); var results = ImmutableArray.CreateBuilder<ProjectFileInfo>(targetFrameworks.Length); if (!_loadedProject.GlobalProperties.TryGetValue(PropertyNames.TargetFramework, out var initialGlobalTargetFrameworkValue)) initialGlobalTargetFrameworkValue = null; foreach (var targetFramework in targetFrameworks) { _loadedProject.SetGlobalProperty(PropertyNames.TargetFramework, targetFramework); _loadedProject.ReevaluateIfNecessary(); var projectFileInfo = await BuildProjectFileInfoAsync(cancellationToken).ConfigureAwait(false); results.Add(projectFileInfo); } if (initialGlobalTargetFrameworkValue is null) { _loadedProject.RemoveGlobalProperty(PropertyNames.TargetFramework); } else { _loadedProject.SetGlobalProperty(PropertyNames.TargetFramework, initialGlobalTargetFrameworkValue); } _loadedProject.ReevaluateIfNecessary(); return results.ToImmutable(); } else { var projectFileInfo = await BuildProjectFileInfoAsync(cancellationToken).ConfigureAwait(false); projectFileInfo ??= ProjectFileInfo.CreateEmpty(Language, _loadedProject?.FullPath, Log); return ImmutableArray.Create(projectFileInfo); } } private async Task<ProjectFileInfo> BuildProjectFileInfoAsync(CancellationToken cancellationToken) { if (_loadedProject is null) { return ProjectFileInfo.CreateEmpty(Language, _loadedProject?.FullPath, Log); } var project = await _buildManager.BuildProjectAsync(_loadedProject, Log, cancellationToken).ConfigureAwait(false); return project != null ? CreateProjectFileInfo(project) : ProjectFileInfo.CreateEmpty(Language, _loadedProject.FullPath, Log); } private ProjectFileInfo CreateProjectFileInfo(MSB.Execution.ProjectInstance project) { var commandLineArgs = GetCommandLineArgs(project); var outputFilePath = project.ReadPropertyString(PropertyNames.TargetPath); if (!RoslynString.IsNullOrWhiteSpace(outputFilePath)) { outputFilePath = GetAbsolutePathRelativeToProject(outputFilePath); } var outputRefFilePath = project.ReadPropertyString(PropertyNames.TargetRefPath); if (!RoslynString.IsNullOrWhiteSpace(outputRefFilePath)) { outputRefFilePath = GetAbsolutePathRelativeToProject(outputRefFilePath); } // Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace // by assigning the value of the project's root namespace to it. So various feature can choose to // use it for their own purpose. // In the future, we might consider officially exposing "default namespace" for VB project // (e.g. through a <defaultnamespace> msbuild property) var defaultNamespace = project.ReadPropertyString(PropertyNames.RootNamespace) ?? string.Empty; var targetFramework = project.ReadPropertyString(PropertyNames.TargetFramework); if (RoslynString.IsNullOrWhiteSpace(targetFramework)) { targetFramework = null; } var docs = project.GetDocuments() .Where(IsNotTemporaryGeneratedFile) .Select(MakeDocumentFileInfo) .ToImmutableArray(); var additionalDocs = project.GetAdditionalFiles() .Select(MakeNonSourceFileDocumentFileInfo) .ToImmutableArray(); var analyzerConfigDocs = project.GetEditorConfigFiles() .Select(MakeNonSourceFileDocumentFileInfo) .ToImmutableArray(); return ProjectFileInfo.Create( Language, project.FullPath, outputFilePath, outputRefFilePath, defaultNamespace, targetFramework, commandLineArgs, docs, additionalDocs, analyzerConfigDocs, project.GetProjectReferences().ToImmutableArray(), Log); } private ImmutableArray<string> GetCommandLineArgs(MSB.Execution.ProjectInstance project) { var commandLineArgs = GetCompilerCommandLineArgs(project) .Select(item => item.ItemSpec) .ToImmutableArray(); if (commandLineArgs.Length == 0) { // We didn't get any command-line args, which likely means that the build // was not successful. In that case, try to read the command-line args from // the ProjectInstance that we have. This is a best effort to provide something // meaningful for the user, though it will likely be incomplete. commandLineArgs = ReadCommandLineArgs(project); } return commandLineArgs; } protected static bool IsNotTemporaryGeneratedFile(MSB.Framework.ITaskItem item) => !Path.GetFileName(item.ItemSpec).StartsWith("TemporaryGeneratedFile_", StringComparison.Ordinal); private DocumentFileInfo MakeDocumentFileInfo(MSB.Framework.ITaskItem documentItem) { var filePath = GetDocumentFilePath(documentItem); var logicalPath = GetDocumentLogicalPath(documentItem, _projectDirectory); var isLinked = IsDocumentLinked(documentItem); var isGenerated = IsDocumentGenerated(documentItem); var sourceCodeKind = GetSourceCodeKind(filePath); return new DocumentFileInfo(filePath, logicalPath, isLinked, isGenerated, sourceCodeKind); } private DocumentFileInfo MakeNonSourceFileDocumentFileInfo(MSB.Framework.ITaskItem documentItem) { var filePath = GetDocumentFilePath(documentItem); var logicalPath = GetDocumentLogicalPath(documentItem, _projectDirectory); var isLinked = IsDocumentLinked(documentItem); var isGenerated = IsDocumentGenerated(documentItem); return new DocumentFileInfo(filePath, logicalPath, isLinked, isGenerated, SourceCodeKind.Regular); } /// <summary> /// Resolves the given path that is possibly relative to the project directory. /// </summary> /// <remarks> /// The resulting path is absolute but might not be normalized. /// </remarks> private string GetAbsolutePathRelativeToProject(string path) { // TODO (tomat): should we report an error when drive-relative path (e.g. "C:goo.cs") is encountered? var absolutePath = FileUtilities.ResolveRelativePath(path, _projectDirectory) ?? path; return FileUtilities.TryNormalizeAbsolutePath(absolutePath) ?? absolutePath; } private string GetDocumentFilePath(MSB.Framework.ITaskItem documentItem) => GetAbsolutePathRelativeToProject(documentItem.ItemSpec); private static bool IsDocumentLinked(MSB.Framework.ITaskItem documentItem) => !RoslynString.IsNullOrEmpty(documentItem.GetMetadata(MetadataNames.Link)); private IDictionary<string, MSB.Evaluation.ProjectItem>? _documents; protected bool IsDocumentGenerated(MSB.Framework.ITaskItem documentItem) { if (_documents == null) { _documents = new Dictionary<string, MSB.Evaluation.ProjectItem>(); if (_loadedProject is null) { return false; } foreach (var item in _loadedProject.GetItems(ItemNames.Compile)) { _documents[GetAbsolutePathRelativeToProject(item.EvaluatedInclude)] = item; } } return !_documents.ContainsKey(GetAbsolutePathRelativeToProject(documentItem.ItemSpec)); } protected static string GetDocumentLogicalPath(MSB.Framework.ITaskItem documentItem, string projectDirectory) { var link = documentItem.GetMetadata(MetadataNames.Link); if (!RoslynString.IsNullOrEmpty(link)) { // if a specific link is specified in the project file then use it to form the logical path. return link; } else { var filePath = documentItem.ItemSpec; if (!PathUtilities.IsAbsolute(filePath)) { return filePath; } var normalizedPath = FileUtilities.TryNormalizeAbsolutePath(filePath); if (normalizedPath == null) { return filePath; } // If the document is within the current project directory (or subdirectory), then the logical path is the relative path // from the project's directory. if (normalizedPath.StartsWith(projectDirectory, StringComparison.OrdinalIgnoreCase)) { return normalizedPath[projectDirectory.Length..]; } else { // if the document lies outside the project's directory (or subdirectory) then place it logically at the root of the project. // if more than one document ends up with the same logical name then so be it (the workspace will survive.) return PathUtilities.GetFileName(normalizedPath); } } } public void AddDocument(string filePath, string? logicalPath = null) { if (_loadedProject is null) { return; } var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath); Dictionary<string, string>? metadata = null; if (logicalPath != null && relativePath != logicalPath) { metadata = new Dictionary<string, string> { { MetadataNames.Link, logicalPath } }; relativePath = filePath; // link to full path } _loadedProject.AddItem(ItemNames.Compile, relativePath, metadata); } public void RemoveDocument(string filePath) { if (_loadedProject is null) { return; } var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath); var items = _loadedProject.GetItems(ItemNames.Compile); var item = items.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) || PathUtilities.PathsEqual(it.EvaluatedInclude, filePath)); if (item != null) { _loadedProject.RemoveItem(item); } } public void AddMetadataReference(MetadataReference reference, AssemblyIdentity identity) { if (_loadedProject is null) { return; } if (reference is PortableExecutableReference peRef && peRef.FilePath != null) { var metadata = new Dictionary<string, string>(); if (!peRef.Properties.Aliases.IsEmpty) { metadata.Add(MetadataNames.Aliases, string.Join(",", peRef.Properties.Aliases)); } if (IsInGAC(peRef.FilePath) && identity != null) { // Since the location of the reference is in GAC, need to use full identity name to find it again. // This typically happens when you base the reference off of a reflection assembly location. _loadedProject.AddItem(ItemNames.Reference, identity.GetDisplayName(), metadata); } else if (IsFrameworkReferenceAssembly(peRef.FilePath)) { // just use short name since this will be resolved by msbuild relative to the known framework reference assemblies. var fileName = identity != null ? identity.Name : Path.GetFileNameWithoutExtension(peRef.FilePath); _loadedProject.AddItem(ItemNames.Reference, fileName, metadata); } else // other location -- need hint to find correct assembly { var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, peRef.FilePath); var fileName = Path.GetFileNameWithoutExtension(peRef.FilePath); metadata.Add(MetadataNames.HintPath, relativePath); _loadedProject.AddItem(ItemNames.Reference, fileName, metadata); } } } private static bool IsInGAC(string filePath) { return GlobalAssemblyCacheLocation.RootLocations.Any(static (gloc, filePath) => PathUtilities.IsChildPath(gloc, filePath), filePath); } private static string? s_frameworkRoot; private static string FrameworkRoot { get { if (RoslynString.IsNullOrEmpty(s_frameworkRoot)) { var runtimeDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(); s_frameworkRoot = Path.GetDirectoryName(runtimeDir); // back out one directory level to be root path of all framework versions } return s_frameworkRoot ?? throw new InvalidOperationException($"Unable to get {nameof(FrameworkRoot)}"); } } private static bool IsFrameworkReferenceAssembly(string filePath) { return PathUtilities.IsChildPath(FrameworkRoot, filePath); } public void RemoveMetadataReference(MetadataReference reference, AssemblyIdentity identity) { if (_loadedProject is null) { return; } if (reference is PortableExecutableReference peRef && peRef.FilePath != null) { var item = FindReferenceItem(identity, peRef.FilePath); if (item != null) { _loadedProject.RemoveItem(item); } } } private MSB.Evaluation.ProjectItem FindReferenceItem(AssemblyIdentity identity, string filePath) { if (_loadedProject is null) { throw new InvalidOperationException($"Unable to find reference item '{identity?.Name}'"); } var references = _loadedProject.GetItems(ItemNames.Reference); MSB.Evaluation.ProjectItem? item = null; var fileName = Path.GetFileNameWithoutExtension(filePath); if (identity != null) { var shortAssemblyName = identity.Name; var fullAssemblyName = identity.GetDisplayName(); // check for short name match item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, shortAssemblyName, StringComparison.OrdinalIgnoreCase) == 0); // check for full name match item ??= references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, fullAssemblyName, StringComparison.OrdinalIgnoreCase) == 0); } // check for file path match if (item == null) { var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath); item = references.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, filePath) || PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) || PathUtilities.PathsEqual(GetHintPath(it), filePath) || PathUtilities.PathsEqual(GetHintPath(it), relativePath)); } // check for partial name match if (item == null && identity != null) { var partialName = identity.Name + ","; var items = references.Where(it => it.EvaluatedInclude.StartsWith(partialName, StringComparison.OrdinalIgnoreCase)).ToList(); if (items.Count == 1) { item = items[0]; } } return item ?? throw new InvalidOperationException($"Unable to find reference item '{identity?.Name}'"); } private static string GetHintPath(MSB.Evaluation.ProjectItem item) => item.Metadata.FirstOrDefault(m => string.Equals(m.Name, MetadataNames.HintPath, StringComparison.OrdinalIgnoreCase))?.EvaluatedValue ?? string.Empty; public void AddProjectReference(string projectName, ProjectFileReference reference) { if (_loadedProject is null) { return; } var metadata = new Dictionary<string, string> { { MetadataNames.Name, projectName } }; if (!reference.Aliases.IsEmpty) { metadata.Add(MetadataNames.Aliases, string.Join(",", reference.Aliases)); } var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, reference.Path); _loadedProject.AddItem(ItemNames.ProjectReference, relativePath, metadata); } public void RemoveProjectReference(string projectName, string projectFilePath) { if (_loadedProject is null) { return; } var item = FindProjectReferenceItem(projectName, projectFilePath); if (item != null) { _loadedProject.RemoveItem(item); } } private MSB.Evaluation.ProjectItem? FindProjectReferenceItem(string projectName, string projectFilePath) { if (_loadedProject is null) { return null; } var references = _loadedProject.GetItems(ItemNames.ProjectReference); var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath); MSB.Evaluation.ProjectItem? item = null; // find by project file path item = references.First(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) || PathUtilities.PathsEqual(it.EvaluatedInclude, projectFilePath)); // try to find by project name item ??= references.First(it => string.Compare(projectName, it.GetMetadataValue(MetadataNames.Name), StringComparison.OrdinalIgnoreCase) == 0); return item; } public void AddAnalyzerReference(AnalyzerReference reference) { if (_loadedProject is null) { return; } if (reference is AnalyzerFileReference fileRef) { var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath); _loadedProject.AddItem(ItemNames.Analyzer, relativePath); } } public void RemoveAnalyzerReference(AnalyzerReference reference) { if (_loadedProject is null) { return; } if (reference is AnalyzerFileReference fileRef) { var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath); var analyzers = _loadedProject.GetItems(ItemNames.Analyzer); var item = analyzers.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) || PathUtilities.PathsEqual(it.EvaluatedInclude, fileRef.FullPath)); if (item != null) { _loadedProject.RemoveItem(item); } } } public void Save() { if (_loadedProject is null) { return; } _loadedProject.Save(); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/Diagnostic/Diagnostic_SimpleDiagnostic.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A diagnostic (such as a compiler error or a warning), along with the location where it occurred. /// </summary> public abstract partial class Diagnostic { internal sealed class SimpleDiagnostic : Diagnostic { private readonly DiagnosticDescriptor _descriptor; private readonly DiagnosticSeverity _severity; private readonly int _warningLevel; private readonly Location _location; private readonly IReadOnlyList<Location> _additionalLocations; private readonly object?[] _messageArgs; private readonly ImmutableDictionary<string, string?> _properties; private readonly bool _isSuppressed; private SimpleDiagnostic( DiagnosticDescriptor descriptor, DiagnosticSeverity severity, int warningLevel, Location location, IEnumerable<Location>? additionalLocations, object?[]? messageArgs, ImmutableDictionary<string, string?>? properties, bool isSuppressed) { if ((warningLevel == 0 && severity != DiagnosticSeverity.Error) || (warningLevel != 0 && severity == DiagnosticSeverity.Error)) { throw new ArgumentException($"{nameof(warningLevel)} ({warningLevel}) and {nameof(severity)} ({severity}) are not compatible.", nameof(warningLevel)); } _descriptor = descriptor ?? throw new ArgumentNullException(nameof(descriptor)); _severity = severity; _warningLevel = warningLevel; _location = location ?? Location.None; _additionalLocations = additionalLocations?.ToImmutableArray() ?? SpecializedCollections.EmptyReadOnlyList<Location>(); _messageArgs = messageArgs ?? Array.Empty<object?>(); _properties = properties ?? ImmutableDictionary<string, string?>.Empty; _isSuppressed = isSuppressed; } internal static SimpleDiagnostic Create( DiagnosticDescriptor descriptor, DiagnosticSeverity severity, int warningLevel, Location location, IEnumerable<Location>? additionalLocations, object?[]? messageArgs, ImmutableDictionary<string, string?>? properties, bool isSuppressed = false) { return new SimpleDiagnostic(descriptor, severity, warningLevel, location, additionalLocations, messageArgs, properties, isSuppressed); } internal static SimpleDiagnostic Create(string id, LocalizableString title, string category, LocalizableString message, LocalizableString description, string helpLink, DiagnosticSeverity severity, DiagnosticSeverity defaultSeverity, bool isEnabledByDefault, int warningLevel, Location location, IEnumerable<Location>? additionalLocations, IEnumerable<string>? customTags, ImmutableDictionary<string, string?>? properties, bool isSuppressed = false) { var descriptor = new DiagnosticDescriptor(id, title, message, category, defaultSeverity, isEnabledByDefault, description, helpLink, customTags.ToImmutableArrayOrEmpty()); return new SimpleDiagnostic(descriptor, severity, warningLevel, location, additionalLocations, messageArgs: null, properties: properties, isSuppressed: isSuppressed); } public override DiagnosticDescriptor Descriptor { get { return _descriptor; } } public override string Id { get { return _descriptor.Id; } } public override string GetMessage(IFormatProvider? formatProvider = null) { if (_messageArgs.Length == 0) { return _descriptor.MessageFormat.ToString(formatProvider); } var localizedMessageFormat = _descriptor.MessageFormat.ToString(formatProvider); try { return string.Format(formatProvider, localizedMessageFormat, _messageArgs); } catch (Exception) { // Analyzer reported diagnostic with invalid format arguments, so just return the unformatted message. return localizedMessageFormat; } } internal override IReadOnlyList<object?> Arguments { get { return _messageArgs; } } public override DiagnosticSeverity Severity { get { return _severity; } } public override bool IsSuppressed { get { return _isSuppressed; } } public override int WarningLevel { get { return _warningLevel; } } public override Location Location { get { return _location; } } public override IReadOnlyList<Location> AdditionalLocations { get { return _additionalLocations; } } public override ImmutableDictionary<string, string?> Properties { get { return _properties; } } public override bool Equals(Diagnostic? obj) { if (ReferenceEquals(this, obj)) { return true; } var other = obj as SimpleDiagnostic; if (other == null) { return false; } if (AnalyzerExecutor.IsAnalyzerExceptionDiagnostic(this)) { // We have custom Equals logic for diagnostics generated for analyzer exceptions. return AnalyzerExecutor.AreEquivalentAnalyzerExceptionDiagnostics(this, other); } return _descriptor.Equals(other._descriptor) && _messageArgs.SequenceEqual(other._messageArgs, (a, b) => a == b) && _location == other._location && _severity == other._severity && _warningLevel == other._warningLevel; } public override int GetHashCode() { return Hash.Combine(_descriptor, Hash.CombineValues(_messageArgs, Hash.Combine(_warningLevel, Hash.Combine(_location, (int)_severity)))); } internal override Diagnostic WithLocation(Location location) { if (location is null) { throw new ArgumentNullException(nameof(location)); } if (location != _location) { return new SimpleDiagnostic(_descriptor, _severity, _warningLevel, location, _additionalLocations, _messageArgs, _properties, _isSuppressed); } return this; } internal override Diagnostic WithSeverity(DiagnosticSeverity severity) { if (this.Severity != severity) { var warningLevel = GetDefaultWarningLevel(severity); return new SimpleDiagnostic(_descriptor, severity, warningLevel, _location, _additionalLocations, _messageArgs, _properties, _isSuppressed); } return this; } internal override Diagnostic WithIsSuppressed(bool isSuppressed) { if (this.IsSuppressed != isSuppressed) { return new SimpleDiagnostic(_descriptor, _severity, _warningLevel, _location, _additionalLocations, _messageArgs, _properties, isSuppressed); } return this; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A diagnostic (such as a compiler error or a warning), along with the location where it occurred. /// </summary> public abstract partial class Diagnostic { internal sealed class SimpleDiagnostic : Diagnostic { private readonly DiagnosticDescriptor _descriptor; private readonly DiagnosticSeverity _severity; private readonly int _warningLevel; private readonly Location _location; private readonly IReadOnlyList<Location> _additionalLocations; private readonly object?[] _messageArgs; private readonly ImmutableDictionary<string, string?> _properties; private readonly bool _isSuppressed; private SimpleDiagnostic( DiagnosticDescriptor descriptor, DiagnosticSeverity severity, int warningLevel, Location location, IEnumerable<Location>? additionalLocations, object?[]? messageArgs, ImmutableDictionary<string, string?>? properties, bool isSuppressed) { if ((warningLevel == 0 && severity != DiagnosticSeverity.Error) || (warningLevel != 0 && severity == DiagnosticSeverity.Error)) { throw new ArgumentException($"{nameof(warningLevel)} ({warningLevel}) and {nameof(severity)} ({severity}) are not compatible.", nameof(warningLevel)); } _descriptor = descriptor ?? throw new ArgumentNullException(nameof(descriptor)); _severity = severity; _warningLevel = warningLevel; _location = location ?? Location.None; _additionalLocations = additionalLocations?.ToImmutableArray() ?? SpecializedCollections.EmptyReadOnlyList<Location>(); _messageArgs = messageArgs ?? Array.Empty<object?>(); _properties = properties ?? ImmutableDictionary<string, string?>.Empty; _isSuppressed = isSuppressed; } internal static SimpleDiagnostic Create( DiagnosticDescriptor descriptor, DiagnosticSeverity severity, int warningLevel, Location location, IEnumerable<Location>? additionalLocations, object?[]? messageArgs, ImmutableDictionary<string, string?>? properties, bool isSuppressed = false) { return new SimpleDiagnostic(descriptor, severity, warningLevel, location, additionalLocations, messageArgs, properties, isSuppressed); } internal static SimpleDiagnostic Create(string id, LocalizableString title, string category, LocalizableString message, LocalizableString description, string helpLink, DiagnosticSeverity severity, DiagnosticSeverity defaultSeverity, bool isEnabledByDefault, int warningLevel, Location location, IEnumerable<Location>? additionalLocations, IEnumerable<string>? customTags, ImmutableDictionary<string, string?>? properties, bool isSuppressed = false) { var descriptor = new DiagnosticDescriptor(id, title, message, category, defaultSeverity, isEnabledByDefault, description, helpLink, customTags.ToImmutableArrayOrEmpty()); return new SimpleDiagnostic(descriptor, severity, warningLevel, location, additionalLocations, messageArgs: null, properties: properties, isSuppressed: isSuppressed); } public override DiagnosticDescriptor Descriptor { get { return _descriptor; } } public override string Id { get { return _descriptor.Id; } } public override string GetMessage(IFormatProvider? formatProvider = null) { if (_messageArgs.Length == 0) { return _descriptor.MessageFormat.ToString(formatProvider); } var localizedMessageFormat = _descriptor.MessageFormat.ToString(formatProvider); try { return string.Format(formatProvider, localizedMessageFormat, _messageArgs); } catch (Exception) { // Analyzer reported diagnostic with invalid format arguments, so just return the unformatted message. return localizedMessageFormat; } } internal override IReadOnlyList<object?> Arguments { get { return _messageArgs; } } public override DiagnosticSeverity Severity { get { return _severity; } } public override bool IsSuppressed { get { return _isSuppressed; } } public override int WarningLevel { get { return _warningLevel; } } public override Location Location { get { return _location; } } public override IReadOnlyList<Location> AdditionalLocations { get { return _additionalLocations; } } public override ImmutableDictionary<string, string?> Properties { get { return _properties; } } public override bool Equals(Diagnostic? obj) { if (ReferenceEquals(this, obj)) { return true; } var other = obj as SimpleDiagnostic; if (other == null) { return false; } if (AnalyzerExecutor.IsAnalyzerExceptionDiagnostic(this)) { // We have custom Equals logic for diagnostics generated for analyzer exceptions. return AnalyzerExecutor.AreEquivalentAnalyzerExceptionDiagnostics(this, other); } return _descriptor.Equals(other._descriptor) && _messageArgs.SequenceEqual(other._messageArgs, (a, b) => a == b) && _location == other._location && _severity == other._severity && _warningLevel == other._warningLevel; } public override int GetHashCode() { return Hash.Combine(_descriptor, Hash.CombineValues(_messageArgs, Hash.Combine(_warningLevel, Hash.Combine(_location, (int)_severity)))); } internal override Diagnostic WithLocation(Location location) { if (location is null) { throw new ArgumentNullException(nameof(location)); } if (location != _location) { return new SimpleDiagnostic(_descriptor, _severity, _warningLevel, location, _additionalLocations, _messageArgs, _properties, _isSuppressed); } return this; } internal override Diagnostic WithSeverity(DiagnosticSeverity severity) { if (this.Severity != severity) { var warningLevel = GetDefaultWarningLevel(severity); return new SimpleDiagnostic(_descriptor, severity, warningLevel, _location, _additionalLocations, _messageArgs, _properties, _isSuppressed); } return this; } internal override Diagnostic WithIsSuppressed(bool isSuppressed) { if (this.IsSuppressed != isSuppressed) { return new SimpleDiagnostic(_descriptor, _severity, _warningLevel, _location, _additionalLocations, _messageArgs, _properties, isSuppressed); } return this; } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/Library/ObjectBrowser/Lists/MemberListItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists { internal class MemberListItem : SymbolListItem<ISymbol> { private readonly MemberKind _kind; private readonly bool _isInherited; internal MemberListItem(ProjectId projectId, ISymbol symbol, string displayText, string fullNameText, string searchText, bool isHidden, bool isInherited) : base(projectId, symbol, displayText, fullNameText, searchText, isHidden) { _isInherited = isInherited; switch (symbol.Kind) { case SymbolKind.Event: _kind = MemberKind.Event; break; case SymbolKind.Field: var fieldSymbol = (IFieldSymbol)symbol; if (fieldSymbol.ContainingType.TypeKind == TypeKind.Enum) { _kind = MemberKind.EnumMember; } else { _kind = fieldSymbol.IsConst ? MemberKind.Constant : MemberKind.Field; } break; case SymbolKind.Method: var methodSymbol = (IMethodSymbol)symbol; _kind = methodSymbol.MethodKind is MethodKind.Conversion or MethodKind.UserDefinedOperator ? MemberKind.Operator : MemberKind.Method; break; case SymbolKind.Property: _kind = MemberKind.Property; break; default: Debug.Fail("Unsupported symbol for member: " + symbol.Kind.ToString()); _kind = MemberKind.None; break; } } public bool IsInherited { get { return _isInherited; } } public MemberKind Kind { get { return _kind; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists { internal class MemberListItem : SymbolListItem<ISymbol> { private readonly MemberKind _kind; private readonly bool _isInherited; internal MemberListItem(ProjectId projectId, ISymbol symbol, string displayText, string fullNameText, string searchText, bool isHidden, bool isInherited) : base(projectId, symbol, displayText, fullNameText, searchText, isHidden) { _isInherited = isInherited; switch (symbol.Kind) { case SymbolKind.Event: _kind = MemberKind.Event; break; case SymbolKind.Field: var fieldSymbol = (IFieldSymbol)symbol; if (fieldSymbol.ContainingType.TypeKind == TypeKind.Enum) { _kind = MemberKind.EnumMember; } else { _kind = fieldSymbol.IsConst ? MemberKind.Constant : MemberKind.Field; } break; case SymbolKind.Method: var methodSymbol = (IMethodSymbol)symbol; _kind = methodSymbol.MethodKind is MethodKind.Conversion or MethodKind.UserDefinedOperator ? MemberKind.Operator : MemberKind.Method; break; case SymbolKind.Property: _kind = MemberKind.Property; break; default: Debug.Fail("Unsupported symbol for member: " + symbol.Kind.ToString()); _kind = MemberKind.None; break; } } public bool IsInherited { get { return _isInherited; } } public MemberKind Kind { get { return _kind; } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_RaiseEvent.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Diagnostics Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitRaiseEventStatement(node As BoundRaiseEventStatement) As BoundNode Dim syntax = node.Syntax Dim saveState As UnstructuredExceptionHandlingContext = LeaveUnstructuredExceptionHandlingContext(node) ' in the absence of errors invocation must be a call '(could also be BadExpression, but that would have errors) Dim raiseCallExpression = DirectCast(node.EventInvocation, BoundCall) Dim result As BoundStatement Dim receiver = raiseCallExpression.ReceiverOpt If receiver Is Nothing OrElse receiver.IsMeReference Then result = New BoundExpressionStatement( syntax, VisitExpressionNode(raiseCallExpression)) Else Debug.Assert(receiver.Kind = BoundKind.FieldAccess) #If DEBUG Then ' NOTE: The receiver is always as lowered as it's going to get (generally, a MeReference), so there's no need to Visit it. Dim fieldAccess As BoundFieldAccess = DirectCast(receiver, BoundFieldAccess) Dim fieldAccessReceiver = fieldAccess.ReceiverOpt Debug.Assert(fieldAccessReceiver Is Nothing OrElse fieldAccessReceiver.Kind = BoundKind.MeReference) #End If If node.EventSymbol.IsWindowsRuntimeEvent Then receiver = GetWindowsRuntimeEventReceiver(syntax, receiver) End If ' Need to null-check the receiver before invoking raise - ' ' eventField.raiseCallExpression === becomes ===> ' ' Block ' Dim temp = eventField ' if temp is Nothing GoTo skipEventRaise ' Call temp.raiseCallExpression ' skipEventRaise: ' End Block ' Dim temp As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, receiver.Type, SynthesizedLocalKind.LoweringTemp) Dim tempAccess As BoundLocal = New BoundLocal(syntax, temp, temp.Type).MakeCompilerGenerated Dim tempInit = New BoundExpressionStatement(syntax, New BoundAssignmentOperator(syntax, tempAccess, receiver, True, receiver.Type)).MakeCompilerGenerated ' replace receiver with temp. raiseCallExpression = raiseCallExpression.Update(raiseCallExpression.Method, raiseCallExpression.MethodGroupOpt, tempAccess, raiseCallExpression.Arguments, raiseCallExpression.DefaultArguments, raiseCallExpression.ConstantValueOpt, isLValue:=raiseCallExpression.IsLValue, suppressObjectClone:=raiseCallExpression.SuppressObjectClone, type:=raiseCallExpression.Type) Dim invokeStatement = New BoundExpressionStatement( syntax, VisitExpressionNode(raiseCallExpression)) Dim condition = New BoundBinaryOperator(syntax, BinaryOperatorKind.Is, tempAccess.MakeRValue(), New BoundLiteral(syntax, ConstantValue.Nothing, Me.Compilation.GetSpecialType(SpecialType.System_Object)), False, Me.Compilation.GetSpecialType(SpecialType.System_Boolean)).MakeCompilerGenerated Dim skipEventRaise As New GeneratedLabelSymbol("skipEventRaise") Dim ifNullSkip = New BoundConditionalGoto(syntax, condition, True, skipEventRaise).MakeCompilerGenerated result = New BoundBlock(syntax, Nothing, ImmutableArray.Create(temp), ImmutableArray.Create(Of BoundStatement)( tempInit, ifNullSkip, invokeStatement, New BoundLabelStatement(syntax, skipEventRaise))) End If RestoreUnstructuredExceptionHandlingContext(node, saveState) If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then result = RegisterUnstructuredExceptionHandlingResumeTarget(node.Syntax, result, canThrow:=True) End If If Instrument(node, result) Then result = _instrumenterOpt.InstrumentRaiseEventStatement(node, result) End If Return result End Function ' If the event is a WinRT event, then the backing field is actually an EventRegistrationTokenTable, ' rather than a delegate. If this is the case, then we replace the receiver with ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(eventField).InvocationList. Private Function GetWindowsRuntimeEventReceiver(syntax As SyntaxNode, rewrittenReceiver As BoundExpression) As BoundExpression Dim fieldType As NamedTypeSymbol = DirectCast(rewrittenReceiver.Type, NamedTypeSymbol) Debug.Assert(fieldType.Name = "EventRegistrationTokenTable") Dim getOrCreateMethod As MethodSymbol = DirectCast(Compilation.GetWellKnownTypeMember( WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable), MethodSymbol) Debug.Assert(getOrCreateMethod IsNot Nothing, "Checked during initial binding") Debug.Assert(TypeSymbol.Equals(getOrCreateMethod.ReturnType, fieldType.OriginalDefinition, TypeCompareKind.ConsiderEverything), "Shape of well-known member") getOrCreateMethod = getOrCreateMethod.AsMember(fieldType) Dim invocationListProperty As PropertySymbol = Nothing If TryGetWellknownMember(invocationListProperty, WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList, syntax) Then Dim invocationListAccessor As MethodSymbol = invocationListProperty.GetMethod If invocationListAccessor IsNot Nothing Then invocationListAccessor = invocationListAccessor.AsMember(fieldType) ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(_tokenTable) Dim getOrCreateCall = New BoundCall(syntax:=syntax, method:=getOrCreateMethod, methodGroupOpt:=Nothing, receiverOpt:=Nothing, arguments:=ImmutableArray.Create(Of BoundExpression)(rewrittenReceiver), constantValueOpt:=Nothing, isLValue:=False, suppressObjectClone:=False, type:=getOrCreateMethod.ReturnType).MakeCompilerGenerated() ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(_tokenTable).InvocationList Dim invocationListAccessorCall = New BoundCall(syntax:=syntax, method:=invocationListAccessor, methodGroupOpt:=Nothing, receiverOpt:=getOrCreateCall, arguments:=ImmutableArray(Of BoundExpression).Empty, constantValueOpt:=Nothing, isLValue:=False, suppressObjectClone:=False, type:=invocationListAccessor.ReturnType).MakeCompilerGenerated() Return invocationListAccessorCall End If Dim memberDescriptor As MemberDescriptor = WellKnownMembers.GetDescriptor(WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList) ' isWinMd only matters for set accessors, we can safely say false here Dim accessorName As String = Binder.GetAccessorName(invocationListProperty.Name, MethodKind.PropertyGet, isWinMd:=False) Dim info = GetDiagnosticForMissingRuntimeHelper(memberDescriptor.DeclaringTypeMetadataName, accessorName, _compilationState.Compilation.Options.EmbedVbCoreRuntime) _diagnostics.Add(info, syntax.GetLocation()) End If Return New BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(rewrittenReceiver), ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Diagnostics Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitRaiseEventStatement(node As BoundRaiseEventStatement) As BoundNode Dim syntax = node.Syntax Dim saveState As UnstructuredExceptionHandlingContext = LeaveUnstructuredExceptionHandlingContext(node) ' in the absence of errors invocation must be a call '(could also be BadExpression, but that would have errors) Dim raiseCallExpression = DirectCast(node.EventInvocation, BoundCall) Dim result As BoundStatement Dim receiver = raiseCallExpression.ReceiverOpt If receiver Is Nothing OrElse receiver.IsMeReference Then result = New BoundExpressionStatement( syntax, VisitExpressionNode(raiseCallExpression)) Else Debug.Assert(receiver.Kind = BoundKind.FieldAccess) #If DEBUG Then ' NOTE: The receiver is always as lowered as it's going to get (generally, a MeReference), so there's no need to Visit it. Dim fieldAccess As BoundFieldAccess = DirectCast(receiver, BoundFieldAccess) Dim fieldAccessReceiver = fieldAccess.ReceiverOpt Debug.Assert(fieldAccessReceiver Is Nothing OrElse fieldAccessReceiver.Kind = BoundKind.MeReference) #End If If node.EventSymbol.IsWindowsRuntimeEvent Then receiver = GetWindowsRuntimeEventReceiver(syntax, receiver) End If ' Need to null-check the receiver before invoking raise - ' ' eventField.raiseCallExpression === becomes ===> ' ' Block ' Dim temp = eventField ' if temp is Nothing GoTo skipEventRaise ' Call temp.raiseCallExpression ' skipEventRaise: ' End Block ' Dim temp As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, receiver.Type, SynthesizedLocalKind.LoweringTemp) Dim tempAccess As BoundLocal = New BoundLocal(syntax, temp, temp.Type).MakeCompilerGenerated Dim tempInit = New BoundExpressionStatement(syntax, New BoundAssignmentOperator(syntax, tempAccess, receiver, True, receiver.Type)).MakeCompilerGenerated ' replace receiver with temp. raiseCallExpression = raiseCallExpression.Update(raiseCallExpression.Method, raiseCallExpression.MethodGroupOpt, tempAccess, raiseCallExpression.Arguments, raiseCallExpression.DefaultArguments, raiseCallExpression.ConstantValueOpt, isLValue:=raiseCallExpression.IsLValue, suppressObjectClone:=raiseCallExpression.SuppressObjectClone, type:=raiseCallExpression.Type) Dim invokeStatement = New BoundExpressionStatement( syntax, VisitExpressionNode(raiseCallExpression)) Dim condition = New BoundBinaryOperator(syntax, BinaryOperatorKind.Is, tempAccess.MakeRValue(), New BoundLiteral(syntax, ConstantValue.Nothing, Me.Compilation.GetSpecialType(SpecialType.System_Object)), False, Me.Compilation.GetSpecialType(SpecialType.System_Boolean)).MakeCompilerGenerated Dim skipEventRaise As New GeneratedLabelSymbol("skipEventRaise") Dim ifNullSkip = New BoundConditionalGoto(syntax, condition, True, skipEventRaise).MakeCompilerGenerated result = New BoundBlock(syntax, Nothing, ImmutableArray.Create(temp), ImmutableArray.Create(Of BoundStatement)( tempInit, ifNullSkip, invokeStatement, New BoundLabelStatement(syntax, skipEventRaise))) End If RestoreUnstructuredExceptionHandlingContext(node, saveState) If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then result = RegisterUnstructuredExceptionHandlingResumeTarget(node.Syntax, result, canThrow:=True) End If If Instrument(node, result) Then result = _instrumenterOpt.InstrumentRaiseEventStatement(node, result) End If Return result End Function ' If the event is a WinRT event, then the backing field is actually an EventRegistrationTokenTable, ' rather than a delegate. If this is the case, then we replace the receiver with ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(eventField).InvocationList. Private Function GetWindowsRuntimeEventReceiver(syntax As SyntaxNode, rewrittenReceiver As BoundExpression) As BoundExpression Dim fieldType As NamedTypeSymbol = DirectCast(rewrittenReceiver.Type, NamedTypeSymbol) Debug.Assert(fieldType.Name = "EventRegistrationTokenTable") Dim getOrCreateMethod As MethodSymbol = DirectCast(Compilation.GetWellKnownTypeMember( WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable), MethodSymbol) Debug.Assert(getOrCreateMethod IsNot Nothing, "Checked during initial binding") Debug.Assert(TypeSymbol.Equals(getOrCreateMethod.ReturnType, fieldType.OriginalDefinition, TypeCompareKind.ConsiderEverything), "Shape of well-known member") getOrCreateMethod = getOrCreateMethod.AsMember(fieldType) Dim invocationListProperty As PropertySymbol = Nothing If TryGetWellknownMember(invocationListProperty, WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList, syntax) Then Dim invocationListAccessor As MethodSymbol = invocationListProperty.GetMethod If invocationListAccessor IsNot Nothing Then invocationListAccessor = invocationListAccessor.AsMember(fieldType) ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(_tokenTable) Dim getOrCreateCall = New BoundCall(syntax:=syntax, method:=getOrCreateMethod, methodGroupOpt:=Nothing, receiverOpt:=Nothing, arguments:=ImmutableArray.Create(Of BoundExpression)(rewrittenReceiver), constantValueOpt:=Nothing, isLValue:=False, suppressObjectClone:=False, type:=getOrCreateMethod.ReturnType).MakeCompilerGenerated() ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(_tokenTable).InvocationList Dim invocationListAccessorCall = New BoundCall(syntax:=syntax, method:=invocationListAccessor, methodGroupOpt:=Nothing, receiverOpt:=getOrCreateCall, arguments:=ImmutableArray(Of BoundExpression).Empty, constantValueOpt:=Nothing, isLValue:=False, suppressObjectClone:=False, type:=invocationListAccessor.ReturnType).MakeCompilerGenerated() Return invocationListAccessorCall End If Dim memberDescriptor As MemberDescriptor = WellKnownMembers.GetDescriptor(WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList) ' isWinMd only matters for set accessors, we can safely say false here Dim accessorName As String = Binder.GetAccessorName(invocationListProperty.Name, MethodKind.PropertyGet, isWinMd:=False) Dim info = GetDiagnosticForMissingRuntimeHelper(memberDescriptor.DeclaringTypeMetadataName, accessorName, _compilationState.Compilation.Options.EmbedVbCoreRuntime) _diagnostics.Add(info, syntax.GetLocation()) End If Return New BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(rewrittenReceiver), ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/FunctionId.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Internal.Log { /// <summary> /// Enum to uniquely identify each function location. /// </summary> internal enum FunctionId { // a value to use in unit tests that won't interfere with reporting // for our other scenarios. TestEvent_NotUsed = 1, WorkCoordinator_DocumentWorker_Enqueue = 2, WorkCoordinator_ProcessProjectAsync = 3, WorkCoordinator_ProcessDocumentAsync = 4, WorkCoordinator_SemanticChange_Enqueue = 5, WorkCoordinator_SemanticChange_EnqueueFromMember = 6, WorkCoordinator_SemanticChange_EnqueueFromType = 7, WorkCoordinator_SemanticChange_FullProjects = 8, WorkCoordinator_Project_Enqueue = 9, WorkCoordinator_AsyncWorkItemQueue_LastItem = 10, WorkCoordinator_AsyncWorkItemQueue_FirstItem = 11, Diagnostics_SyntaxDiagnostic = 12, Diagnostics_SemanticDiagnostic = 13, Diagnostics_ProjectDiagnostic = 14, Diagnostics_DocumentReset = 15, Diagnostics_DocumentOpen = 16, Diagnostics_RemoveDocument = 17, Diagnostics_RemoveProject = 18, Diagnostics_DocumentClose = 19, // add new values after this Run_Environment = 20, Run_Environment_Options = 21, Tagger_AdornmentManager_OnLayoutChanged = 22, Tagger_AdornmentManager_UpdateInvalidSpans = 23, Tagger_BatchChangeNotifier_NotifyEditorNow = 24, Tagger_BatchChangeNotifier_NotifyEditor = 25, Tagger_TagSource_RecomputeTags = 26, Tagger_TagSource_ProcessNewTags = 27, Tagger_SyntacticClassification_TagComputer_GetTags = 28, Tagger_SemanticClassification_TagProducer_ProduceTags = 29, Tagger_BraceHighlighting_TagProducer_ProduceTags = 30, Tagger_LineSeparator_TagProducer_ProduceTags = 31, Tagger_Outlining_TagProducer_ProduceTags = 32, Tagger_Highlighter_TagProducer_ProduceTags = 33, Tagger_ReferenceHighlighting_TagProducer_ProduceTags = 34, CaseCorrection_CaseCorrect = 35, CaseCorrection_ReplaceTokens = 36, CaseCorrection_AddReplacements = 37, CodeCleanup_CleanupAsync = 38, CodeCleanup_Cleanup = 39, CodeCleanup_IterateAllCodeCleanupProviders = 40, CodeCleanup_IterateOneCodeCleanup = 41, CommandHandler_GetCommandState = 42, CommandHandler_ExecuteHandlers = 43, CommandHandler_FormatCommand = 44, CommandHandler_CompleteStatement = 45, CommandHandler_ToggleBlockComment = 46, CommandHandler_ToggleLineComment = 47, Workspace_SourceText_GetChangeRanges = 48, Workspace_Recoverable_RecoverRootAsync = 49, Workspace_Recoverable_RecoverRoot = 50, Workspace_Recoverable_RecoverTextAsync = 51, Workspace_Recoverable_RecoverText = 52, Workspace_SkeletonAssembly_GetMetadataOnlyImage = 53, Workspace_SkeletonAssembly_EmitMetadataOnlyImage = 54, Workspace_Document_State_FullyParseSyntaxTree = 55, Workspace_Document_State_IncrementallyParseSyntaxTree = 56, Workspace_Document_GetSemanticModel = 57, Workspace_Document_GetSyntaxTree = 58, Workspace_Document_GetTextChanges = 59, Workspace_Project_GetCompilation = 60, Workspace_Project_CompilationTracker_BuildCompilationAsync = 61, Workspace_ApplyChanges = 62, Workspace_TryGetDocument = 63, Workspace_TryGetDocumentFromInProgressSolution = 64, // obsolete: Workspace_Solution_LinkedFileDiffMergingSession = 65, // obsolete: Workspace_Solution_LinkedFileDiffMergingSession_LinkedFileGroup = 66, Workspace_Solution_Info = 67, EndConstruct_DoStatement = 68, EndConstruct_XmlCData = 69, EndConstruct_XmlComment = 70, EndConstruct_XmlElement = 71, EndConstruct_XmlEmbeddedExpression = 72, EndConstruct_XmlProcessingInstruction = 73, FindReference_Rename = 74, FindReference_ChangeSignature = 75, FindReference = 76, FindReference_DetermineAllSymbolsAsync = 77, FindReference_CreateProjectMapAsync = 78, FindReference_CreateDocumentMapAsync = 79, FindReference_ProcessAsync = 80, FindReference_ProcessProjectAsync = 81, FindReference_ProcessDocumentAsync = 82, LineCommit_CommitRegion = 83, Formatting_TokenStreamConstruction = 84, Formatting_ContextInitialization = 85, Formatting_Format = 86, Formatting_ApplyResultToBuffer = 87, Formatting_IterateNodes = 88, Formatting_CollectIndentBlock = 89, Formatting_CollectSuppressOperation = 90, Formatting_CollectAlignOperation = 91, Formatting_CollectAnchorOperation = 92, Formatting_CollectTokenOperation = 93, Formatting_BuildContext = 94, Formatting_ApplySpaceAndLine = 95, Formatting_ApplyAnchorOperation = 96, Formatting_ApplyAlignOperation = 97, Formatting_AggregateCreateTextChanges = 98, Formatting_AggregateCreateFormattedRoot = 99, Formatting_CreateTextChanges = 100, Formatting_CreateFormattedRoot = 101, Formatting_Partitions = 102, SmartIndentation_Start = 103, SmartIndentation_OpenCurly = 104, SmartIndentation_CloseCurly = 105, Rename_InlineSession = 106, Rename_InlineSession_Session = 107, Rename_FindLinkedSpans = 108, Rename_GetSymbolRenameInfo = 109, Rename_OnTextBufferChanged = 110, Rename_ApplyReplacementText = 111, Rename_CommitCore = 112, Rename_CommitCoreWithPreview = 113, Rename_GetAsynchronousLocationsSource = 114, Rename_AllRenameLocations = 115, Rename_StartSearchingForSpansInAllOpenDocuments = 116, Rename_StartSearchingForSpansInOpenDocument = 117, Rename_CreateOpenTextBufferManagerForAllOpenDocs = 118, Rename_CreateOpenTextBufferManagerForAllOpenDocument = 119, Rename_ReportSpan = 120, Rename_GetNoChangeConflictResolution = 121, Rename_Tracking_BufferChanged = 122, TPLTask_TaskScheduled = 123, TPLTask_TaskStarted = 124, TPLTask_TaskCompleted = 125, Get_QuickInfo_Async = 126, Completion_ModelComputer_DoInBackground = 127, Completion_ModelComputation_FilterModelInBackground = 128, Completion_ModelComputation_WaitForModel = 129, Completion_SymbolCompletionProvider_GetItemsWorker = 130, Completion_KeywordCompletionProvider_GetItemsWorker = 131, Completion_SnippetCompletionProvider_GetItemsWorker_CSharp = 132, Completion_TypeImportCompletionProvider_GetCompletionItemsAsync = 133, Completion_ExtensionMethodImportCompletionProvider_GetCompletionItemsAsync = 134, SignatureHelp_ModelComputation_ComputeModelInBackground = 135, SignatureHelp_ModelComputation_UpdateModelInBackground = 136, Refactoring_CodeRefactoringService_GetRefactoringsAsync = 137, Refactoring_AddImport = 138, Refactoring_FullyQualify = 139, Refactoring_GenerateFromMembers_AddConstructorParametersFromMembers = 140, Refactoring_GenerateFromMembers_GenerateConstructorFromMembers = 141, Refactoring_GenerateFromMembers_GenerateEqualsAndGetHashCode = 142, Refactoring_GenerateMember_GenerateConstructor = 143, Refactoring_GenerateMember_GenerateDefaultConstructors = 144, Refactoring_GenerateMember_GenerateEnumMember = 145, Refactoring_GenerateMember_GenerateMethod = 146, Refactoring_GenerateMember_GenerateVariable = 147, Refactoring_ImplementAbstractClass = 148, Refactoring_ImplementInterface = 149, Refactoring_IntroduceVariable = 150, Refactoring_GenerateType = 151, Refactoring_RemoveUnnecessaryImports_CSharp = 152, Refactoring_RemoveUnnecessaryImports_VisualBasic = 153, Snippet_OnBeforeInsertion = 154, Snippet_OnAfterInsertion = 155, Misc_NonReentrantLock_BlockingWait = 156, Misc_SaveEventsSink_OnBeforeSave = 158, TaskList_Refresh = 159, TaskList_NavigateTo = 160, WinformDesigner_GenerateXML = 161, NavigateTo_Search = 162, NavigationService_VSDocumentNavigationService_NavigateTo = 163, NavigationBar_ComputeModelAsync = 164, NavigationBar_ItemService_GetMembersInTypes_CSharp = 165, NavigationBar_ItemService_GetTypesInFile_CSharp = 166, NavigationBar_UpdateDropDownsSynchronously_WaitForModel = 167, NavigationBar_UpdateDropDownsSynchronously_WaitForSelectedItemInfo = 168, EventHookup_Determine_If_Event_Hookup = 169, EventHookup_Generate_Handler = 170, EventHookup_Type_Char = 171, Cache_Created = 172, Cache_AddOrAccess = 173, Cache_Remove = 174, Cache_Evict = 175, Cache_EvictAll = 176, Cache_ItemRank = 177, TextStructureNavigator_GetExtentOfWord = 178, TextStructureNavigator_GetSpanOfEnclosing = 179, TextStructureNavigator_GetSpanOfFirstChild = 180, TextStructureNavigator_GetSpanOfNextSibling = 181, TextStructureNavigator_GetSpanOfPreviousSibling = 182, Debugging_LanguageDebugInfoService_GetDataTipSpanAndText = 183, Debugging_VsLanguageDebugInfo_ValidateBreakpointLocation = 184, Debugging_VsLanguageDebugInfo_GetProximityExpressions = 185, Debugging_VsLanguageDebugInfo_ResolveName = 186, Debugging_VsLanguageDebugInfo_GetNameOfLocation = 187, Debugging_VsLanguageDebugInfo_GetDataTipText = 188, Debugging_EncSession = 189, Debugging_EncSession_EditSession = 190, Debugging_EncSession_EditSession_EmitDeltaErrorId = 191, Debugging_EncSession_EditSession_RudeEdit = 192, Simplifier_ReduceAsync = 193, Simplifier_ExpandNode = 194, Simplifier_ExpandToken = 195, ForegroundNotificationService_Processed = 196, ForegroundNotificationService_NotifyOnForeground = 197, BackgroundCompiler_BuildCompilationsAsync = 198, PersistenceService_ReadAsync = 199, PersistenceService_WriteAsync = 200, PersistenceService_ReadAsyncFailed = 201, PersistenceService_WriteAsyncFailed = 202, PersistenceService_Initialization = 203, TemporaryStorageServiceFactory_ReadText = 204, TemporaryStorageServiceFactory_WriteText = 205, TemporaryStorageServiceFactory_ReadStream = 206, TemporaryStorageServiceFactory_WriteStream = 207, PullMembersUpWarning_ChangeTargetToAbstract = 208, PullMembersUpWarning_ChangeOriginToPublic = 209, PullMembersUpWarning_ChangeOriginToNonStatic = 210, PullMembersUpWarning_UserProceedToFinish = 211, PullMembersUpWarning_UserGoBack = 212, // currently no-one uses these SmartTags_RefreshSession = 213, SmartTags_SmartTagInitializeFixes = 214, SmartTags_ApplyQuickFix = 215, EditorTestApp_RefreshTask = 216, EditorTestApp_UpdateDiagnostics = 217, IncrementalAnalyzerProcessor_Analyzers = 218, IncrementalAnalyzerProcessor_Analyzer = 219, IncrementalAnalyzerProcessor_ActiveFileAnalyzers = 220, IncrementalAnalyzerProcessor_ActiveFileAnalyzer = 221, IncrementalAnalyzerProcessor_Shutdown = 222, WorkCoordinatorRegistrationService_Register = 223, WorkCoordinatorRegistrationService_Unregister = 224, WorkCoordinatorRegistrationService_Reanalyze = 225, // obsolete: WorkCoordinator_SolutionCrawlerOption = 226, WorkCoordinator_PersistentStorageAdded = 227, WorkCoordinator_PersistentStorageRemoved = 228, WorkCoordinator_Shutdown = 229, DiagnosticAnalyzerService_Analyzers = 230, DiagnosticAnalyzerDriver_AnalyzerCrash = 231, DiagnosticAnalyzerDriver_AnalyzerTypeCount = 232, // obsolete: PersistedSemanticVersion_Info = 233, StorageDatabase_Exceptions = 234, WorkCoordinator_ShutdownTimeout = 235, Diagnostics_HyperLink = 236, CodeFixes_FixAllOccurrencesSession = 237, CodeFixes_FixAllOccurrencesContext = 238, CodeFixes_FixAllOccurrencesComputation = 239, CodeFixes_FixAllOccurrencesComputation_Document_Diagnostics = 240, CodeFixes_FixAllOccurrencesComputation_Project_Diagnostics = 241, CodeFixes_FixAllOccurrencesComputation_Document_Fixes = 242, CodeFixes_FixAllOccurrencesComputation_Project_Fixes = 243, CodeFixes_FixAllOccurrencesComputation_Document_Merge = 244, CodeFixes_FixAllOccurrencesComputation_Project_Merge = 245, CodeFixes_FixAllOccurrencesPreviewChanges = 246, CodeFixes_ApplyChanges = 247, SolutionExplorer_AnalyzerItemSource_GetItems = 248, SolutionExplorer_DiagnosticItemSource_GetItems = 249, WorkCoordinator_ActiveFileEnqueue = 250, SymbolFinder_FindDeclarationsAsync = 251, SymbolFinder_Project_AddDeclarationsAsync = 252, SymbolFinder_Assembly_AddDeclarationsAsync = 253, SymbolFinder_Solution_Name_FindSourceDeclarationsAsync = 254, SymbolFinder_Project_Name_FindSourceDeclarationsAsync = 255, SymbolFinder_Solution_Predicate_FindSourceDeclarationsAsync = 256, SymbolFinder_Project_Predicate_FindSourceDeclarationsAsync = 257, Tagger_Diagnostics_RecomputeTags = 258, Tagger_Diagnostics_Updated = 259, SuggestedActions_HasSuggestedActionsAsync = 260, SuggestedActions_GetSuggestedActions = 261, AnalyzerDependencyCheckingService_LogConflict = 262, AnalyzerDependencyCheckingService_LogMissingDependency = 263, VirtualMemory_MemoryLow = 264, Extension_Exception = 265, WorkCoordinator_WaitForHigherPriorityOperationsAsync = 266, CSharp_Interactive_Window = 267, VisualBasic_Interactive_Window = 268, NonFatalWatson = 269, // GlobalOperationRegistration = 270, No longer fired. CommandHandler_FindAllReference = 271, CodefixInfobar_Enable = 272, CodefixInfobar_EnableAndIgnoreFutureErrors = 273, CodefixInfobar_LeaveDisabled = 274, CodefixInfobar_ErrorIgnored = 275, Refactoring_NamingStyle = 276, // Caches SymbolTreeInfo_ExceptionInCacheRead = 277, SpellChecker_ExceptionInCacheRead = 278, BKTree_ExceptionInCacheRead = 279, IntellisenseBuild_Failed = 280, FileTextLoader_FileLengthThresholdExceeded = 281, // Generic performance measurement action IDs MeasurePerformance_StartAction = 282, MeasurePerformance_StopAction = 283, Serializer_CreateChecksum = 284, Serializer_Serialize = 285, Serializer_Deserialize = 286, CodeAnalysisService_CalculateDiagnosticsAsync = 287, CodeAnalysisService_SerializeDiagnosticResultAsync = 288, CodeAnalysisService_GetReferenceCountAsync = 289, CodeAnalysisService_FindReferenceLocationsAsync = 290, CodeAnalysisService_FindReferenceMethodsAsync = 291, CodeAnalysisService_GetFullyQualifiedName = 292, CodeAnalysisService_GetTodoCommentsAsync = 293, CodeAnalysisService_GetDesignerAttributesAsync = 294, ServiceHubRemoteHostClient_CreateAsync = 295, // obsolete: PinnedRemotableDataScope_GetRemotableData = 296, RemoteHost_Connect = 297, RemoteHost_Disconnect = 298, // obsolete: RemoteHostClientService_AddGlobalAssetsAsync = 299, // obsolete: RemoteHostClientService_RemoveGlobalAssets = 300, // obsolete: RemoteHostClientService_Enabled = 301, // obsolete: RemoteHostClientService_Restarted = 302, RemoteHostService_SynchronizePrimaryWorkspaceAsync = 303, // obsolete: RemoteHostService_SynchronizeGlobalAssetsAsync = 304, AssetStorage_CleanAssets = 305, AssetStorage_TryGetAsset = 306, AssetService_GetAssetAsync = 307, AssetService_SynchronizeAssetsAsync = 308, AssetService_SynchronizeSolutionAssetsAsync = 309, AssetService_SynchronizeProjectAssetsAsync = 310, CodeLens_GetReferenceCountAsync = 311, CodeLens_FindReferenceLocationsAsync = 312, CodeLens_FindReferenceMethodsAsync = 313, CodeLens_GetFullyQualifiedName = 314, SolutionState_ComputeChecksumsAsync = 315, ProjectState_ComputeChecksumsAsync = 316, DocumentState_ComputeChecksumsAsync = 317, // obsolete: SolutionSynchronizationService_GetRemotableData = 318, // obsolete: SolutionSynchronizationServiceFactory_CreatePinnedRemotableDataScopeAsync = 319, SolutionChecksumUpdater_SynchronizePrimaryWorkspace = 320, JsonRpcSession_RequestAssetAsync = 321, SolutionService_GetSolutionAsync = 322, SolutionService_UpdatePrimaryWorkspaceAsync = 323, RemoteHostService_GetAssetsAsync = 324, // obsolete: CompilationService_GetCompilationAsync = 325, SolutionCreator_AssetDifferences = 326, Extension_InfoBar = 327, FxCopAnalyzersInstall = 328, AssetStorage_ForceGC = 329, // obsolete: RemoteHost_Bitness = 330, Intellisense_Completion = 331, MetadataOnlyImage_EmitFailure = 332, LiveTableDataSource_OnDiagnosticsUpdated = 333, Experiment_KeybindingsReset = 334, Diagnostics_GeneratePerformaceReport = 335, Diagnostics_BadAnalyzer = 336, CodeAnalysisService_ReportAnalyzerPerformance = 337, PerformanceTrackerService_AddSnapshot = 338, // obsolete: AbstractProject_SetIntelliSenseBuild = 339, // obsolete: AbstractProject_Created = 340, // obsolete: AbstractProject_PushedToWorkspace = 341, ExternalErrorDiagnosticUpdateSource_AddError = 342, DiagnosticIncrementalAnalyzer_SynchronizeWithBuildAsync = 343, Completion_ExecuteCommand_TypeChar = 344, RemoteHostService_SynchronizeTextAsync = 345, SymbolFinder_Solution_Pattern_FindSourceDeclarationsAsync = 346, SymbolFinder_Project_Pattern_FindSourceDeclarationsAsync = 347, // obsolete: Intellisense_Completion_Commit = 348, CodeCleanupInfobar_BarDisplayed = 349, CodeCleanupInfobar_ConfigureNow = 350, CodeCleanupInfobar_NeverShowCodeCleanupInfoBarAgain = 351, FormatDocument = 352, CodeCleanup_ApplyCodeFixesAsync = 353, CodeCleanup_RemoveUnusedImports = 354, CodeCleanup_SortImports = 355, CodeCleanup_Format = 356, CodeCleanupABTest_AssignedToOnByDefault = 357, CodeCleanupABTest_AssignedToOffByDefault = 358, Workspace_Events = 359, Refactoring_ExtractMethod_UnknownMatrixItem = 360, SyntaxTreeIndex_Precalculate = 361, SyntaxTreeIndex_Precalculate_Create = 362, SymbolTreeInfo_Create = 363, SymbolTreeInfo_TryLoadOrCreate = 364, CommandHandler_GoToImplementation = 365, GraphQuery_ImplementedBy = 366, GraphQuery_Implements = 367, GraphQuery_IsCalledBy = 368, GraphQuery_IsUsedBy = 369, GraphQuery_Overrides = 370, Intellisense_AsyncCompletion_Data = 371, Intellisense_CompletionProviders_Data = 372, RemoteHostService_IsExperimentEnabledAsync = 373, PartialLoad_FullyLoaded = 374, Liveshare_UnknownCodeAction = 375, // obsolete: Liveshare_LexicalClassifications = 376, // obsolete: Liveshare_SyntacticClassifications = 377, // obsolete: Liveshare_SyntacticTagger = 378, CommandHandler_GoToBase = 379, DiagnosticAnalyzerService_GetDiagnosticsForSpanAsync = 380, CodeFixes_GetCodeFixesAsync = 381, LanguageServer_ActivateFailed = 382, LanguageServer_OnLoadedFailed = 383, CodeFixes_AddExplicitCast = 384, ToolsOptions_GenerateEditorconfig = 385, Renamer_RenameSymbolAsync = 386, Renamer_FindRenameLocationsAsync = 387, Renamer_ResolveConflictsAsync = 388, ChangeSignature_Data = 400, AbstractEncapsulateFieldService_EncapsulateFieldsAsync = 410, AbstractConvertTupleToStructCodeRefactoringProvider_ConvertToStructAsync = 420, DependentTypeFinder_FindAndCacheDerivedClassesAsync = 430, DependentTypeFinder_FindAndCacheDerivedInterfacesAsync = 431, DependentTypeFinder_FindAndCacheImplementingTypesAsync = 432, RemoteSemanticClassificationCacheService_ExceptionInCacheRead = 440, // obsolete: FeatureNotAvailable = 441, LSPCompletion_MissingLSPCompletionTriggerKind = 450, LSPCompletion_MissingLSPCompletionInvokeKind = 451, Workspace_Project_CompilationThrownAway = 460, CommandHandler_Paste_ImportsOnPaste = 470, // Superseded by LSP_FindDocumentInWorkspace // obsolete: FindDocumentInWorkspace = 480, RegisterWorkspace = 481, LSP_RequestCounter = 482, LSP_RequestDuration = 483, LSP_TimeInQueue = 484, Intellicode_UnknownIntent = 485, LSP_CompletionListCacheMiss = 486, InheritanceMargin_TargetsMenuOpen = 487, InheritanceMargin_NavigateToTarget = 488, VS_ErrorReportingService_ShowGlobalErrorInfo = 489, UnusedReferences_GetUnusedReferences = 490, ValueTracking_Command = 491, ValueTracking_TrackValueSource = 492, InheritanceMargin_GetInheritanceMemberItems = 493, LSP_FindDocumentInWorkspace = 494, SuggestedActions_GetSuggestedActionsAsync = 500, NavigateTo_CacheItemsMiss = 510, AssetService_Perf = 520, Inline_Hints_DoubleClick = 530, NavigateToExternalSources = 531, StackTraceToolWindow_ShowOnActivated = 540, CodeModel_FileCodeModel_Create = 550, Refactoring_FixAllOccurrencesSession = 560, Refactoring_FixAllOccurrencesContext = 561, Refactoring_FixAllOccurrencesComputation = 562, Refactoring_FixAllOccurrencesPreviewChanges = 563, LSP_UsedForkedSolution = 571, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Internal.Log { /// <summary> /// Enum to uniquely identify each function location. /// </summary> internal enum FunctionId { // a value to use in unit tests that won't interfere with reporting // for our other scenarios. TestEvent_NotUsed = 1, WorkCoordinator_DocumentWorker_Enqueue = 2, WorkCoordinator_ProcessProjectAsync = 3, WorkCoordinator_ProcessDocumentAsync = 4, WorkCoordinator_SemanticChange_Enqueue = 5, WorkCoordinator_SemanticChange_EnqueueFromMember = 6, WorkCoordinator_SemanticChange_EnqueueFromType = 7, WorkCoordinator_SemanticChange_FullProjects = 8, WorkCoordinator_Project_Enqueue = 9, WorkCoordinator_AsyncWorkItemQueue_LastItem = 10, WorkCoordinator_AsyncWorkItemQueue_FirstItem = 11, Diagnostics_SyntaxDiagnostic = 12, Diagnostics_SemanticDiagnostic = 13, Diagnostics_ProjectDiagnostic = 14, Diagnostics_DocumentReset = 15, Diagnostics_DocumentOpen = 16, Diagnostics_RemoveDocument = 17, Diagnostics_RemoveProject = 18, Diagnostics_DocumentClose = 19, // add new values after this Run_Environment = 20, Run_Environment_Options = 21, Tagger_AdornmentManager_OnLayoutChanged = 22, Tagger_AdornmentManager_UpdateInvalidSpans = 23, Tagger_BatchChangeNotifier_NotifyEditorNow = 24, Tagger_BatchChangeNotifier_NotifyEditor = 25, Tagger_TagSource_RecomputeTags = 26, Tagger_TagSource_ProcessNewTags = 27, Tagger_SyntacticClassification_TagComputer_GetTags = 28, Tagger_SemanticClassification_TagProducer_ProduceTags = 29, Tagger_BraceHighlighting_TagProducer_ProduceTags = 30, Tagger_LineSeparator_TagProducer_ProduceTags = 31, Tagger_Outlining_TagProducer_ProduceTags = 32, Tagger_Highlighter_TagProducer_ProduceTags = 33, Tagger_ReferenceHighlighting_TagProducer_ProduceTags = 34, CaseCorrection_CaseCorrect = 35, CaseCorrection_ReplaceTokens = 36, CaseCorrection_AddReplacements = 37, CodeCleanup_CleanupAsync = 38, CodeCleanup_Cleanup = 39, CodeCleanup_IterateAllCodeCleanupProviders = 40, CodeCleanup_IterateOneCodeCleanup = 41, CommandHandler_GetCommandState = 42, CommandHandler_ExecuteHandlers = 43, CommandHandler_FormatCommand = 44, CommandHandler_CompleteStatement = 45, CommandHandler_ToggleBlockComment = 46, CommandHandler_ToggleLineComment = 47, Workspace_SourceText_GetChangeRanges = 48, Workspace_Recoverable_RecoverRootAsync = 49, Workspace_Recoverable_RecoverRoot = 50, Workspace_Recoverable_RecoverTextAsync = 51, Workspace_Recoverable_RecoverText = 52, Workspace_SkeletonAssembly_GetMetadataOnlyImage = 53, Workspace_SkeletonAssembly_EmitMetadataOnlyImage = 54, Workspace_Document_State_FullyParseSyntaxTree = 55, Workspace_Document_State_IncrementallyParseSyntaxTree = 56, Workspace_Document_GetSemanticModel = 57, Workspace_Document_GetSyntaxTree = 58, Workspace_Document_GetTextChanges = 59, Workspace_Project_GetCompilation = 60, Workspace_Project_CompilationTracker_BuildCompilationAsync = 61, Workspace_ApplyChanges = 62, Workspace_TryGetDocument = 63, Workspace_TryGetDocumentFromInProgressSolution = 64, // obsolete: Workspace_Solution_LinkedFileDiffMergingSession = 65, // obsolete: Workspace_Solution_LinkedFileDiffMergingSession_LinkedFileGroup = 66, Workspace_Solution_Info = 67, EndConstruct_DoStatement = 68, EndConstruct_XmlCData = 69, EndConstruct_XmlComment = 70, EndConstruct_XmlElement = 71, EndConstruct_XmlEmbeddedExpression = 72, EndConstruct_XmlProcessingInstruction = 73, FindReference_Rename = 74, FindReference_ChangeSignature = 75, FindReference = 76, FindReference_DetermineAllSymbolsAsync = 77, FindReference_CreateProjectMapAsync = 78, FindReference_CreateDocumentMapAsync = 79, FindReference_ProcessAsync = 80, FindReference_ProcessProjectAsync = 81, FindReference_ProcessDocumentAsync = 82, LineCommit_CommitRegion = 83, Formatting_TokenStreamConstruction = 84, Formatting_ContextInitialization = 85, Formatting_Format = 86, Formatting_ApplyResultToBuffer = 87, Formatting_IterateNodes = 88, Formatting_CollectIndentBlock = 89, Formatting_CollectSuppressOperation = 90, Formatting_CollectAlignOperation = 91, Formatting_CollectAnchorOperation = 92, Formatting_CollectTokenOperation = 93, Formatting_BuildContext = 94, Formatting_ApplySpaceAndLine = 95, Formatting_ApplyAnchorOperation = 96, Formatting_ApplyAlignOperation = 97, Formatting_AggregateCreateTextChanges = 98, Formatting_AggregateCreateFormattedRoot = 99, Formatting_CreateTextChanges = 100, Formatting_CreateFormattedRoot = 101, Formatting_Partitions = 102, SmartIndentation_Start = 103, SmartIndentation_OpenCurly = 104, SmartIndentation_CloseCurly = 105, Rename_InlineSession = 106, Rename_InlineSession_Session = 107, Rename_FindLinkedSpans = 108, Rename_GetSymbolRenameInfo = 109, Rename_OnTextBufferChanged = 110, Rename_ApplyReplacementText = 111, Rename_CommitCore = 112, Rename_CommitCoreWithPreview = 113, Rename_GetAsynchronousLocationsSource = 114, Rename_AllRenameLocations = 115, Rename_StartSearchingForSpansInAllOpenDocuments = 116, Rename_StartSearchingForSpansInOpenDocument = 117, Rename_CreateOpenTextBufferManagerForAllOpenDocs = 118, Rename_CreateOpenTextBufferManagerForAllOpenDocument = 119, Rename_ReportSpan = 120, Rename_GetNoChangeConflictResolution = 121, Rename_Tracking_BufferChanged = 122, TPLTask_TaskScheduled = 123, TPLTask_TaskStarted = 124, TPLTask_TaskCompleted = 125, Get_QuickInfo_Async = 126, Completion_ModelComputer_DoInBackground = 127, Completion_ModelComputation_FilterModelInBackground = 128, Completion_ModelComputation_WaitForModel = 129, Completion_SymbolCompletionProvider_GetItemsWorker = 130, Completion_KeywordCompletionProvider_GetItemsWorker = 131, Completion_SnippetCompletionProvider_GetItemsWorker_CSharp = 132, Completion_TypeImportCompletionProvider_GetCompletionItemsAsync = 133, Completion_ExtensionMethodImportCompletionProvider_GetCompletionItemsAsync = 134, SignatureHelp_ModelComputation_ComputeModelInBackground = 135, SignatureHelp_ModelComputation_UpdateModelInBackground = 136, Refactoring_CodeRefactoringService_GetRefactoringsAsync = 137, Refactoring_AddImport = 138, Refactoring_FullyQualify = 139, Refactoring_GenerateFromMembers_AddConstructorParametersFromMembers = 140, Refactoring_GenerateFromMembers_GenerateConstructorFromMembers = 141, Refactoring_GenerateFromMembers_GenerateEqualsAndGetHashCode = 142, Refactoring_GenerateMember_GenerateConstructor = 143, Refactoring_GenerateMember_GenerateDefaultConstructors = 144, Refactoring_GenerateMember_GenerateEnumMember = 145, Refactoring_GenerateMember_GenerateMethod = 146, Refactoring_GenerateMember_GenerateVariable = 147, Refactoring_ImplementAbstractClass = 148, Refactoring_ImplementInterface = 149, Refactoring_IntroduceVariable = 150, Refactoring_GenerateType = 151, Refactoring_RemoveUnnecessaryImports_CSharp = 152, Refactoring_RemoveUnnecessaryImports_VisualBasic = 153, Snippet_OnBeforeInsertion = 154, Snippet_OnAfterInsertion = 155, Misc_NonReentrantLock_BlockingWait = 156, Misc_SaveEventsSink_OnBeforeSave = 158, TaskList_Refresh = 159, TaskList_NavigateTo = 160, WinformDesigner_GenerateXML = 161, NavigateTo_Search = 162, NavigationService_VSDocumentNavigationService_NavigateTo = 163, NavigationBar_ComputeModelAsync = 164, NavigationBar_ItemService_GetMembersInTypes_CSharp = 165, NavigationBar_ItemService_GetTypesInFile_CSharp = 166, NavigationBar_UpdateDropDownsSynchronously_WaitForModel = 167, NavigationBar_UpdateDropDownsSynchronously_WaitForSelectedItemInfo = 168, EventHookup_Determine_If_Event_Hookup = 169, EventHookup_Generate_Handler = 170, EventHookup_Type_Char = 171, Cache_Created = 172, Cache_AddOrAccess = 173, Cache_Remove = 174, Cache_Evict = 175, Cache_EvictAll = 176, Cache_ItemRank = 177, TextStructureNavigator_GetExtentOfWord = 178, TextStructureNavigator_GetSpanOfEnclosing = 179, TextStructureNavigator_GetSpanOfFirstChild = 180, TextStructureNavigator_GetSpanOfNextSibling = 181, TextStructureNavigator_GetSpanOfPreviousSibling = 182, Debugging_LanguageDebugInfoService_GetDataTipSpanAndText = 183, Debugging_VsLanguageDebugInfo_ValidateBreakpointLocation = 184, Debugging_VsLanguageDebugInfo_GetProximityExpressions = 185, Debugging_VsLanguageDebugInfo_ResolveName = 186, Debugging_VsLanguageDebugInfo_GetNameOfLocation = 187, Debugging_VsLanguageDebugInfo_GetDataTipText = 188, Debugging_EncSession = 189, Debugging_EncSession_EditSession = 190, Debugging_EncSession_EditSession_EmitDeltaErrorId = 191, Debugging_EncSession_EditSession_RudeEdit = 192, Simplifier_ReduceAsync = 193, Simplifier_ExpandNode = 194, Simplifier_ExpandToken = 195, ForegroundNotificationService_Processed = 196, ForegroundNotificationService_NotifyOnForeground = 197, BackgroundCompiler_BuildCompilationsAsync = 198, PersistenceService_ReadAsync = 199, PersistenceService_WriteAsync = 200, PersistenceService_ReadAsyncFailed = 201, PersistenceService_WriteAsyncFailed = 202, PersistenceService_Initialization = 203, TemporaryStorageServiceFactory_ReadText = 204, TemporaryStorageServiceFactory_WriteText = 205, TemporaryStorageServiceFactory_ReadStream = 206, TemporaryStorageServiceFactory_WriteStream = 207, PullMembersUpWarning_ChangeTargetToAbstract = 208, PullMembersUpWarning_ChangeOriginToPublic = 209, PullMembersUpWarning_ChangeOriginToNonStatic = 210, PullMembersUpWarning_UserProceedToFinish = 211, PullMembersUpWarning_UserGoBack = 212, // currently no-one uses these SmartTags_RefreshSession = 213, SmartTags_SmartTagInitializeFixes = 214, SmartTags_ApplyQuickFix = 215, EditorTestApp_RefreshTask = 216, EditorTestApp_UpdateDiagnostics = 217, IncrementalAnalyzerProcessor_Analyzers = 218, IncrementalAnalyzerProcessor_Analyzer = 219, IncrementalAnalyzerProcessor_ActiveFileAnalyzers = 220, IncrementalAnalyzerProcessor_ActiveFileAnalyzer = 221, IncrementalAnalyzerProcessor_Shutdown = 222, WorkCoordinatorRegistrationService_Register = 223, WorkCoordinatorRegistrationService_Unregister = 224, WorkCoordinatorRegistrationService_Reanalyze = 225, // obsolete: WorkCoordinator_SolutionCrawlerOption = 226, WorkCoordinator_PersistentStorageAdded = 227, WorkCoordinator_PersistentStorageRemoved = 228, WorkCoordinator_Shutdown = 229, DiagnosticAnalyzerService_Analyzers = 230, DiagnosticAnalyzerDriver_AnalyzerCrash = 231, DiagnosticAnalyzerDriver_AnalyzerTypeCount = 232, // obsolete: PersistedSemanticVersion_Info = 233, StorageDatabase_Exceptions = 234, WorkCoordinator_ShutdownTimeout = 235, Diagnostics_HyperLink = 236, CodeFixes_FixAllOccurrencesSession = 237, CodeFixes_FixAllOccurrencesContext = 238, CodeFixes_FixAllOccurrencesComputation = 239, CodeFixes_FixAllOccurrencesComputation_Document_Diagnostics = 240, CodeFixes_FixAllOccurrencesComputation_Project_Diagnostics = 241, CodeFixes_FixAllOccurrencesComputation_Document_Fixes = 242, CodeFixes_FixAllOccurrencesComputation_Project_Fixes = 243, CodeFixes_FixAllOccurrencesComputation_Document_Merge = 244, CodeFixes_FixAllOccurrencesComputation_Project_Merge = 245, CodeFixes_FixAllOccurrencesPreviewChanges = 246, CodeFixes_ApplyChanges = 247, SolutionExplorer_AnalyzerItemSource_GetItems = 248, SolutionExplorer_DiagnosticItemSource_GetItems = 249, WorkCoordinator_ActiveFileEnqueue = 250, SymbolFinder_FindDeclarationsAsync = 251, SymbolFinder_Project_AddDeclarationsAsync = 252, SymbolFinder_Assembly_AddDeclarationsAsync = 253, SymbolFinder_Solution_Name_FindSourceDeclarationsAsync = 254, SymbolFinder_Project_Name_FindSourceDeclarationsAsync = 255, SymbolFinder_Solution_Predicate_FindSourceDeclarationsAsync = 256, SymbolFinder_Project_Predicate_FindSourceDeclarationsAsync = 257, Tagger_Diagnostics_RecomputeTags = 258, Tagger_Diagnostics_Updated = 259, SuggestedActions_HasSuggestedActionsAsync = 260, SuggestedActions_GetSuggestedActions = 261, AnalyzerDependencyCheckingService_LogConflict = 262, AnalyzerDependencyCheckingService_LogMissingDependency = 263, VirtualMemory_MemoryLow = 264, Extension_Exception = 265, WorkCoordinator_WaitForHigherPriorityOperationsAsync = 266, CSharp_Interactive_Window = 267, VisualBasic_Interactive_Window = 268, NonFatalWatson = 269, // GlobalOperationRegistration = 270, No longer fired. CommandHandler_FindAllReference = 271, CodefixInfobar_Enable = 272, CodefixInfobar_EnableAndIgnoreFutureErrors = 273, CodefixInfobar_LeaveDisabled = 274, CodefixInfobar_ErrorIgnored = 275, Refactoring_NamingStyle = 276, // Caches SymbolTreeInfo_ExceptionInCacheRead = 277, SpellChecker_ExceptionInCacheRead = 278, BKTree_ExceptionInCacheRead = 279, IntellisenseBuild_Failed = 280, FileTextLoader_FileLengthThresholdExceeded = 281, // Generic performance measurement action IDs MeasurePerformance_StartAction = 282, MeasurePerformance_StopAction = 283, Serializer_CreateChecksum = 284, Serializer_Serialize = 285, Serializer_Deserialize = 286, CodeAnalysisService_CalculateDiagnosticsAsync = 287, CodeAnalysisService_SerializeDiagnosticResultAsync = 288, CodeAnalysisService_GetReferenceCountAsync = 289, CodeAnalysisService_FindReferenceLocationsAsync = 290, CodeAnalysisService_FindReferenceMethodsAsync = 291, CodeAnalysisService_GetFullyQualifiedName = 292, CodeAnalysisService_GetTodoCommentsAsync = 293, CodeAnalysisService_GetDesignerAttributesAsync = 294, ServiceHubRemoteHostClient_CreateAsync = 295, // obsolete: PinnedRemotableDataScope_GetRemotableData = 296, RemoteHost_Connect = 297, RemoteHost_Disconnect = 298, // obsolete: RemoteHostClientService_AddGlobalAssetsAsync = 299, // obsolete: RemoteHostClientService_RemoveGlobalAssets = 300, // obsolete: RemoteHostClientService_Enabled = 301, // obsolete: RemoteHostClientService_Restarted = 302, RemoteHostService_SynchronizePrimaryWorkspaceAsync = 303, // obsolete: RemoteHostService_SynchronizeGlobalAssetsAsync = 304, AssetStorage_CleanAssets = 305, AssetStorage_TryGetAsset = 306, AssetService_GetAssetAsync = 307, AssetService_SynchronizeAssetsAsync = 308, AssetService_SynchronizeSolutionAssetsAsync = 309, AssetService_SynchronizeProjectAssetsAsync = 310, CodeLens_GetReferenceCountAsync = 311, CodeLens_FindReferenceLocationsAsync = 312, CodeLens_FindReferenceMethodsAsync = 313, CodeLens_GetFullyQualifiedName = 314, SolutionState_ComputeChecksumsAsync = 315, ProjectState_ComputeChecksumsAsync = 316, DocumentState_ComputeChecksumsAsync = 317, // obsolete: SolutionSynchronizationService_GetRemotableData = 318, // obsolete: SolutionSynchronizationServiceFactory_CreatePinnedRemotableDataScopeAsync = 319, SolutionChecksumUpdater_SynchronizePrimaryWorkspace = 320, JsonRpcSession_RequestAssetAsync = 321, SolutionService_GetSolutionAsync = 322, SolutionService_UpdatePrimaryWorkspaceAsync = 323, RemoteHostService_GetAssetsAsync = 324, // obsolete: CompilationService_GetCompilationAsync = 325, SolutionCreator_AssetDifferences = 326, Extension_InfoBar = 327, FxCopAnalyzersInstall = 328, AssetStorage_ForceGC = 329, // obsolete: RemoteHost_Bitness = 330, Intellisense_Completion = 331, MetadataOnlyImage_EmitFailure = 332, LiveTableDataSource_OnDiagnosticsUpdated = 333, Experiment_KeybindingsReset = 334, Diagnostics_GeneratePerformaceReport = 335, Diagnostics_BadAnalyzer = 336, CodeAnalysisService_ReportAnalyzerPerformance = 337, PerformanceTrackerService_AddSnapshot = 338, // obsolete: AbstractProject_SetIntelliSenseBuild = 339, // obsolete: AbstractProject_Created = 340, // obsolete: AbstractProject_PushedToWorkspace = 341, ExternalErrorDiagnosticUpdateSource_AddError = 342, DiagnosticIncrementalAnalyzer_SynchronizeWithBuildAsync = 343, Completion_ExecuteCommand_TypeChar = 344, RemoteHostService_SynchronizeTextAsync = 345, SymbolFinder_Solution_Pattern_FindSourceDeclarationsAsync = 346, SymbolFinder_Project_Pattern_FindSourceDeclarationsAsync = 347, // obsolete: Intellisense_Completion_Commit = 348, CodeCleanupInfobar_BarDisplayed = 349, CodeCleanupInfobar_ConfigureNow = 350, CodeCleanupInfobar_NeverShowCodeCleanupInfoBarAgain = 351, FormatDocument = 352, CodeCleanup_ApplyCodeFixesAsync = 353, CodeCleanup_RemoveUnusedImports = 354, CodeCleanup_SortImports = 355, CodeCleanup_Format = 356, CodeCleanupABTest_AssignedToOnByDefault = 357, CodeCleanupABTest_AssignedToOffByDefault = 358, Workspace_Events = 359, Refactoring_ExtractMethod_UnknownMatrixItem = 360, SyntaxTreeIndex_Precalculate = 361, SyntaxTreeIndex_Precalculate_Create = 362, SymbolTreeInfo_Create = 363, SymbolTreeInfo_TryLoadOrCreate = 364, CommandHandler_GoToImplementation = 365, GraphQuery_ImplementedBy = 366, GraphQuery_Implements = 367, GraphQuery_IsCalledBy = 368, GraphQuery_IsUsedBy = 369, GraphQuery_Overrides = 370, Intellisense_AsyncCompletion_Data = 371, Intellisense_CompletionProviders_Data = 372, RemoteHostService_IsExperimentEnabledAsync = 373, PartialLoad_FullyLoaded = 374, Liveshare_UnknownCodeAction = 375, // obsolete: Liveshare_LexicalClassifications = 376, // obsolete: Liveshare_SyntacticClassifications = 377, // obsolete: Liveshare_SyntacticTagger = 378, CommandHandler_GoToBase = 379, DiagnosticAnalyzerService_GetDiagnosticsForSpanAsync = 380, CodeFixes_GetCodeFixesAsync = 381, LanguageServer_ActivateFailed = 382, LanguageServer_OnLoadedFailed = 383, CodeFixes_AddExplicitCast = 384, ToolsOptions_GenerateEditorconfig = 385, Renamer_RenameSymbolAsync = 386, Renamer_FindRenameLocationsAsync = 387, Renamer_ResolveConflictsAsync = 388, ChangeSignature_Data = 400, AbstractEncapsulateFieldService_EncapsulateFieldsAsync = 410, AbstractConvertTupleToStructCodeRefactoringProvider_ConvertToStructAsync = 420, DependentTypeFinder_FindAndCacheDerivedClassesAsync = 430, DependentTypeFinder_FindAndCacheDerivedInterfacesAsync = 431, DependentTypeFinder_FindAndCacheImplementingTypesAsync = 432, RemoteSemanticClassificationCacheService_ExceptionInCacheRead = 440, // obsolete: FeatureNotAvailable = 441, LSPCompletion_MissingLSPCompletionTriggerKind = 450, LSPCompletion_MissingLSPCompletionInvokeKind = 451, Workspace_Project_CompilationThrownAway = 460, CommandHandler_Paste_ImportsOnPaste = 470, // Superseded by LSP_FindDocumentInWorkspace // obsolete: FindDocumentInWorkspace = 480, RegisterWorkspace = 481, LSP_RequestCounter = 482, LSP_RequestDuration = 483, LSP_TimeInQueue = 484, Intellicode_UnknownIntent = 485, LSP_CompletionListCacheMiss = 486, InheritanceMargin_TargetsMenuOpen = 487, InheritanceMargin_NavigateToTarget = 488, VS_ErrorReportingService_ShowGlobalErrorInfo = 489, UnusedReferences_GetUnusedReferences = 490, ValueTracking_Command = 491, ValueTracking_TrackValueSource = 492, InheritanceMargin_GetInheritanceMemberItems = 493, LSP_FindDocumentInWorkspace = 494, SuggestedActions_GetSuggestedActionsAsync = 500, NavigateTo_CacheItemsMiss = 510, AssetService_Perf = 520, Inline_Hints_DoubleClick = 530, NavigateToExternalSources = 531, StackTraceToolWindow_ShowOnActivated = 540, CodeModel_FileCodeModel_Create = 550, Refactoring_FixAllOccurrencesSession = 560, Refactoring_FixAllOccurrencesContext = 561, Refactoring_FixAllOccurrencesComputation = 562, Refactoring_FixAllOccurrencesPreviewChanges = 563, LSP_UsedForkedSolution = 571, } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Portable/Binder/Binder_InterpolatedString.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { private BoundExpression BindInterpolatedString(InterpolatedStringExpressionSyntax node, BindingDiagnosticBag diagnostics) { if (CheckFeatureAvailability(node, MessageID.IDS_FeatureInterpolatedStrings, diagnostics)) { // Only bother reporting an issue for raw string literals if we didn't already report above that // interpolated strings are not allowed. if (node.StringStartToken.Kind() is SyntaxKind.InterpolatedSingleLineRawStringStartToken or SyntaxKind.InterpolatedMultiLineRawStringStartToken) { CheckFeatureAvailability(node, MessageID.IDS_FeatureRawStringLiterals, diagnostics); } } var startText = node.StringStartToken.Text; if (startText.StartsWith("@$\"") && !Compilation.IsFeatureEnabled(MessageID.IDS_FeatureAltInterpolatedVerbatimStrings)) { Error(diagnostics, ErrorCode.ERR_AltInterpolatedVerbatimStringsNotAvailable, node.StringStartToken.GetLocation(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureAltInterpolatedVerbatimStrings.RequiredVersion())); } var builder = ArrayBuilder<BoundExpression>.GetInstance(); var stringType = GetSpecialType(SpecialType.System_String, diagnostics, node); ConstantValue? resultConstant = null; bool isResultConstant = true; if (node.Contents.Count == 0) { resultConstant = ConstantValue.Create(string.Empty); } else { var isNonVerbatimInterpolatedString = node.StringStartToken.Kind() != SyntaxKind.InterpolatedVerbatimStringStartToken; var isRawInterpolatedString = node.StringStartToken.Kind() is SyntaxKind.InterpolatedSingleLineRawStringStartToken or SyntaxKind.InterpolatedMultiLineRawStringStartToken; var newLinesInInterpolationsAllowed = this.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNewLinesInInterpolations); var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, node); foreach (var content in node.Contents) { switch (content.Kind()) { case SyntaxKind.Interpolation: { var interpolation = (InterpolationSyntax)content; // If we're prior to C# 11 then we don't allow newlines in the interpolations of // non-verbatim interpolated strings. Check for that here and report an error // if the interpolation spans multiple lines (and thus must have a newline). // // Note: don't bother doing this if the interpolation is otherwise malformed or // we've already reported some other error within it. No need to spam the user // with multiple errors (esp as a malformed interpolation may commonly span multiple // lines due to error recovery). if (isNonVerbatimInterpolatedString && !interpolation.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) && !newLinesInInterpolationsAllowed && !interpolation.OpenBraceToken.IsMissing && !interpolation.CloseBraceToken.IsMissing) { var text = node.SyntaxTree.GetText(); if (text.Lines.GetLineFromPosition(interpolation.OpenBraceToken.SpanStart).LineNumber != text.Lines.GetLineFromPosition(interpolation.CloseBraceToken.SpanStart).LineNumber) { diagnostics.Add( ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, interpolation.CloseBraceToken.GetLocation(), this.Compilation.LanguageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureNewLinesInInterpolations.RequiredVersion())); } } var value = BindValue(interpolation.Expression, diagnostics, BindValueKind.RValue); // We need to ensure the argument is not a lambda, method group, etc. It isn't nice to wait until lowering, // when we perform overload resolution, to report a problem. So we do that check by calling // GenerateConversionForAssignment with objectType. However we want to preserve the original expression's // natural type so that overload resolution may select a specialized implementation of string.Format, // so we discard the result of that call and only preserve its diagnostics. BoundExpression? alignment = null; BoundLiteral? format = null; if (interpolation.AlignmentClause != null) { alignment = GenerateConversionForAssignment(intType, BindValue(interpolation.AlignmentClause.Value, diagnostics, Binder.BindValueKind.RValue), diagnostics); var alignmentConstant = alignment.ConstantValue; if (alignmentConstant != null && !alignmentConstant.IsBad) { const int magnitudeLimit = 32767; // check that the magnitude of the alignment is "in range". int alignmentValue = alignmentConstant.Int32Value; // We do the arithmetic using negative numbers because the largest negative int has no corresponding positive (absolute) value. alignmentValue = (alignmentValue > 0) ? -alignmentValue : alignmentValue; if (alignmentValue < -magnitudeLimit) { diagnostics.Add(ErrorCode.WRN_AlignmentMagnitude, alignment.Syntax.Location, alignmentConstant.Int32Value, magnitudeLimit); } } else if (!alignment.HasErrors) { diagnostics.Add(ErrorCode.ERR_ConstantExpected, interpolation.AlignmentClause.Value.Location); } } if (interpolation.FormatClause != null) { var text = interpolation.FormatClause.FormatStringToken.ValueText; char lastChar; bool hasErrors = false; if (text.Length == 0) { diagnostics.Add(ErrorCode.ERR_EmptyFormatSpecifier, interpolation.FormatClause.Location); hasErrors = true; } else if (SyntaxFacts.IsWhitespace(lastChar = text[text.Length - 1]) || SyntaxFacts.IsNewLine(lastChar)) { diagnostics.Add(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, interpolation.FormatClause.Location); hasErrors = true; } format = new BoundLiteral(interpolation.FormatClause, ConstantValue.Create(text), stringType, hasErrors); } builder.Add(new BoundStringInsert(interpolation, value, alignment, format, isInterpolatedStringHandlerAppendCall: false)); if (!isResultConstant || value.ConstantValue == null || !(interpolation is { FormatClause: null, AlignmentClause: null }) || !(value.ConstantValue is { IsString: true, IsBad: false })) { isResultConstant = false; continue; } resultConstant = (resultConstant is null) ? value.ConstantValue : FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, value.ConstantValue); continue; } case SyntaxKind.InterpolatedStringText: { var text = ((InterpolatedStringTextSyntax)content).TextToken.ValueText; // Raw string literals have no escapes. So there is no need to manipulate their value texts. // We have to unescape normal interpolated strings as the parser stores their text without // interpreting {{ and }} sequences (as '{' and '}') respectively. Changing that at the syntax // level might potentially be a breaking change, so we do the conversion here when creating the // bound nodes. if (!isRawInterpolatedString) { text = unescapeInterpolatedStringLiteral(text); } var constantValue = ConstantValue.Create(text, SpecialType.System_String); builder.Add(new BoundLiteral(content, constantValue, stringType)); if (isResultConstant) { resultConstant = resultConstant is null ? constantValue : FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, constantValue); } continue; } default: throw ExceptionUtilities.UnexpectedValue(content.Kind()); } } if (!isResultConstant) { resultConstant = null; } } Debug.Assert(isResultConstant == (resultConstant != null)); return new BoundUnconvertedInterpolatedString(node, builder.ToImmutableAndFree(), resultConstant, stringType); static string unescapeInterpolatedStringLiteral(string value) { var builder = PooledStringBuilder.GetInstance(); var stringBuilder = builder.Builder; for (int i = 0, formatLength = value.Length; i < formatLength; i++) { var c = value[i]; stringBuilder.Append(c); if (c is '{' or '}' && i + 1 < formatLength && value[i + 1] == c) { i++; } } // Avoid unnecessary allocation in the common case of no escaped curlies. var result = builder.Length == value.Length ? value : builder.Builder.ToString(); builder.Free(); return result; } } private BoundInterpolatedString BindUnconvertedInterpolatedStringToString(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) { // We have 4 possible lowering strategies, dependent on the contents of the string, in this order: // 1. The string is a constant value. We can just use the final value. // 2. The string is composed of 4 or fewer components that are all strings, we can lower to a call to string.Concat without a // params array. This is very efficient as the runtime can allocate a buffer for the string with exactly the correct length and // make no intermediate allocations. // 3. The WellKnownType DefaultInterpolatedStringHandler is available, and none of the interpolation holes contain an await expression. // The builder is a ref struct, and we can guarantee the lifetime won't outlive the stack if the string doesn't contain any // awaits, but if it does we cannot use it. This builder is the only way that ref structs can be directly used as interpolation // hole components, which means that ref structs components and await expressions cannot be combined. It is already illegal for // the user to use ref structs in an async method today, but if that were to ever change, this would still need to be respected. // We also cannot use this method if the interpolated string appears within a catch filter, as the builder is disposable and we // cannot put a try/finally inside a filter block. // 4. The string is composed of more than 4 components that are all strings themselves. We can turn this into a single // call to string.Concat. We prefer the builder over this because the builder can use pooling to avoid new allocations, while this // call will need to allocate a param array. // 5. The string has heterogeneous data and either InterpolatedStringHandler is unavailable, or one of the holes contains an await // expression. This is turned into a call to string.Format. // // We need to do the determination of 1, 2, 3, or 4/5 up front, rather than in lowering, as it affects diagnostics (ref structs not being // able to be used, for example). However, between 4 and 5, we don't need to know at this point, so that logic is deferred for lowering. if (unconvertedInterpolatedString.ConstantValue is not null) { // Case 1 Debug.Assert(unconvertedInterpolatedString.Parts.All(static part => part.Type is null or { SpecialType: SpecialType.System_String })); return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); } // Case 2. Attempt to see if all parts are strings. if (unconvertedInterpolatedString.Parts.Length <= 4 && AllInterpolatedStringPartsAreStrings(unconvertedInterpolatedString.Parts)) { return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); } if (tryBindAsHandlerType(out var result)) { // Case 3 return result; } // The specifics of 4 vs 5 aren't necessary for this stage of binding. The only thing that matters is that every part needs to be convertible // object. return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); BoundInterpolatedString constructWithData(ImmutableArray<BoundExpression> parts, InterpolatedStringHandlerData? data) => new BoundInterpolatedString( unconvertedInterpolatedString.Syntax, data, parts, unconvertedInterpolatedString.ConstantValue, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); bool tryBindAsHandlerType([NotNullWhen(true)] out BoundInterpolatedString? result) { result = null; if (InExpressionTree || !InterpolatedStringPartsAreValidInDefaultHandler(unconvertedInterpolatedString)) { return false; } var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler); if (interpolatedStringHandlerType is MissingMetadataTypeSymbol) { return false; } result = BindUnconvertedInterpolatedStringToHandlerType(unconvertedInterpolatedString, interpolatedStringHandlerType, diagnostics, isHandlerConversion: false); return true; } } private static bool InterpolatedStringPartsAreValidInDefaultHandler(BoundUnconvertedInterpolatedString unconvertedInterpolatedString) => !unconvertedInterpolatedString.Parts.ContainsAwaitExpression() && unconvertedInterpolatedString.Parts.All(p => p is not BoundStringInsert { Value.Type.TypeKind: TypeKind.Dynamic }); private static bool AllInterpolatedStringPartsAreStrings(ImmutableArray<BoundExpression> parts) => parts.All(p => p is BoundLiteral or BoundStringInsert { Value.Type.SpecialType: SpecialType.System_String, Alignment: null, Format: null }); private bool TryBindUnconvertedBinaryOperatorToDefaultInterpolatedStringHandler(BoundBinaryOperator binaryOperator, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out BoundBinaryOperator? convertedBinaryOperator) { // Much like BindUnconvertedInterpolatedStringToString above, we only want to use DefaultInterpolatedStringHandler if it's worth it. We therefore // check for cases 1 and 2: if they are present, we let normal string binary operator binding machinery handle it. Otherwise, we take care of it ourselves. Debug.Assert(binaryOperator.IsUnconvertedInterpolatedStringAddition); convertedBinaryOperator = null; if (InExpressionTree) { return false; } var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler); if (interpolatedStringHandlerType.IsErrorType()) { // Can't ever bind to the handler no matter what, so just let the default handling take care of it. Cases 4 and 5 are covered by this. return false; } // The constant value is folded as part of creating the unconverted operator. If there is a constant value, then the top-level binary operator // will have one. if (binaryOperator.ConstantValue is not null) { // This is case 1. Let the standard machinery handle it return false; } var partsArrayBuilder = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(); if (!binaryOperator.VisitBinaryOperatorInterpolatedString( partsArrayBuilder, static (BoundUnconvertedInterpolatedString unconvertedInterpolatedString, ArrayBuilder<ImmutableArray<BoundExpression>> partsArrayBuilder) => { if (!InterpolatedStringPartsAreValidInDefaultHandler(unconvertedInterpolatedString)) { return false; } partsArrayBuilder.Add(unconvertedInterpolatedString.Parts); return true; })) { partsArrayBuilder.Free(); return false; } Debug.Assert(partsArrayBuilder.Count >= 2); if (partsArrayBuilder.Count <= 4 && partsArrayBuilder.All(static parts => AllInterpolatedStringPartsAreStrings(parts))) { // This is case 2. Let the standard machinery handle it partsArrayBuilder.Free(); return false; } // Case 3. Bind as handler. var (appendCalls, data) = BindUnconvertedInterpolatedPartsToHandlerType( binaryOperator.Syntax, partsArrayBuilder.ToImmutableAndFree(), interpolatedStringHandlerType, diagnostics, isHandlerConversion: false, additionalConstructorArguments: default, additionalConstructorRefKinds: default); // Now that the parts have been bound, reconstruct the binary operators. convertedBinaryOperator = UpdateBinaryOperatorWithInterpolatedContents(binaryOperator, appendCalls, data, binaryOperator.Syntax, diagnostics); return true; } private BoundBinaryOperator UpdateBinaryOperatorWithInterpolatedContents(BoundBinaryOperator originalOperator, ImmutableArray<ImmutableArray<BoundExpression>> appendCalls, InterpolatedStringHandlerData data, SyntaxNode rootSyntax, BindingDiagnosticBag diagnostics) { var @string = GetSpecialType(SpecialType.System_String, diagnostics, rootSyntax); Func<BoundUnconvertedInterpolatedString, int, (ImmutableArray<ImmutableArray<BoundExpression>>, TypeSymbol), BoundExpression> interpolationFactory = createInterpolation; Func<BoundBinaryOperator, BoundExpression, BoundExpression, (ImmutableArray<ImmutableArray<BoundExpression>>, TypeSymbol), BoundExpression> binaryOperatorFactory = createBinaryOperator; var rewritten = (BoundBinaryOperator)originalOperator.RewriteInterpolatedStringAddition((appendCalls, @string), interpolationFactory, binaryOperatorFactory); return rewritten.Update(BoundBinaryOperator.UncommonData.InterpolatedStringHandlerAddition(data)); static BoundInterpolatedString createInterpolation(BoundUnconvertedInterpolatedString expression, int i, (ImmutableArray<ImmutableArray<BoundExpression>> AppendCalls, TypeSymbol _) arg) { Debug.Assert(arg.AppendCalls.Length > i); return new BoundInterpolatedString( expression.Syntax, interpolationData: null, arg.AppendCalls[i], expression.ConstantValue, expression.Type, expression.HasErrors); } static BoundBinaryOperator createBinaryOperator(BoundBinaryOperator original, BoundExpression left, BoundExpression right, (ImmutableArray<ImmutableArray<BoundExpression>> _, TypeSymbol @string) arg) => new BoundBinaryOperator( original.Syntax, BinaryOperatorKind.StringConcatenation, left, right, original.ConstantValue, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, originalUserDefinedOperatorsOpt: default, arg.@string, original.HasErrors); } private BoundExpression BindUnconvertedInterpolatedExpressionToHandlerType( BoundExpression unconvertedExpression, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default, ImmutableArray<RefKind> additionalConstructorRefKinds = default) => unconvertedExpression switch { BoundUnconvertedInterpolatedString interpolatedString => BindUnconvertedInterpolatedStringToHandlerType( interpolatedString, interpolatedStringHandlerType, diagnostics, isHandlerConversion: true, additionalConstructorArguments, additionalConstructorRefKinds), BoundBinaryOperator binary => BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType(binary, interpolatedStringHandlerType, diagnostics, additionalConstructorArguments, additionalConstructorRefKinds), _ => throw ExceptionUtilities.UnexpectedValue(unconvertedExpression.Kind) }; private BoundInterpolatedString BindUnconvertedInterpolatedStringToHandlerType( BoundUnconvertedInterpolatedString unconvertedInterpolatedString, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, bool isHandlerConversion, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default, ImmutableArray<RefKind> additionalConstructorRefKinds = default) { var (appendCalls, interpolationData) = BindUnconvertedInterpolatedPartsToHandlerType( unconvertedInterpolatedString.Syntax, ImmutableArray.Create(unconvertedInterpolatedString.Parts), interpolatedStringHandlerType, diagnostics, isHandlerConversion, additionalConstructorArguments, additionalConstructorRefKinds); Debug.Assert(appendCalls.Length == 1); return new BoundInterpolatedString( unconvertedInterpolatedString.Syntax, interpolationData, appendCalls[0], unconvertedInterpolatedString.ConstantValue, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); } private BoundBinaryOperator BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType( BoundBinaryOperator binaryOperator, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, ImmutableArray<RefKind> additionalConstructorRefKinds) { Debug.Assert(binaryOperator.IsUnconvertedInterpolatedStringAddition); var partsArrayBuilder = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(); binaryOperator.VisitBinaryOperatorInterpolatedString(partsArrayBuilder, static (BoundUnconvertedInterpolatedString unconvertedInterpolatedString, ArrayBuilder<ImmutableArray<BoundExpression>> partsArrayBuilder) => { partsArrayBuilder.Add(unconvertedInterpolatedString.Parts); return true; }); var (appendCalls, data) = BindUnconvertedInterpolatedPartsToHandlerType( binaryOperator.Syntax, partsArrayBuilder.ToImmutableAndFree(), interpolatedStringHandlerType, diagnostics, isHandlerConversion: true, additionalConstructorArguments, additionalConstructorRefKinds); var result = UpdateBinaryOperatorWithInterpolatedContents(binaryOperator, appendCalls, data, binaryOperator.Syntax, diagnostics); return result; } private (ImmutableArray<ImmutableArray<BoundExpression>> AppendCalls, InterpolatedStringHandlerData Data) BindUnconvertedInterpolatedPartsToHandlerType( SyntaxNode syntax, ImmutableArray<ImmutableArray<BoundExpression>> partsArray, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, bool isHandlerConversion, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, ImmutableArray<RefKind> additionalConstructorRefKinds) { Debug.Assert(additionalConstructorArguments.IsDefault ? additionalConstructorRefKinds.IsDefault : additionalConstructorArguments.Length == additionalConstructorRefKinds.Length); additionalConstructorArguments = additionalConstructorArguments.NullToEmpty(); additionalConstructorRefKinds = additionalConstructorRefKinds.NullToEmpty(); ReportUseSite(interpolatedStringHandlerType, diagnostics, syntax); // We satisfy the conditions for using an interpolated string builder. Bind all the builder calls unconditionally, so that if // there are errors we get better diagnostics than "could not convert to object." var implicitBuilderReceiver = new BoundInterpolatedStringHandlerPlaceholder(syntax, interpolatedStringHandlerType) { WasCompilerGenerated = true }; var (appendCallsArray, usesBoolReturn, positionInfo, baseStringLength, numFormatHoles) = BindInterpolatedStringAppendCalls(partsArray, implicitBuilderReceiver, diagnostics); // Prior to C# 10, all types in an interpolated string expression needed to be convertible to `object`. After 10, some types // (such as Span<T>) that are not convertible to `object` are permissible as interpolated string components, provided there // is an applicable AppendFormatted method that accepts them. To preserve langversion, we therefore make sure all components // are convertible to object if the current langversion is lower than the interpolation feature and we're converting this // interpolation into an actual string. bool needToCheckConversionToObject = false; if (isHandlerConversion) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); } else if (!Compilation.IsFeatureEnabled(MessageID.IDS_FeatureImprovedInterpolatedStrings) && diagnostics.AccumulatesDiagnostics) { needToCheckConversionToObject = true; } Debug.Assert(appendCallsArray.Select(a => a.Length).SequenceEqual(partsArray.Select(a => a.Length))); Debug.Assert(appendCallsArray.All(appendCalls => appendCalls.All(a => a is { HasErrors: true } or BoundCall { Arguments: { Length: > 0 } } or BoundDynamicInvocation))); if (needToCheckConversionToObject) { TypeSymbol objectType = GetSpecialType(SpecialType.System_Object, diagnostics, syntax); BindingDiagnosticBag conversionDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); foreach (var parts in partsArray) { foreach (var currentPart in parts) { if (currentPart is BoundStringInsert insert) { var value = insert.Value; bool reported = false; if (value.Type is not null) { value = BindToNaturalType(value, conversionDiagnostics); if (conversionDiagnostics.HasAnyErrors()) { CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); reported = true; } } if (!reported) { _ = GenerateConversionForAssignment(objectType, value, conversionDiagnostics); if (conversionDiagnostics.HasAnyErrors()) { CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); } } conversionDiagnostics.Clear(); } } } conversionDiagnostics.Free(); } var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, syntax); int constructorArgumentLength = 3 + additionalConstructorArguments.Length; var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(constructorArgumentLength); var refKindsBuilder = ArrayBuilder<RefKind>.GetInstance(constructorArgumentLength); refKindsBuilder.Add(RefKind.None); refKindsBuilder.Add(RefKind.None); refKindsBuilder.AddRange(additionalConstructorRefKinds); // Add the trailing out validity parameter for the first attempt.Note that we intentionally use `diagnostics` for resolving System.Boolean, // because we want to track that we're using the type no matter what. var boolType = GetSpecialType(SpecialType.System_Boolean, diagnostics, syntax); var trailingConstructorValidityPlaceholder = new BoundInterpolatedStringArgumentPlaceholder(syntax, BoundInterpolatedStringArgumentPlaceholder.TrailingConstructorValidityParameter, valSafeToEscape: LocalScopeDepth, boolType) { WasCompilerGenerated = true }; var outConstructorAdditionalArguments = additionalConstructorArguments.Add(trailingConstructorValidityPlaceholder); refKindsBuilder.Add(RefKind.Out); populateArguments(syntax, outConstructorAdditionalArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder); BoundExpression constructorCall; var outConstructorDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: diagnostics.AccumulatesDependencies); var outConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, syntax, outConstructorDiagnostics); if (outConstructorCall is not BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable }) { // MakeConstructorInvocation can call CoerceArguments on the builder if overload resolution succeeded ignoring accessibility, which // could still end up not succeeding, and that would end up changing the arguments. So we want to clear and repopulate. argumentsBuilder.Clear(); // Try again without an out parameter. populateArguments(syntax, additionalConstructorArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder); refKindsBuilder.RemoveLast(); var nonOutConstructorDiagnostics = BindingDiagnosticBag.GetInstance(template: outConstructorDiagnostics); BoundExpression nonOutConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, syntax, nonOutConstructorDiagnostics); if (nonOutConstructorCall is BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable }) { // We successfully bound the out version, so set all the final data based on that binding constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); outConstructorDiagnostics.Free(); } else { // We'll attempt to figure out which failure was "best" by looking to see if one failed to bind because it couldn't find // a constructor with the correct number of arguments. We presume that, if one failed for this reason and the other failed // for a different reason, that different reason is the one the user will want to know about. If both or neither failed // because of this error, we'll report everything. // https://github.com/dotnet/roslyn/issues/54396 Instead of inspecting errors, we should be capturing the results of overload // resolution and attempting to determine which method considered was the best to report errors for. var nonOutConstructorHasArityError = nonOutConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false; var outConstructorHasArityError = outConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false; switch ((nonOutConstructorHasArityError, outConstructorHasArityError)) { case (true, false): constructorCall = outConstructorCall; additionalConstructorArguments = outConstructorAdditionalArguments; diagnostics.AddRangeAndFree(outConstructorDiagnostics); nonOutConstructorDiagnostics.Free(); break; case (false, true): constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); outConstructorDiagnostics.Free(); break; default: // For the final output binding info, we'll go with the shorter constructor in the absence of any tiebreaker, // but we'll report all diagnostics constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); diagnostics.AddRangeAndFree(outConstructorDiagnostics); break; } } } else { diagnostics.AddRangeAndFree(outConstructorDiagnostics); constructorCall = outConstructorCall; additionalConstructorArguments = outConstructorAdditionalArguments; } argumentsBuilder.Free(); refKindsBuilder.Free(); Debug.Assert(constructorCall.HasErrors || constructorCall is BoundObjectCreationExpression or BoundDynamicObjectCreationExpression); if (constructorCall is BoundDynamicObjectCreationExpression) { // An interpolated string handler construction cannot use dynamic. Manually construct an instance of '{0}'. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, syntax.Location, interpolatedStringHandlerType.Name); } var interpolationData = new InterpolatedStringHandlerData( interpolatedStringHandlerType, constructorCall, usesBoolReturn, LocalScopeDepth, additionalConstructorArguments.NullToEmpty(), positionInfo, implicitBuilderReceiver); return (appendCallsArray, interpolationData); static void populateArguments(SyntaxNode syntax, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, int baseStringLength, int numFormatHoles, NamedTypeSymbol intType, ArrayBuilder<BoundExpression> argumentsBuilder) { // literalLength argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(baseStringLength), intType) { WasCompilerGenerated = true }); // formattedCount argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(numFormatHoles), intType) { WasCompilerGenerated = true }); // Any other arguments from the call site argumentsBuilder.AddRange(additionalConstructorArguments); } } private ImmutableArray<BoundExpression> BindInterpolatedStringParts(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) { ArrayBuilder<BoundExpression>? partsBuilder = null; var objectType = GetSpecialType(SpecialType.System_Object, diagnostics, unconvertedInterpolatedString.Syntax); for (int i = 0; i < unconvertedInterpolatedString.Parts.Length; i++) { var part = unconvertedInterpolatedString.Parts[i]; if (part is BoundStringInsert insert) { BoundExpression newValue; if (insert.Value.Type is null) { newValue = GenerateConversionForAssignment(objectType, insert.Value, diagnostics); } else { newValue = BindToNaturalType(insert.Value, diagnostics); _ = GenerateConversionForAssignment(objectType, insert.Value, diagnostics); } if (insert.Value != newValue) { if (partsBuilder is null) { partsBuilder = ArrayBuilder<BoundExpression>.GetInstance(unconvertedInterpolatedString.Parts.Length); partsBuilder.AddRange(unconvertedInterpolatedString.Parts, i); } partsBuilder.Add(insert.Update(newValue, insert.Alignment, insert.Format, isInterpolatedStringHandlerAppendCall: false)); } else { partsBuilder?.Add(part); } } else { Debug.Assert(part is BoundLiteral { Type: { SpecialType: SpecialType.System_String } }); partsBuilder?.Add(part); } } return partsBuilder?.ToImmutableAndFree() ?? unconvertedInterpolatedString.Parts; } private (ImmutableArray<ImmutableArray<BoundExpression>> AppendFormatCalls, bool UsesBoolReturn, ImmutableArray<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>, int BaseStringLength, int NumFormatHoles) BindInterpolatedStringAppendCalls( ImmutableArray<ImmutableArray<BoundExpression>> partsArray, BoundInterpolatedStringHandlerPlaceholder implicitBuilderReceiver, BindingDiagnosticBag diagnostics) { if (partsArray.IsEmpty && partsArray.All(p => p.IsEmpty)) { return (ImmutableArray<ImmutableArray<BoundExpression>>.Empty, false, ImmutableArray<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>.Empty, 0, 0); } bool? builderPatternExpectsBool = null; var firstPartsLength = partsArray[0].Length; var builderAppendCallsArray = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(partsArray.Length); var builderAppendCalls = ArrayBuilder<BoundExpression>.GetInstance(firstPartsLength); var positionInfoArray = ArrayBuilder<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>.GetInstance(partsArray.Length); var positionInfo = ArrayBuilder<(bool IsLiteral, bool HasAlignment, bool HasFormat)>.GetInstance(firstPartsLength); var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(3); var parameterNamesAndLocationsBuilder = ArrayBuilder<(string, Location)?>.GetInstance(3); int baseStringLength = 0; int numFormatHoles = 0; foreach (var parts in partsArray) { foreach (var part in parts) { Debug.Assert(part is BoundLiteral or BoundStringInsert); string methodName; bool isLiteral; bool hasAlignment; bool hasFormat; if (part is BoundStringInsert insert) { methodName = BoundInterpolatedString.AppendFormattedMethod; argumentsBuilder.Add(insert.Value); parameterNamesAndLocationsBuilder.Add(null); isLiteral = false; hasAlignment = false; hasFormat = false; if (insert.Alignment is not null) { hasAlignment = true; argumentsBuilder.Add(insert.Alignment); parameterNamesAndLocationsBuilder.Add(("alignment", insert.Alignment.Syntax.Location)); } if (insert.Format is not null) { hasFormat = true; argumentsBuilder.Add(insert.Format); parameterNamesAndLocationsBuilder.Add(("format", insert.Format.Syntax.Location)); } numFormatHoles++; } else { var boundLiteral = (BoundLiteral)part; Debug.Assert(boundLiteral.ConstantValue != null && boundLiteral.ConstantValue.IsString); var literalText = boundLiteral.ConstantValue.StringValue; methodName = BoundInterpolatedString.AppendLiteralMethod; argumentsBuilder.Add(boundLiteral.Update(ConstantValue.Create(literalText), boundLiteral.Type)); isLiteral = true; hasAlignment = false; hasFormat = false; baseStringLength += literalText.Length; } var arguments = argumentsBuilder.ToImmutableAndClear(); ImmutableArray<(string, Location)?> parameterNamesAndLocations; if (parameterNamesAndLocationsBuilder.Count > 1) { parameterNamesAndLocations = parameterNamesAndLocationsBuilder.ToImmutableAndClear(); } else { Debug.Assert(parameterNamesAndLocationsBuilder.Count == 0 || parameterNamesAndLocationsBuilder[0] == null); parameterNamesAndLocations = default; parameterNamesAndLocationsBuilder.Clear(); } var call = MakeInvocationExpression(part.Syntax, implicitBuilderReceiver, methodName, arguments, diagnostics, names: parameterNamesAndLocations, searchExtensionMethodsIfNecessary: false); builderAppendCalls.Add(call); positionInfo.Add((isLiteral, hasAlignment, hasFormat)); Debug.Assert(call is BoundCall or BoundDynamicInvocation or { HasErrors: true }); // We just assume that dynamic is going to do the right thing, and runtime will fail if it does not. If there are only dynamic calls, we assume that // void is returned. if (call is BoundCall { Method: { ReturnType: var returnType } method }) { bool methodReturnsBool = returnType.SpecialType == SpecialType.System_Boolean; if (!methodReturnsBool && returnType.SpecialType != SpecialType.System_Void) { // Interpolated string handler method '{0}' is malformed. It does not return 'void' or 'bool'. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, part.Syntax.Location, method); } else if (builderPatternExpectsBool == null) { builderPatternExpectsBool = methodReturnsBool; } else if (builderPatternExpectsBool != methodReturnsBool) { // Interpolated string handler method '{0}' has inconsistent return types. Expected to return '{1}'. var expected = builderPatternExpectsBool == true ? Compilation.GetSpecialType(SpecialType.System_Boolean) : Compilation.GetSpecialType(SpecialType.System_Void); diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, part.Syntax.Location, method, expected); } } } builderAppendCallsArray.Add(builderAppendCalls.ToImmutableAndClear()); positionInfoArray.Add(positionInfo.ToImmutableAndClear()); } argumentsBuilder.Free(); parameterNamesAndLocationsBuilder.Free(); builderAppendCalls.Free(); positionInfo.Free(); return (builderAppendCallsArray.ToImmutableAndFree(), builderPatternExpectsBool ?? false, positionInfoArray.ToImmutableAndFree(), baseStringLength, numFormatHoles); } private BoundExpression BindInterpolatedStringHandlerInMemberCall( BoundExpression unconvertedString, ArrayBuilder<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parameters, ref MemberAnalysisResult memberAnalysisResult, int interpolatedStringArgNum, BoundExpression? receiver, bool requiresInstanceReceiver, BindingDiagnosticBag diagnostics) { Debug.Assert(unconvertedString is BoundUnconvertedInterpolatedString or BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: true }); var interpolatedStringConversion = memberAnalysisResult.ConversionForArg(interpolatedStringArgNum); Debug.Assert(interpolatedStringConversion.IsInterpolatedStringHandler); var interpolatedStringParameter = GetCorrespondingParameter(ref memberAnalysisResult, parameters, interpolatedStringArgNum); Debug.Assert(interpolatedStringParameter is { Type: NamedTypeSymbol { IsInterpolatedStringHandlerType: true } } #pragma warning disable format or { IsParams: true, Type: ArrayTypeSymbol { ElementType: NamedTypeSymbol { IsInterpolatedStringHandlerType: true } }, InterpolatedStringHandlerArgumentIndexes.IsEmpty: true }); #pragma warning restore format Debug.Assert(!interpolatedStringParameter.IsParams || memberAnalysisResult.Kind == MemberResolutionKind.ApplicableInExpandedForm); if (interpolatedStringParameter.HasInterpolatedStringHandlerArgumentError) { // The InterpolatedStringHandlerArgumentAttribute applied to parameter '{0}' is malformed and cannot be interpreted. Construct an instance of '{1}' manually. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, unconvertedString.Syntax.Location, interpolatedStringParameter, interpolatedStringParameter.Type); return CreateConversion( unconvertedString.Syntax, unconvertedString, interpolatedStringConversion, isCast: false, conversionGroupOpt: null, wasCompilerGenerated: false, interpolatedStringParameter.Type, diagnostics, hasErrors: true); } var handlerParameterIndexes = interpolatedStringParameter.InterpolatedStringHandlerArgumentIndexes; if (handlerParameterIndexes.IsEmpty) { // No arguments, fall back to the standard conversion steps. return CreateConversion( unconvertedString.Syntax, unconvertedString, interpolatedStringConversion, isCast: false, conversionGroupOpt: null, interpolatedStringParameter.IsParams ? ((ArrayTypeSymbol)interpolatedStringParameter.Type).ElementType : interpolatedStringParameter.Type, diagnostics); } Debug.Assert(handlerParameterIndexes.All((index, paramLength) => index >= BoundInterpolatedStringArgumentPlaceholder.InstanceParameter && index < paramLength, parameters.Length)); // We need to find the appropriate argument expression for every expected parameter, and error on any that occur after the current parameter ImmutableArray<int> handlerArgumentIndexes; if (memberAnalysisResult.ArgsToParamsOpt.IsDefault && arguments.Count == parameters.Length) { // No parameters are missing and no remapped indexes, we can just use the original indexes handlerArgumentIndexes = handlerParameterIndexes; } else { // Args and parameters were reordered via named parameters, or parameters are missing. Find the correct argument index for each parameter. var handlerArgumentIndexesBuilder = ArrayBuilder<int>.GetInstance(handlerParameterIndexes.Length, fillWithValue: BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter); for (int handlerParameterIndex = 0; handlerParameterIndex < handlerParameterIndexes.Length; handlerParameterIndex++) { int handlerParameter = handlerParameterIndexes[handlerParameterIndex]; Debug.Assert(handlerArgumentIndexesBuilder[handlerParameterIndex] is BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter); if (handlerParameter == BoundInterpolatedStringArgumentPlaceholder.InstanceParameter) { handlerArgumentIndexesBuilder[handlerParameterIndex] = handlerParameter; continue; } for (int argumentIndex = 0; argumentIndex < arguments.Count; argumentIndex++) { // The index in the original parameter list we're looking to match up. int argumentParameterIndex = memberAnalysisResult.ParameterFromArgument(argumentIndex); // Is the original parameter index of the current argument the parameter index that was specified in the attribute? if (argumentParameterIndex == handlerParameter) { // We can't just bail out on the first match: users can duplicate parameters in attributes, causing the same value to be passed twice. handlerArgumentIndexesBuilder[handlerParameterIndex] = argumentIndex; } } } handlerArgumentIndexes = handlerArgumentIndexesBuilder.ToImmutableAndFree(); } var argumentPlaceholdersBuilder = ArrayBuilder<BoundInterpolatedStringArgumentPlaceholder>.GetInstance(handlerArgumentIndexes.Length); var argumentRefKindsBuilder = ArrayBuilder<RefKind>.GetInstance(handlerArgumentIndexes.Length); bool hasErrors = false; // Now, go through all the specified arguments and see if any were specified _after_ the interpolated string, and construct // a set of placeholders for overload resolution. for (int i = 0; i < handlerArgumentIndexes.Length; i++) { int argumentIndex = handlerArgumentIndexes[i]; Debug.Assert(argumentIndex != interpolatedStringArgNum); RefKind refKind; TypeSymbol placeholderType; switch (argumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: Debug.Assert(receiver!.Type is not null); refKind = RefKind.None; placeholderType = receiver.Type; break; case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: { // Don't error if the parameter isn't optional or params: the user will already have an error for missing an optional parameter or overload resolution failed. // If it is optional, then they could otherwise not specify the parameter and that's an error var originalParameterIndex = handlerParameterIndexes[i]; var parameter = parameters[originalParameterIndex]; if (parameter.IsOptional || (originalParameterIndex + 1 == parameters.Length && OverloadResolution.IsValidParamsParameter(parameter))) { // Parameter '{0}' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter '{1}'. Specify the value of '{0}' before '{1}'. diagnostics.Add( ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, unconvertedString.Syntax.Location, parameter.Name, interpolatedStringParameter.Name); hasErrors = true; } refKind = parameter.RefKind; placeholderType = parameter.Type; } break; default: { var originalParameterIndex = handlerParameterIndexes[i]; var parameter = parameters[originalParameterIndex]; if (argumentIndex > interpolatedStringArgNum) { // Parameter '{0}' is an argument to the interpolated string handler conversion on parameter '{1}', but the corresponding argument is specified after the interpolated string expression. Reorder the arguments to move '{0}' before '{1}'. diagnostics.Add( ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, arguments[argumentIndex].Syntax.Location, parameter.Name, interpolatedStringParameter.Name); hasErrors = true; } refKind = parameter.RefKind; placeholderType = parameter.Type; } break; } SyntaxNode placeholderSyntax; uint valSafeToEscapeScope; bool isSuppressed; switch (argumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: Debug.Assert(receiver != null); valSafeToEscapeScope = requiresInstanceReceiver ? receiver.GetRefKind().IsWritableReference() == true ? GetRefEscape(receiver, LocalScopeDepth) : GetValEscape(receiver, LocalScopeDepth) : Binder.ExternalScope; isSuppressed = receiver.IsSuppressed; placeholderSyntax = receiver.Syntax; break; case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: placeholderSyntax = unconvertedString.Syntax; valSafeToEscapeScope = Binder.ExternalScope; isSuppressed = false; break; case >= 0: placeholderSyntax = arguments[argumentIndex].Syntax; valSafeToEscapeScope = GetValEscape(arguments[argumentIndex], LocalScopeDepth); isSuppressed = arguments[argumentIndex].IsSuppressed; break; default: throw ExceptionUtilities.UnexpectedValue(argumentIndex); } argumentPlaceholdersBuilder.Add( (BoundInterpolatedStringArgumentPlaceholder)(new BoundInterpolatedStringArgumentPlaceholder( placeholderSyntax, argumentIndex, valSafeToEscapeScope, placeholderType, hasErrors: argumentIndex == BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter) { WasCompilerGenerated = true }.WithSuppression(isSuppressed))); // We use the parameter refkind, rather than what the argument was actually passed with, because that will suppress duplicated errors // about arguments being passed with the wrong RefKind. The user will have already gotten an error about mismatched RefKinds or it will // be a place where refkinds are allowed to differ argumentRefKindsBuilder.Add(refKind); } var interpolatedString = BindUnconvertedInterpolatedExpressionToHandlerType( unconvertedString, (NamedTypeSymbol)interpolatedStringParameter.Type, diagnostics, additionalConstructorArguments: argumentPlaceholdersBuilder.ToImmutableAndFree(), additionalConstructorRefKinds: argumentRefKindsBuilder.ToImmutableAndFree()); return new BoundConversion( interpolatedString.Syntax, interpolatedString, interpolatedStringConversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, interpolatedStringParameter.Type, hasErrors || interpolatedString.HasErrors); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { private BoundExpression BindInterpolatedString(InterpolatedStringExpressionSyntax node, BindingDiagnosticBag diagnostics) { if (CheckFeatureAvailability(node, MessageID.IDS_FeatureInterpolatedStrings, diagnostics)) { // Only bother reporting an issue for raw string literals if we didn't already report above that // interpolated strings are not allowed. if (node.StringStartToken.Kind() is SyntaxKind.InterpolatedSingleLineRawStringStartToken or SyntaxKind.InterpolatedMultiLineRawStringStartToken) { CheckFeatureAvailability(node, MessageID.IDS_FeatureRawStringLiterals, diagnostics); } } var startText = node.StringStartToken.Text; if (startText.StartsWith("@$\"") && !Compilation.IsFeatureEnabled(MessageID.IDS_FeatureAltInterpolatedVerbatimStrings)) { Error(diagnostics, ErrorCode.ERR_AltInterpolatedVerbatimStringsNotAvailable, node.StringStartToken.GetLocation(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureAltInterpolatedVerbatimStrings.RequiredVersion())); } var builder = ArrayBuilder<BoundExpression>.GetInstance(); var stringType = GetSpecialType(SpecialType.System_String, diagnostics, node); ConstantValue? resultConstant = null; bool isResultConstant = true; if (node.Contents.Count == 0) { resultConstant = ConstantValue.Create(string.Empty); } else { var isNonVerbatimInterpolatedString = node.StringStartToken.Kind() != SyntaxKind.InterpolatedVerbatimStringStartToken; var isRawInterpolatedString = node.StringStartToken.Kind() is SyntaxKind.InterpolatedSingleLineRawStringStartToken or SyntaxKind.InterpolatedMultiLineRawStringStartToken; var newLinesInInterpolationsAllowed = this.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNewLinesInInterpolations); var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, node); foreach (var content in node.Contents) { switch (content.Kind()) { case SyntaxKind.Interpolation: { var interpolation = (InterpolationSyntax)content; // If we're prior to C# 11 then we don't allow newlines in the interpolations of // non-verbatim interpolated strings. Check for that here and report an error // if the interpolation spans multiple lines (and thus must have a newline). // // Note: don't bother doing this if the interpolation is otherwise malformed or // we've already reported some other error within it. No need to spam the user // with multiple errors (esp as a malformed interpolation may commonly span multiple // lines due to error recovery). if (isNonVerbatimInterpolatedString && !interpolation.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) && !newLinesInInterpolationsAllowed && !interpolation.OpenBraceToken.IsMissing && !interpolation.CloseBraceToken.IsMissing) { var text = node.SyntaxTree.GetText(); if (text.Lines.GetLineFromPosition(interpolation.OpenBraceToken.SpanStart).LineNumber != text.Lines.GetLineFromPosition(interpolation.CloseBraceToken.SpanStart).LineNumber) { diagnostics.Add( ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, interpolation.CloseBraceToken.GetLocation(), this.Compilation.LanguageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureNewLinesInInterpolations.RequiredVersion())); } } var value = BindValue(interpolation.Expression, diagnostics, BindValueKind.RValue); // We need to ensure the argument is not a lambda, method group, etc. It isn't nice to wait until lowering, // when we perform overload resolution, to report a problem. So we do that check by calling // GenerateConversionForAssignment with objectType. However we want to preserve the original expression's // natural type so that overload resolution may select a specialized implementation of string.Format, // so we discard the result of that call and only preserve its diagnostics. BoundExpression? alignment = null; BoundLiteral? format = null; if (interpolation.AlignmentClause != null) { alignment = GenerateConversionForAssignment(intType, BindValue(interpolation.AlignmentClause.Value, diagnostics, Binder.BindValueKind.RValue), diagnostics); var alignmentConstant = alignment.ConstantValue; if (alignmentConstant != null && !alignmentConstant.IsBad) { const int magnitudeLimit = 32767; // check that the magnitude of the alignment is "in range". int alignmentValue = alignmentConstant.Int32Value; // We do the arithmetic using negative numbers because the largest negative int has no corresponding positive (absolute) value. alignmentValue = (alignmentValue > 0) ? -alignmentValue : alignmentValue; if (alignmentValue < -magnitudeLimit) { diagnostics.Add(ErrorCode.WRN_AlignmentMagnitude, alignment.Syntax.Location, alignmentConstant.Int32Value, magnitudeLimit); } } else if (!alignment.HasErrors) { diagnostics.Add(ErrorCode.ERR_ConstantExpected, interpolation.AlignmentClause.Value.Location); } } if (interpolation.FormatClause != null) { var text = interpolation.FormatClause.FormatStringToken.ValueText; char lastChar; bool hasErrors = false; if (text.Length == 0) { diagnostics.Add(ErrorCode.ERR_EmptyFormatSpecifier, interpolation.FormatClause.Location); hasErrors = true; } else if (SyntaxFacts.IsWhitespace(lastChar = text[text.Length - 1]) || SyntaxFacts.IsNewLine(lastChar)) { diagnostics.Add(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, interpolation.FormatClause.Location); hasErrors = true; } format = new BoundLiteral(interpolation.FormatClause, ConstantValue.Create(text), stringType, hasErrors); } builder.Add(new BoundStringInsert(interpolation, value, alignment, format, isInterpolatedStringHandlerAppendCall: false)); if (!isResultConstant || value.ConstantValue == null || !(interpolation is { FormatClause: null, AlignmentClause: null }) || !(value.ConstantValue is { IsString: true, IsBad: false })) { isResultConstant = false; continue; } resultConstant = (resultConstant is null) ? value.ConstantValue : FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, value.ConstantValue); continue; } case SyntaxKind.InterpolatedStringText: { var text = ((InterpolatedStringTextSyntax)content).TextToken.ValueText; // Raw string literals have no escapes. So there is no need to manipulate their value texts. // We have to unescape normal interpolated strings as the parser stores their text without // interpreting {{ and }} sequences (as '{' and '}') respectively. Changing that at the syntax // level might potentially be a breaking change, so we do the conversion here when creating the // bound nodes. if (!isRawInterpolatedString) { text = unescapeInterpolatedStringLiteral(text); } var constantValue = ConstantValue.Create(text, SpecialType.System_String); builder.Add(new BoundLiteral(content, constantValue, stringType)); if (isResultConstant) { resultConstant = resultConstant is null ? constantValue : FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, constantValue); } continue; } default: throw ExceptionUtilities.UnexpectedValue(content.Kind()); } } if (!isResultConstant) { resultConstant = null; } } Debug.Assert(isResultConstant == (resultConstant != null)); return new BoundUnconvertedInterpolatedString(node, builder.ToImmutableAndFree(), resultConstant, stringType); static string unescapeInterpolatedStringLiteral(string value) { var builder = PooledStringBuilder.GetInstance(); var stringBuilder = builder.Builder; for (int i = 0, formatLength = value.Length; i < formatLength; i++) { var c = value[i]; stringBuilder.Append(c); if (c is '{' or '}' && i + 1 < formatLength && value[i + 1] == c) { i++; } } // Avoid unnecessary allocation in the common case of no escaped curlies. var result = builder.Length == value.Length ? value : builder.Builder.ToString(); builder.Free(); return result; } } private BoundInterpolatedString BindUnconvertedInterpolatedStringToString(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) { // We have 4 possible lowering strategies, dependent on the contents of the string, in this order: // 1. The string is a constant value. We can just use the final value. // 2. The string is composed of 4 or fewer components that are all strings, we can lower to a call to string.Concat without a // params array. This is very efficient as the runtime can allocate a buffer for the string with exactly the correct length and // make no intermediate allocations. // 3. The WellKnownType DefaultInterpolatedStringHandler is available, and none of the interpolation holes contain an await expression. // The builder is a ref struct, and we can guarantee the lifetime won't outlive the stack if the string doesn't contain any // awaits, but if it does we cannot use it. This builder is the only way that ref structs can be directly used as interpolation // hole components, which means that ref structs components and await expressions cannot be combined. It is already illegal for // the user to use ref structs in an async method today, but if that were to ever change, this would still need to be respected. // We also cannot use this method if the interpolated string appears within a catch filter, as the builder is disposable and we // cannot put a try/finally inside a filter block. // 4. The string is composed of more than 4 components that are all strings themselves. We can turn this into a single // call to string.Concat. We prefer the builder over this because the builder can use pooling to avoid new allocations, while this // call will need to allocate a param array. // 5. The string has heterogeneous data and either InterpolatedStringHandler is unavailable, or one of the holes contains an await // expression. This is turned into a call to string.Format. // // We need to do the determination of 1, 2, 3, or 4/5 up front, rather than in lowering, as it affects diagnostics (ref structs not being // able to be used, for example). However, between 4 and 5, we don't need to know at this point, so that logic is deferred for lowering. if (unconvertedInterpolatedString.ConstantValue is not null) { // Case 1 Debug.Assert(unconvertedInterpolatedString.Parts.All(static part => part.Type is null or { SpecialType: SpecialType.System_String })); return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); } // Case 2. Attempt to see if all parts are strings. if (unconvertedInterpolatedString.Parts.Length <= 4 && AllInterpolatedStringPartsAreStrings(unconvertedInterpolatedString.Parts)) { return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); } if (tryBindAsHandlerType(out var result)) { // Case 3 return result; } // The specifics of 4 vs 5 aren't necessary for this stage of binding. The only thing that matters is that every part needs to be convertible // object. return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); BoundInterpolatedString constructWithData(ImmutableArray<BoundExpression> parts, InterpolatedStringHandlerData? data) => new BoundInterpolatedString( unconvertedInterpolatedString.Syntax, data, parts, unconvertedInterpolatedString.ConstantValue, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); bool tryBindAsHandlerType([NotNullWhen(true)] out BoundInterpolatedString? result) { result = null; if (InExpressionTree || !InterpolatedStringPartsAreValidInDefaultHandler(unconvertedInterpolatedString)) { return false; } var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler); if (interpolatedStringHandlerType is MissingMetadataTypeSymbol) { return false; } result = BindUnconvertedInterpolatedStringToHandlerType(unconvertedInterpolatedString, interpolatedStringHandlerType, diagnostics, isHandlerConversion: false); return true; } } private static bool InterpolatedStringPartsAreValidInDefaultHandler(BoundUnconvertedInterpolatedString unconvertedInterpolatedString) => !unconvertedInterpolatedString.Parts.ContainsAwaitExpression() && unconvertedInterpolatedString.Parts.All(p => p is not BoundStringInsert { Value.Type.TypeKind: TypeKind.Dynamic }); private static bool AllInterpolatedStringPartsAreStrings(ImmutableArray<BoundExpression> parts) => parts.All(p => p is BoundLiteral or BoundStringInsert { Value.Type.SpecialType: SpecialType.System_String, Alignment: null, Format: null }); private bool TryBindUnconvertedBinaryOperatorToDefaultInterpolatedStringHandler(BoundBinaryOperator binaryOperator, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out BoundBinaryOperator? convertedBinaryOperator) { // Much like BindUnconvertedInterpolatedStringToString above, we only want to use DefaultInterpolatedStringHandler if it's worth it. We therefore // check for cases 1 and 2: if they are present, we let normal string binary operator binding machinery handle it. Otherwise, we take care of it ourselves. Debug.Assert(binaryOperator.IsUnconvertedInterpolatedStringAddition); convertedBinaryOperator = null; if (InExpressionTree) { return false; } var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler); if (interpolatedStringHandlerType.IsErrorType()) { // Can't ever bind to the handler no matter what, so just let the default handling take care of it. Cases 4 and 5 are covered by this. return false; } // The constant value is folded as part of creating the unconverted operator. If there is a constant value, then the top-level binary operator // will have one. if (binaryOperator.ConstantValue is not null) { // This is case 1. Let the standard machinery handle it return false; } var partsArrayBuilder = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(); if (!binaryOperator.VisitBinaryOperatorInterpolatedString( partsArrayBuilder, static (BoundUnconvertedInterpolatedString unconvertedInterpolatedString, ArrayBuilder<ImmutableArray<BoundExpression>> partsArrayBuilder) => { if (!InterpolatedStringPartsAreValidInDefaultHandler(unconvertedInterpolatedString)) { return false; } partsArrayBuilder.Add(unconvertedInterpolatedString.Parts); return true; })) { partsArrayBuilder.Free(); return false; } Debug.Assert(partsArrayBuilder.Count >= 2); if (partsArrayBuilder.Count <= 4 && partsArrayBuilder.All(static parts => AllInterpolatedStringPartsAreStrings(parts))) { // This is case 2. Let the standard machinery handle it partsArrayBuilder.Free(); return false; } // Case 3. Bind as handler. var (appendCalls, data) = BindUnconvertedInterpolatedPartsToHandlerType( binaryOperator.Syntax, partsArrayBuilder.ToImmutableAndFree(), interpolatedStringHandlerType, diagnostics, isHandlerConversion: false, additionalConstructorArguments: default, additionalConstructorRefKinds: default); // Now that the parts have been bound, reconstruct the binary operators. convertedBinaryOperator = UpdateBinaryOperatorWithInterpolatedContents(binaryOperator, appendCalls, data, binaryOperator.Syntax, diagnostics); return true; } private BoundBinaryOperator UpdateBinaryOperatorWithInterpolatedContents(BoundBinaryOperator originalOperator, ImmutableArray<ImmutableArray<BoundExpression>> appendCalls, InterpolatedStringHandlerData data, SyntaxNode rootSyntax, BindingDiagnosticBag diagnostics) { var @string = GetSpecialType(SpecialType.System_String, diagnostics, rootSyntax); Func<BoundUnconvertedInterpolatedString, int, (ImmutableArray<ImmutableArray<BoundExpression>>, TypeSymbol), BoundExpression> interpolationFactory = createInterpolation; Func<BoundBinaryOperator, BoundExpression, BoundExpression, (ImmutableArray<ImmutableArray<BoundExpression>>, TypeSymbol), BoundExpression> binaryOperatorFactory = createBinaryOperator; var rewritten = (BoundBinaryOperator)originalOperator.RewriteInterpolatedStringAddition((appendCalls, @string), interpolationFactory, binaryOperatorFactory); return rewritten.Update(BoundBinaryOperator.UncommonData.InterpolatedStringHandlerAddition(data)); static BoundInterpolatedString createInterpolation(BoundUnconvertedInterpolatedString expression, int i, (ImmutableArray<ImmutableArray<BoundExpression>> AppendCalls, TypeSymbol _) arg) { Debug.Assert(arg.AppendCalls.Length > i); return new BoundInterpolatedString( expression.Syntax, interpolationData: null, arg.AppendCalls[i], expression.ConstantValue, expression.Type, expression.HasErrors); } static BoundBinaryOperator createBinaryOperator(BoundBinaryOperator original, BoundExpression left, BoundExpression right, (ImmutableArray<ImmutableArray<BoundExpression>> _, TypeSymbol @string) arg) => new BoundBinaryOperator( original.Syntax, BinaryOperatorKind.StringConcatenation, left, right, original.ConstantValue, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, originalUserDefinedOperatorsOpt: default, arg.@string, original.HasErrors); } private BoundExpression BindUnconvertedInterpolatedExpressionToHandlerType( BoundExpression unconvertedExpression, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default, ImmutableArray<RefKind> additionalConstructorRefKinds = default) => unconvertedExpression switch { BoundUnconvertedInterpolatedString interpolatedString => BindUnconvertedInterpolatedStringToHandlerType( interpolatedString, interpolatedStringHandlerType, diagnostics, isHandlerConversion: true, additionalConstructorArguments, additionalConstructorRefKinds), BoundBinaryOperator binary => BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType(binary, interpolatedStringHandlerType, diagnostics, additionalConstructorArguments, additionalConstructorRefKinds), _ => throw ExceptionUtilities.UnexpectedValue(unconvertedExpression.Kind) }; private BoundInterpolatedString BindUnconvertedInterpolatedStringToHandlerType( BoundUnconvertedInterpolatedString unconvertedInterpolatedString, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, bool isHandlerConversion, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default, ImmutableArray<RefKind> additionalConstructorRefKinds = default) { var (appendCalls, interpolationData) = BindUnconvertedInterpolatedPartsToHandlerType( unconvertedInterpolatedString.Syntax, ImmutableArray.Create(unconvertedInterpolatedString.Parts), interpolatedStringHandlerType, diagnostics, isHandlerConversion, additionalConstructorArguments, additionalConstructorRefKinds); Debug.Assert(appendCalls.Length == 1); return new BoundInterpolatedString( unconvertedInterpolatedString.Syntax, interpolationData, appendCalls[0], unconvertedInterpolatedString.ConstantValue, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); } private BoundBinaryOperator BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType( BoundBinaryOperator binaryOperator, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, ImmutableArray<RefKind> additionalConstructorRefKinds) { Debug.Assert(binaryOperator.IsUnconvertedInterpolatedStringAddition); var partsArrayBuilder = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(); binaryOperator.VisitBinaryOperatorInterpolatedString(partsArrayBuilder, static (BoundUnconvertedInterpolatedString unconvertedInterpolatedString, ArrayBuilder<ImmutableArray<BoundExpression>> partsArrayBuilder) => { partsArrayBuilder.Add(unconvertedInterpolatedString.Parts); return true; }); var (appendCalls, data) = BindUnconvertedInterpolatedPartsToHandlerType( binaryOperator.Syntax, partsArrayBuilder.ToImmutableAndFree(), interpolatedStringHandlerType, diagnostics, isHandlerConversion: true, additionalConstructorArguments, additionalConstructorRefKinds); var result = UpdateBinaryOperatorWithInterpolatedContents(binaryOperator, appendCalls, data, binaryOperator.Syntax, diagnostics); return result; } private (ImmutableArray<ImmutableArray<BoundExpression>> AppendCalls, InterpolatedStringHandlerData Data) BindUnconvertedInterpolatedPartsToHandlerType( SyntaxNode syntax, ImmutableArray<ImmutableArray<BoundExpression>> partsArray, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, bool isHandlerConversion, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, ImmutableArray<RefKind> additionalConstructorRefKinds) { Debug.Assert(additionalConstructorArguments.IsDefault ? additionalConstructorRefKinds.IsDefault : additionalConstructorArguments.Length == additionalConstructorRefKinds.Length); additionalConstructorArguments = additionalConstructorArguments.NullToEmpty(); additionalConstructorRefKinds = additionalConstructorRefKinds.NullToEmpty(); ReportUseSite(interpolatedStringHandlerType, diagnostics, syntax); // We satisfy the conditions for using an interpolated string builder. Bind all the builder calls unconditionally, so that if // there are errors we get better diagnostics than "could not convert to object." var implicitBuilderReceiver = new BoundInterpolatedStringHandlerPlaceholder(syntax, interpolatedStringHandlerType) { WasCompilerGenerated = true }; var (appendCallsArray, usesBoolReturn, positionInfo, baseStringLength, numFormatHoles) = BindInterpolatedStringAppendCalls(partsArray, implicitBuilderReceiver, diagnostics); // Prior to C# 10, all types in an interpolated string expression needed to be convertible to `object`. After 10, some types // (such as Span<T>) that are not convertible to `object` are permissible as interpolated string components, provided there // is an applicable AppendFormatted method that accepts them. To preserve langversion, we therefore make sure all components // are convertible to object if the current langversion is lower than the interpolation feature and we're converting this // interpolation into an actual string. bool needToCheckConversionToObject = false; if (isHandlerConversion) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); } else if (!Compilation.IsFeatureEnabled(MessageID.IDS_FeatureImprovedInterpolatedStrings) && diagnostics.AccumulatesDiagnostics) { needToCheckConversionToObject = true; } Debug.Assert(appendCallsArray.Select(a => a.Length).SequenceEqual(partsArray.Select(a => a.Length))); Debug.Assert(appendCallsArray.All(appendCalls => appendCalls.All(a => a is { HasErrors: true } or BoundCall { Arguments: { Length: > 0 } } or BoundDynamicInvocation))); if (needToCheckConversionToObject) { TypeSymbol objectType = GetSpecialType(SpecialType.System_Object, diagnostics, syntax); BindingDiagnosticBag conversionDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); foreach (var parts in partsArray) { foreach (var currentPart in parts) { if (currentPart is BoundStringInsert insert) { var value = insert.Value; bool reported = false; if (value.Type is not null) { value = BindToNaturalType(value, conversionDiagnostics); if (conversionDiagnostics.HasAnyErrors()) { CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); reported = true; } } if (!reported) { _ = GenerateConversionForAssignment(objectType, value, conversionDiagnostics); if (conversionDiagnostics.HasAnyErrors()) { CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); } } conversionDiagnostics.Clear(); } } } conversionDiagnostics.Free(); } var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, syntax); int constructorArgumentLength = 3 + additionalConstructorArguments.Length; var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(constructorArgumentLength); var refKindsBuilder = ArrayBuilder<RefKind>.GetInstance(constructorArgumentLength); refKindsBuilder.Add(RefKind.None); refKindsBuilder.Add(RefKind.None); refKindsBuilder.AddRange(additionalConstructorRefKinds); // Add the trailing out validity parameter for the first attempt.Note that we intentionally use `diagnostics` for resolving System.Boolean, // because we want to track that we're using the type no matter what. var boolType = GetSpecialType(SpecialType.System_Boolean, diagnostics, syntax); var trailingConstructorValidityPlaceholder = new BoundInterpolatedStringArgumentPlaceholder(syntax, BoundInterpolatedStringArgumentPlaceholder.TrailingConstructorValidityParameter, valSafeToEscape: LocalScopeDepth, boolType) { WasCompilerGenerated = true }; var outConstructorAdditionalArguments = additionalConstructorArguments.Add(trailingConstructorValidityPlaceholder); refKindsBuilder.Add(RefKind.Out); populateArguments(syntax, outConstructorAdditionalArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder); BoundExpression constructorCall; var outConstructorDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: diagnostics.AccumulatesDependencies); var outConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, syntax, outConstructorDiagnostics); if (outConstructorCall is not BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable }) { // MakeConstructorInvocation can call CoerceArguments on the builder if overload resolution succeeded ignoring accessibility, which // could still end up not succeeding, and that would end up changing the arguments. So we want to clear and repopulate. argumentsBuilder.Clear(); // Try again without an out parameter. populateArguments(syntax, additionalConstructorArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder); refKindsBuilder.RemoveLast(); var nonOutConstructorDiagnostics = BindingDiagnosticBag.GetInstance(template: outConstructorDiagnostics); BoundExpression nonOutConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, syntax, nonOutConstructorDiagnostics); if (nonOutConstructorCall is BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable }) { // We successfully bound the out version, so set all the final data based on that binding constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); outConstructorDiagnostics.Free(); } else { // We'll attempt to figure out which failure was "best" by looking to see if one failed to bind because it couldn't find // a constructor with the correct number of arguments. We presume that, if one failed for this reason and the other failed // for a different reason, that different reason is the one the user will want to know about. If both or neither failed // because of this error, we'll report everything. // https://github.com/dotnet/roslyn/issues/54396 Instead of inspecting errors, we should be capturing the results of overload // resolution and attempting to determine which method considered was the best to report errors for. var nonOutConstructorHasArityError = nonOutConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false; var outConstructorHasArityError = outConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false; switch ((nonOutConstructorHasArityError, outConstructorHasArityError)) { case (true, false): constructorCall = outConstructorCall; additionalConstructorArguments = outConstructorAdditionalArguments; diagnostics.AddRangeAndFree(outConstructorDiagnostics); nonOutConstructorDiagnostics.Free(); break; case (false, true): constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); outConstructorDiagnostics.Free(); break; default: // For the final output binding info, we'll go with the shorter constructor in the absence of any tiebreaker, // but we'll report all diagnostics constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); diagnostics.AddRangeAndFree(outConstructorDiagnostics); break; } } } else { diagnostics.AddRangeAndFree(outConstructorDiagnostics); constructorCall = outConstructorCall; additionalConstructorArguments = outConstructorAdditionalArguments; } argumentsBuilder.Free(); refKindsBuilder.Free(); Debug.Assert(constructorCall.HasErrors || constructorCall is BoundObjectCreationExpression or BoundDynamicObjectCreationExpression); if (constructorCall is BoundDynamicObjectCreationExpression) { // An interpolated string handler construction cannot use dynamic. Manually construct an instance of '{0}'. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, syntax.Location, interpolatedStringHandlerType.Name); } var interpolationData = new InterpolatedStringHandlerData( interpolatedStringHandlerType, constructorCall, usesBoolReturn, LocalScopeDepth, additionalConstructorArguments.NullToEmpty(), positionInfo, implicitBuilderReceiver); return (appendCallsArray, interpolationData); static void populateArguments(SyntaxNode syntax, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, int baseStringLength, int numFormatHoles, NamedTypeSymbol intType, ArrayBuilder<BoundExpression> argumentsBuilder) { // literalLength argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(baseStringLength), intType) { WasCompilerGenerated = true }); // formattedCount argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(numFormatHoles), intType) { WasCompilerGenerated = true }); // Any other arguments from the call site argumentsBuilder.AddRange(additionalConstructorArguments); } } private ImmutableArray<BoundExpression> BindInterpolatedStringParts(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) { ArrayBuilder<BoundExpression>? partsBuilder = null; var objectType = GetSpecialType(SpecialType.System_Object, diagnostics, unconvertedInterpolatedString.Syntax); for (int i = 0; i < unconvertedInterpolatedString.Parts.Length; i++) { var part = unconvertedInterpolatedString.Parts[i]; if (part is BoundStringInsert insert) { BoundExpression newValue; if (insert.Value.Type is null) { newValue = GenerateConversionForAssignment(objectType, insert.Value, diagnostics); } else { newValue = BindToNaturalType(insert.Value, diagnostics); _ = GenerateConversionForAssignment(objectType, insert.Value, diagnostics); } if (insert.Value != newValue) { if (partsBuilder is null) { partsBuilder = ArrayBuilder<BoundExpression>.GetInstance(unconvertedInterpolatedString.Parts.Length); partsBuilder.AddRange(unconvertedInterpolatedString.Parts, i); } partsBuilder.Add(insert.Update(newValue, insert.Alignment, insert.Format, isInterpolatedStringHandlerAppendCall: false)); } else { partsBuilder?.Add(part); } } else { Debug.Assert(part is BoundLiteral { Type: { SpecialType: SpecialType.System_String } }); partsBuilder?.Add(part); } } return partsBuilder?.ToImmutableAndFree() ?? unconvertedInterpolatedString.Parts; } private (ImmutableArray<ImmutableArray<BoundExpression>> AppendFormatCalls, bool UsesBoolReturn, ImmutableArray<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>, int BaseStringLength, int NumFormatHoles) BindInterpolatedStringAppendCalls( ImmutableArray<ImmutableArray<BoundExpression>> partsArray, BoundInterpolatedStringHandlerPlaceholder implicitBuilderReceiver, BindingDiagnosticBag diagnostics) { if (partsArray.IsEmpty && partsArray.All(p => p.IsEmpty)) { return (ImmutableArray<ImmutableArray<BoundExpression>>.Empty, false, ImmutableArray<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>.Empty, 0, 0); } bool? builderPatternExpectsBool = null; var firstPartsLength = partsArray[0].Length; var builderAppendCallsArray = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(partsArray.Length); var builderAppendCalls = ArrayBuilder<BoundExpression>.GetInstance(firstPartsLength); var positionInfoArray = ArrayBuilder<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>.GetInstance(partsArray.Length); var positionInfo = ArrayBuilder<(bool IsLiteral, bool HasAlignment, bool HasFormat)>.GetInstance(firstPartsLength); var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(3); var parameterNamesAndLocationsBuilder = ArrayBuilder<(string, Location)?>.GetInstance(3); int baseStringLength = 0; int numFormatHoles = 0; foreach (var parts in partsArray) { foreach (var part in parts) { Debug.Assert(part is BoundLiteral or BoundStringInsert); string methodName; bool isLiteral; bool hasAlignment; bool hasFormat; if (part is BoundStringInsert insert) { methodName = BoundInterpolatedString.AppendFormattedMethod; argumentsBuilder.Add(insert.Value); parameterNamesAndLocationsBuilder.Add(null); isLiteral = false; hasAlignment = false; hasFormat = false; if (insert.Alignment is not null) { hasAlignment = true; argumentsBuilder.Add(insert.Alignment); parameterNamesAndLocationsBuilder.Add(("alignment", insert.Alignment.Syntax.Location)); } if (insert.Format is not null) { hasFormat = true; argumentsBuilder.Add(insert.Format); parameterNamesAndLocationsBuilder.Add(("format", insert.Format.Syntax.Location)); } numFormatHoles++; } else { var boundLiteral = (BoundLiteral)part; Debug.Assert(boundLiteral.ConstantValue != null && boundLiteral.ConstantValue.IsString); var literalText = boundLiteral.ConstantValue.StringValue; methodName = BoundInterpolatedString.AppendLiteralMethod; argumentsBuilder.Add(boundLiteral.Update(ConstantValue.Create(literalText), boundLiteral.Type)); isLiteral = true; hasAlignment = false; hasFormat = false; baseStringLength += literalText.Length; } var arguments = argumentsBuilder.ToImmutableAndClear(); ImmutableArray<(string, Location)?> parameterNamesAndLocations; if (parameterNamesAndLocationsBuilder.Count > 1) { parameterNamesAndLocations = parameterNamesAndLocationsBuilder.ToImmutableAndClear(); } else { Debug.Assert(parameterNamesAndLocationsBuilder.Count == 0 || parameterNamesAndLocationsBuilder[0] == null); parameterNamesAndLocations = default; parameterNamesAndLocationsBuilder.Clear(); } var call = MakeInvocationExpression(part.Syntax, implicitBuilderReceiver, methodName, arguments, diagnostics, names: parameterNamesAndLocations, searchExtensionMethodsIfNecessary: false); builderAppendCalls.Add(call); positionInfo.Add((isLiteral, hasAlignment, hasFormat)); Debug.Assert(call is BoundCall or BoundDynamicInvocation or { HasErrors: true }); // We just assume that dynamic is going to do the right thing, and runtime will fail if it does not. If there are only dynamic calls, we assume that // void is returned. if (call is BoundCall { Method: { ReturnType: var returnType } method }) { bool methodReturnsBool = returnType.SpecialType == SpecialType.System_Boolean; if (!methodReturnsBool && returnType.SpecialType != SpecialType.System_Void) { // Interpolated string handler method '{0}' is malformed. It does not return 'void' or 'bool'. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, part.Syntax.Location, method); } else if (builderPatternExpectsBool == null) { builderPatternExpectsBool = methodReturnsBool; } else if (builderPatternExpectsBool != methodReturnsBool) { // Interpolated string handler method '{0}' has inconsistent return types. Expected to return '{1}'. var expected = builderPatternExpectsBool == true ? Compilation.GetSpecialType(SpecialType.System_Boolean) : Compilation.GetSpecialType(SpecialType.System_Void); diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, part.Syntax.Location, method, expected); } } } builderAppendCallsArray.Add(builderAppendCalls.ToImmutableAndClear()); positionInfoArray.Add(positionInfo.ToImmutableAndClear()); } argumentsBuilder.Free(); parameterNamesAndLocationsBuilder.Free(); builderAppendCalls.Free(); positionInfo.Free(); return (builderAppendCallsArray.ToImmutableAndFree(), builderPatternExpectsBool ?? false, positionInfoArray.ToImmutableAndFree(), baseStringLength, numFormatHoles); } private BoundExpression BindInterpolatedStringHandlerInMemberCall( BoundExpression unconvertedString, ArrayBuilder<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parameters, ref MemberAnalysisResult memberAnalysisResult, int interpolatedStringArgNum, BoundExpression? receiver, bool requiresInstanceReceiver, BindingDiagnosticBag diagnostics) { Debug.Assert(unconvertedString is BoundUnconvertedInterpolatedString or BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: true }); var interpolatedStringConversion = memberAnalysisResult.ConversionForArg(interpolatedStringArgNum); Debug.Assert(interpolatedStringConversion.IsInterpolatedStringHandler); var interpolatedStringParameter = GetCorrespondingParameter(ref memberAnalysisResult, parameters, interpolatedStringArgNum); Debug.Assert(interpolatedStringParameter is { Type: NamedTypeSymbol { IsInterpolatedStringHandlerType: true } } #pragma warning disable format or { IsParams: true, Type: ArrayTypeSymbol { ElementType: NamedTypeSymbol { IsInterpolatedStringHandlerType: true } }, InterpolatedStringHandlerArgumentIndexes.IsEmpty: true }); #pragma warning restore format Debug.Assert(!interpolatedStringParameter.IsParams || memberAnalysisResult.Kind == MemberResolutionKind.ApplicableInExpandedForm); if (interpolatedStringParameter.HasInterpolatedStringHandlerArgumentError) { // The InterpolatedStringHandlerArgumentAttribute applied to parameter '{0}' is malformed and cannot be interpreted. Construct an instance of '{1}' manually. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, unconvertedString.Syntax.Location, interpolatedStringParameter, interpolatedStringParameter.Type); return CreateConversion( unconvertedString.Syntax, unconvertedString, interpolatedStringConversion, isCast: false, conversionGroupOpt: null, wasCompilerGenerated: false, interpolatedStringParameter.Type, diagnostics, hasErrors: true); } var handlerParameterIndexes = interpolatedStringParameter.InterpolatedStringHandlerArgumentIndexes; if (handlerParameterIndexes.IsEmpty) { // No arguments, fall back to the standard conversion steps. return CreateConversion( unconvertedString.Syntax, unconvertedString, interpolatedStringConversion, isCast: false, conversionGroupOpt: null, interpolatedStringParameter.IsParams ? ((ArrayTypeSymbol)interpolatedStringParameter.Type).ElementType : interpolatedStringParameter.Type, diagnostics); } Debug.Assert(handlerParameterIndexes.All((index, paramLength) => index >= BoundInterpolatedStringArgumentPlaceholder.InstanceParameter && index < paramLength, parameters.Length)); // We need to find the appropriate argument expression for every expected parameter, and error on any that occur after the current parameter ImmutableArray<int> handlerArgumentIndexes; if (memberAnalysisResult.ArgsToParamsOpt.IsDefault && arguments.Count == parameters.Length) { // No parameters are missing and no remapped indexes, we can just use the original indexes handlerArgumentIndexes = handlerParameterIndexes; } else { // Args and parameters were reordered via named parameters, or parameters are missing. Find the correct argument index for each parameter. var handlerArgumentIndexesBuilder = ArrayBuilder<int>.GetInstance(handlerParameterIndexes.Length, fillWithValue: BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter); for (int handlerParameterIndex = 0; handlerParameterIndex < handlerParameterIndexes.Length; handlerParameterIndex++) { int handlerParameter = handlerParameterIndexes[handlerParameterIndex]; Debug.Assert(handlerArgumentIndexesBuilder[handlerParameterIndex] is BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter); if (handlerParameter == BoundInterpolatedStringArgumentPlaceholder.InstanceParameter) { handlerArgumentIndexesBuilder[handlerParameterIndex] = handlerParameter; continue; } for (int argumentIndex = 0; argumentIndex < arguments.Count; argumentIndex++) { // The index in the original parameter list we're looking to match up. int argumentParameterIndex = memberAnalysisResult.ParameterFromArgument(argumentIndex); // Is the original parameter index of the current argument the parameter index that was specified in the attribute? if (argumentParameterIndex == handlerParameter) { // We can't just bail out on the first match: users can duplicate parameters in attributes, causing the same value to be passed twice. handlerArgumentIndexesBuilder[handlerParameterIndex] = argumentIndex; } } } handlerArgumentIndexes = handlerArgumentIndexesBuilder.ToImmutableAndFree(); } var argumentPlaceholdersBuilder = ArrayBuilder<BoundInterpolatedStringArgumentPlaceholder>.GetInstance(handlerArgumentIndexes.Length); var argumentRefKindsBuilder = ArrayBuilder<RefKind>.GetInstance(handlerArgumentIndexes.Length); bool hasErrors = false; // Now, go through all the specified arguments and see if any were specified _after_ the interpolated string, and construct // a set of placeholders for overload resolution. for (int i = 0; i < handlerArgumentIndexes.Length; i++) { int argumentIndex = handlerArgumentIndexes[i]; Debug.Assert(argumentIndex != interpolatedStringArgNum); RefKind refKind; TypeSymbol placeholderType; switch (argumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: Debug.Assert(receiver!.Type is not null); refKind = RefKind.None; placeholderType = receiver.Type; break; case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: { // Don't error if the parameter isn't optional or params: the user will already have an error for missing an optional parameter or overload resolution failed. // If it is optional, then they could otherwise not specify the parameter and that's an error var originalParameterIndex = handlerParameterIndexes[i]; var parameter = parameters[originalParameterIndex]; if (parameter.IsOptional || (originalParameterIndex + 1 == parameters.Length && OverloadResolution.IsValidParamsParameter(parameter))) { // Parameter '{0}' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter '{1}'. Specify the value of '{0}' before '{1}'. diagnostics.Add( ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, unconvertedString.Syntax.Location, parameter.Name, interpolatedStringParameter.Name); hasErrors = true; } refKind = parameter.RefKind; placeholderType = parameter.Type; } break; default: { var originalParameterIndex = handlerParameterIndexes[i]; var parameter = parameters[originalParameterIndex]; if (argumentIndex > interpolatedStringArgNum) { // Parameter '{0}' is an argument to the interpolated string handler conversion on parameter '{1}', but the corresponding argument is specified after the interpolated string expression. Reorder the arguments to move '{0}' before '{1}'. diagnostics.Add( ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, arguments[argumentIndex].Syntax.Location, parameter.Name, interpolatedStringParameter.Name); hasErrors = true; } refKind = parameter.RefKind; placeholderType = parameter.Type; } break; } SyntaxNode placeholderSyntax; uint valSafeToEscapeScope; bool isSuppressed; switch (argumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: Debug.Assert(receiver != null); valSafeToEscapeScope = requiresInstanceReceiver ? receiver.GetRefKind().IsWritableReference() == true ? GetRefEscape(receiver, LocalScopeDepth) : GetValEscape(receiver, LocalScopeDepth) : Binder.ExternalScope; isSuppressed = receiver.IsSuppressed; placeholderSyntax = receiver.Syntax; break; case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: placeholderSyntax = unconvertedString.Syntax; valSafeToEscapeScope = Binder.ExternalScope; isSuppressed = false; break; case >= 0: placeholderSyntax = arguments[argumentIndex].Syntax; valSafeToEscapeScope = GetValEscape(arguments[argumentIndex], LocalScopeDepth); isSuppressed = arguments[argumentIndex].IsSuppressed; break; default: throw ExceptionUtilities.UnexpectedValue(argumentIndex); } argumentPlaceholdersBuilder.Add( (BoundInterpolatedStringArgumentPlaceholder)(new BoundInterpolatedStringArgumentPlaceholder( placeholderSyntax, argumentIndex, valSafeToEscapeScope, placeholderType, hasErrors: argumentIndex == BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter) { WasCompilerGenerated = true }.WithSuppression(isSuppressed))); // We use the parameter refkind, rather than what the argument was actually passed with, because that will suppress duplicated errors // about arguments being passed with the wrong RefKind. The user will have already gotten an error about mismatched RefKinds or it will // be a place where refkinds are allowed to differ argumentRefKindsBuilder.Add(refKind); } var interpolatedString = BindUnconvertedInterpolatedExpressionToHandlerType( unconvertedString, (NamedTypeSymbol)interpolatedStringParameter.Type, diagnostics, additionalConstructorArguments: argumentPlaceholdersBuilder.ToImmutableAndFree(), additionalConstructorRefKinds: argumentRefKindsBuilder.ToImmutableAndFree()); return new BoundConversion( interpolatedString.Syntax, interpolatedString, interpolatedStringConversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, interpolatedStringParameter.Type, hasErrors || interpolatedString.HasErrors); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/CSharpTest/ImplementAbstractClass/ImplementAbstractClassTests_FixAllTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.ImplementAbstractClass; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementAbstractClass { public partial class ImplementAbstractClassTests { #region "Fix all occurrences tests" [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F1(); } public interface I1 { void F2(); } class {|FixAllInDocument:B1|} : A1 { class C1 : A1, I1 { } } </Document> <Document> class B2 : A1 { class C2 : A1, I1 { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class B3 : A1 { class C3 : A1, I1 { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F1(); } public interface I1 { void F2(); } class B1 : A1 { public override void F1() { throw new System.NotImplementedException(); } class C1 : A1, I1 { public override void F1() { throw new System.NotImplementedException(); } } } </Document> <Document> class B2 : A1 { class C2 : A1, I1 { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class B3 : A1 { class C3 : A1, I1 { } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F1(); } public interface I1 { void F2(); } class {|FixAllInProject:B1|} : A1 { class C1 : A1, I1 { } } </Document> <Document> class B2 : A1 { class C2 : A1, I1 { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class B3 : A1 { class C3 : A1, I1 { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F1(); } public interface I1 { void F2(); } class B1 : A1 { public override void F1() { throw new System.NotImplementedException(); } class C1 : A1, I1 { public override void F1() { throw new System.NotImplementedException(); } } } </Document> <Document> class B2 : A1 { public override void F1() { throw new System.NotImplementedException(); } class C2 : A1, I1 { public override void F1() { throw new System.NotImplementedException(); } } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class B3 : A1 { class C3 : A1, I1 { } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F1(); } public interface I1 { void F2(); } class {|FixAllInSolution:B1|} : A1 { class C1 : A1, I1 { } } </Document> <Document> class B2 : A1 { class C2 : A1, I1 { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <ProjectReference>Assembly1</ProjectReference> <Document> class B3 : A1 { class C3 : A1, I1 { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F1(); } public interface I1 { void F2(); } class B1 : A1 { public override void F1() { throw new System.NotImplementedException(); } class C1 : A1, I1 { public override void F1() { throw new System.NotImplementedException(); } } } </Document> <Document> class B2 : A1 { public override void F1() { throw new System.NotImplementedException(); } class C2 : A1, I1 { public override void F1() { throw new System.NotImplementedException(); } } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <ProjectReference>Assembly1</ProjectReference> <Document> class B3 : A1 { public override void F1() { throw new System.NotImplementedException(); } class C3 : A1, I1 { public override void F1() { throw new System.NotImplementedException(); } } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_DifferentAssemblyWithSameTypeName() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F1(); } public interface I1 { void F2(); } class {|FixAllInSolution:B1|} : A1 { class C1 : A1, I1 { } } </Document> <Document> class B2 : A1 { class C2 : A1, I1 { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F2(); } class B3 : A1 { class C3 : A1, I1 { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F1(); } public interface I1 { void F2(); } class B1 : A1 { public override void F1() { throw new System.NotImplementedException(); } class C1 : A1, I1 { public override void F1() { throw new System.NotImplementedException(); } } } </Document> <Document> class B2 : A1 { public override void F1() { throw new System.NotImplementedException(); } class C2 : A1, I1 { public override void F1() { throw new System.NotImplementedException(); } } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F2(); } class B3 : A1 { class C3 : A1, I1 { } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.ImplementAbstractClass; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementAbstractClass { public partial class ImplementAbstractClassTests { #region "Fix all occurrences tests" [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F1(); } public interface I1 { void F2(); } class {|FixAllInDocument:B1|} : A1 { class C1 : A1, I1 { } } </Document> <Document> class B2 : A1 { class C2 : A1, I1 { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class B3 : A1 { class C3 : A1, I1 { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F1(); } public interface I1 { void F2(); } class B1 : A1 { public override void F1() { throw new System.NotImplementedException(); } class C1 : A1, I1 { public override void F1() { throw new System.NotImplementedException(); } } } </Document> <Document> class B2 : A1 { class C2 : A1, I1 { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class B3 : A1 { class C3 : A1, I1 { } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F1(); } public interface I1 { void F2(); } class {|FixAllInProject:B1|} : A1 { class C1 : A1, I1 { } } </Document> <Document> class B2 : A1 { class C2 : A1, I1 { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class B3 : A1 { class C3 : A1, I1 { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F1(); } public interface I1 { void F2(); } class B1 : A1 { public override void F1() { throw new System.NotImplementedException(); } class C1 : A1, I1 { public override void F1() { throw new System.NotImplementedException(); } } } </Document> <Document> class B2 : A1 { public override void F1() { throw new System.NotImplementedException(); } class C2 : A1, I1 { public override void F1() { throw new System.NotImplementedException(); } } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class B3 : A1 { class C3 : A1, I1 { } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F1(); } public interface I1 { void F2(); } class {|FixAllInSolution:B1|} : A1 { class C1 : A1, I1 { } } </Document> <Document> class B2 : A1 { class C2 : A1, I1 { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <ProjectReference>Assembly1</ProjectReference> <Document> class B3 : A1 { class C3 : A1, I1 { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F1(); } public interface I1 { void F2(); } class B1 : A1 { public override void F1() { throw new System.NotImplementedException(); } class C1 : A1, I1 { public override void F1() { throw new System.NotImplementedException(); } } } </Document> <Document> class B2 : A1 { public override void F1() { throw new System.NotImplementedException(); } class C2 : A1, I1 { public override void F1() { throw new System.NotImplementedException(); } } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <ProjectReference>Assembly1</ProjectReference> <Document> class B3 : A1 { public override void F1() { throw new System.NotImplementedException(); } class C3 : A1, I1 { public override void F1() { throw new System.NotImplementedException(); } } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_DifferentAssemblyWithSameTypeName() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F1(); } public interface I1 { void F2(); } class {|FixAllInSolution:B1|} : A1 { class C1 : A1, I1 { } } </Document> <Document> class B2 : A1 { class C2 : A1, I1 { } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F2(); } class B3 : A1 { class C3 : A1, I1 { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F1(); } public interface I1 { void F2(); } class B1 : A1 { public override void F1() { throw new System.NotImplementedException(); } class C1 : A1, I1 { public override void F1() { throw new System.NotImplementedException(); } } } </Document> <Document> class B2 : A1 { public override void F1() { throw new System.NotImplementedException(); } class C2 : A1, I1 { public override void F1() { throw new System.NotImplementedException(); } } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> public abstract class A1 { public abstract void F2(); } class B3 : A1 { class C3 : A1, I1 { } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } #endregion } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/ExternalAccess/ProjectSystem/Api/IProjectSystemReferenceCleanupService2.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.ProjectSystem.Api { // Interface to be implemented and MEF exported by Project System internal interface IProjectSystemReferenceCleanupService2 : IProjectSystemReferenceCleanupService { /// <summary> /// Gets an operation that can update the project’s references by removing or marking references as /// TreatAsUsed in the project file. /// </summary> Task<IProjectSystemUpdateReferenceOperation> GetUpdateReferenceOperationAsync( string projectPath, ProjectSystemReferenceUpdate referenceUpdate, CancellationToken canellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.ProjectSystem.Api { // Interface to be implemented and MEF exported by Project System internal interface IProjectSystemReferenceCleanupService2 : IProjectSystemReferenceCleanupService { /// <summary> /// Gets an operation that can update the project’s references by removing or marking references as /// TreatAsUsed in the project file. /// </summary> Task<IProjectSystemUpdateReferenceOperation> GetUpdateReferenceOperationAsync( string projectPath, ProjectSystemReferenceUpdate referenceUpdate, CancellationToken canellationToken); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/AddParameterDialog_InProc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature; using Microsoft.VisualStudio.Threading; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal class AddParameterDialog_InProc : AbstractCodeRefactorDialog_InProc<AddParameterDialog, AddParameterDialog.TestAccessor> { private AddParameterDialog_InProc() { } public static AddParameterDialog_InProc Create() => new AddParameterDialog_InProc(); public void FillCallSiteField(string callSiteValue) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); dialog.CallsiteValueTextBox.Focus(); dialog.CallsiteValueTextBox.Text = callSiteValue; }); } } public void FillNameField(string parameterName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); dialog.NameContentControl.Focus(); dialog.NameContentControl.Text = parameterName; }); } } public void SetCallSiteTodo() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); dialog.IntroduceErrorRadioButton.Focus(); dialog.IntroduceErrorRadioButton.IsChecked = true; }); } } public void FillTypeField(string typeName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); dialog.TypeContentControl.Focus(); dialog.TypeContentControl.Text = typeName; }); } } public void ClickOK() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.OKButton, cancellationTokenSource.Token)); } } public void ClickCancel() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.CancelButton, cancellationTokenSource.Token)); } } public bool CloseWindow() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { if (JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationTokenSource.Token)) is null) { return false; } } ClickCancel(); return true; } protected override AddParameterDialog.TestAccessor GetAccessor(AddParameterDialog dialog) => dialog.GetTestAccessor(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature; using Microsoft.VisualStudio.Threading; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal class AddParameterDialog_InProc : AbstractCodeRefactorDialog_InProc<AddParameterDialog, AddParameterDialog.TestAccessor> { private AddParameterDialog_InProc() { } public static AddParameterDialog_InProc Create() => new AddParameterDialog_InProc(); public void FillCallSiteField(string callSiteValue) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); dialog.CallsiteValueTextBox.Focus(); dialog.CallsiteValueTextBox.Text = callSiteValue; }); } } public void FillNameField(string parameterName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); dialog.NameContentControl.Focus(); dialog.NameContentControl.Text = parameterName; }); } } public void SetCallSiteTodo() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); dialog.IntroduceErrorRadioButton.Focus(); dialog.IntroduceErrorRadioButton.IsChecked = true; }); } } public void FillTypeField(string typeName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); dialog.TypeContentControl.Focus(); dialog.TypeContentControl.Text = typeName; }); } } public void ClickOK() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.OKButton, cancellationTokenSource.Token)); } } public void ClickCancel() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.CancelButton, cancellationTokenSource.Token)); } } public bool CloseWindow() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { if (JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationTokenSource.Token)) is null) { return false; } } ClickCancel(); return true; } protected override AddParameterDialog.TestAccessor GetAccessor(AddParameterDialog dialog) => dialog.GetTestAccessor(); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/VisualBasicTest/EditAndContinue/SyntaxUtilitiesTests.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 SyntaxUtilities = Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.SyntaxUtilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EditAndContinue Public Class SyntaxUtilitiesTests Private Shared Sub VerifySyntaxMap(oldSource As String, newSource As String) Dim oldRoot = SyntaxFactory.ParseSyntaxTree(oldSource).GetRoot() Dim newRoot = SyntaxFactory.ParseSyntaxTree(newSource).GetRoot() For Each oldNode In oldRoot.DescendantNodes().Where(Function(n) n.FullSpan.Length > 0) Dim newNode = SyntaxUtilities.FindPartner(oldRoot, newRoot, oldNode) Assert.True(SyntaxFactory.AreEquivalent(oldNode, newNode), $"Node 'oldNodeEnd' not equivalent to 'newNodeEnd'.") Next End Sub <Fact> Public Sub FindPartner1() Dim source1 = " Imports System Class C Shared Sub Main(args As String()) ' sdasd Dim b = true Do Console.WriteLine(""hi"") While b = True End Sub End Class " Dim source2 = " Imports System Class C Shared Sub Main(args As String()) Dim b = true Do Console.WriteLine(""hi"") While b = True End Sub End Class " VerifySyntaxMap(source1, source2) End Sub <Fact> Public Sub FindLeafNodeAndPartner1() Dim leftRoot = SyntaxFactory.ParseSyntaxTree(" Imports System; Class C Public Sub M() If 0 = 1 Then Console.WriteLine(0) End If End Sub End Class ").GetRoot() Dim leftPosition = leftRoot.DescendantNodes().OfType(Of LiteralExpressionSyntax).ElementAt(2).SpanStart '0 within Console.WriteLine(0) Dim rightRoot = SyntaxFactory.ParseSyntaxTree(" Imports System; Class C Public Sub M() If 0 = 1 Then If 2 = 3 Then Console.WriteLine(0) End If End If End Sub End Class ").GetRoot() Dim leftNode As SyntaxNode = Nothing Dim rightNodeOpt As SyntaxNode = Nothing SyntaxUtilities.FindLeafNodeAndPartner(leftRoot, leftPosition, rightRoot, leftNode, rightNodeOpt) Assert.Equal("0", leftNode.ToString()) Assert.Null(rightNodeOpt) End Sub <Fact> Public Sub FindLeafNodeAndPartner2() ' Check that the method does Not fail even if the index of the child (4) ' is greater than the count of children on the corresponding (from the upper side) node (3). Dim leftRoot = SyntaxFactory.ParseSyntaxTree(" Imports System; Class C Public Sub M() If 0 = 1 Then Console.WriteLine(0) Console.WriteLine(1) Console.WriteLine(2) Console.WriteLine(3) End If End Sub End Class ").GetRoot() Dim leftPosition = leftRoot.DescendantNodes().OfType(Of LiteralExpressionSyntax).ElementAt(5).SpanStart '3 within Console.WriteLine(3) Dim rightRoot = SyntaxFactory.ParseSyntaxTree(" Imports System; Class C Public Sub M() If 0 = 1 Then If 2 = 3 Then Console.WriteLine(0) Console.WriteLine(1) Console.WriteLine(2) Console.WriteLine(3) End If End If End Sub End Class ").GetRoot() Dim leftNode As SyntaxNode = Nothing Dim rightNodeOpt As SyntaxNode = Nothing SyntaxUtilities.FindLeafNodeAndPartner(leftRoot, leftPosition, rightRoot, leftNode, rightNodeOpt) Assert.Equal("3", leftNode.ToString()) Assert.Null(rightNodeOpt) 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 SyntaxUtilities = Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.SyntaxUtilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EditAndContinue Public Class SyntaxUtilitiesTests Private Shared Sub VerifySyntaxMap(oldSource As String, newSource As String) Dim oldRoot = SyntaxFactory.ParseSyntaxTree(oldSource).GetRoot() Dim newRoot = SyntaxFactory.ParseSyntaxTree(newSource).GetRoot() For Each oldNode In oldRoot.DescendantNodes().Where(Function(n) n.FullSpan.Length > 0) Dim newNode = SyntaxUtilities.FindPartner(oldRoot, newRoot, oldNode) Assert.True(SyntaxFactory.AreEquivalent(oldNode, newNode), $"Node 'oldNodeEnd' not equivalent to 'newNodeEnd'.") Next End Sub <Fact> Public Sub FindPartner1() Dim source1 = " Imports System Class C Shared Sub Main(args As String()) ' sdasd Dim b = true Do Console.WriteLine(""hi"") While b = True End Sub End Class " Dim source2 = " Imports System Class C Shared Sub Main(args As String()) Dim b = true Do Console.WriteLine(""hi"") While b = True End Sub End Class " VerifySyntaxMap(source1, source2) End Sub <Fact> Public Sub FindLeafNodeAndPartner1() Dim leftRoot = SyntaxFactory.ParseSyntaxTree(" Imports System; Class C Public Sub M() If 0 = 1 Then Console.WriteLine(0) End If End Sub End Class ").GetRoot() Dim leftPosition = leftRoot.DescendantNodes().OfType(Of LiteralExpressionSyntax).ElementAt(2).SpanStart '0 within Console.WriteLine(0) Dim rightRoot = SyntaxFactory.ParseSyntaxTree(" Imports System; Class C Public Sub M() If 0 = 1 Then If 2 = 3 Then Console.WriteLine(0) End If End If End Sub End Class ").GetRoot() Dim leftNode As SyntaxNode = Nothing Dim rightNodeOpt As SyntaxNode = Nothing SyntaxUtilities.FindLeafNodeAndPartner(leftRoot, leftPosition, rightRoot, leftNode, rightNodeOpt) Assert.Equal("0", leftNode.ToString()) Assert.Null(rightNodeOpt) End Sub <Fact> Public Sub FindLeafNodeAndPartner2() ' Check that the method does Not fail even if the index of the child (4) ' is greater than the count of children on the corresponding (from the upper side) node (3). Dim leftRoot = SyntaxFactory.ParseSyntaxTree(" Imports System; Class C Public Sub M() If 0 = 1 Then Console.WriteLine(0) Console.WriteLine(1) Console.WriteLine(2) Console.WriteLine(3) End If End Sub End Class ").GetRoot() Dim leftPosition = leftRoot.DescendantNodes().OfType(Of LiteralExpressionSyntax).ElementAt(5).SpanStart '3 within Console.WriteLine(3) Dim rightRoot = SyntaxFactory.ParseSyntaxTree(" Imports System; Class C Public Sub M() If 0 = 1 Then If 2 = 3 Then Console.WriteLine(0) Console.WriteLine(1) Console.WriteLine(2) Console.WriteLine(3) End If End If End Sub End Class ").GetRoot() Dim leftNode As SyntaxNode = Nothing Dim rightNodeOpt As SyntaxNode = Nothing SyntaxUtilities.FindLeafNodeAndPartner(leftRoot, leftPosition, rightRoot, leftNode, rightNodeOpt) Assert.Equal("3", leftNode.ToString()) Assert.Null(rightNodeOpt) End Sub End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Portable/Binder/LookupOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Options that can be used to modify the symbol lookup mechanism. /// </summary> /// <remarks> /// Multiple options can be combined together. LookupOptions.AreValid checks for valid combinations. /// </remarks> [Flags] internal enum LookupOptions { /// <summary> /// Consider all symbols, using normal accessibility rules. /// </summary> Default = 0, /// <summary> /// Consider only namespace aliases and extern aliases. /// </summary> NamespaceAliasesOnly = 1 << 1, /// <summary> /// Consider only namespaces and types. /// </summary> NamespacesOrTypesOnly = 1 << 2, /// <summary> /// Consider non-members, plus invocable members. /// </summary> MustBeInvocableIfMember = 1 << 3, /// <summary> /// Consider only symbols that are instance members. Valid with IncludeExtensionMethods /// since extension methods are invoked on an instance. /// </summary> MustBeInstance = 1 << 4, /// <summary> /// Do not consider symbols that are instance members. /// </summary> MustNotBeInstance = 1 << 5, /// <summary> /// Do not consider symbols that are namespaces. /// </summary> MustNotBeNamespace = 1 << 6, /// <summary> /// Consider methods of any arity when arity zero is specified. Because type parameters can be inferred, it is /// often desired to consider generic methods when no type arguments were present. /// </summary> AllMethodsOnArityZero = 1 << 7, /// <summary> /// Look only for label symbols. This must be exclusive of all other options. /// </summary> LabelsOnly = 1 << 8, /// <summary> /// Usually, when determining if a member is accessible, both the type of the receiver /// and the type containing the access are used. If this flag is specified, then only /// the containing type will be used (i.e. as if you've written base.XX). /// </summary> UseBaseReferenceAccessibility = 1 << 9, /// <summary> /// Include extension methods. /// </summary> IncludeExtensionMethods = 1 << 10, /// <summary> /// Consider only attribute types. /// </summary> AttributeTypeOnly = (1 << 11) | NamespacesOrTypesOnly, /// <summary> /// Consider lookup name to be a verbatim identifier. /// If this flag is specified, then only one lookup is performed for attribute name: lookup with the given name, /// and attribute name lookup with "Attribute" suffix is skipped. /// </summary> VerbatimNameAttributeTypeOnly = (1 << 12) | AttributeTypeOnly, /// <summary> /// Consider named types of any arity when arity zero is specified. It is specifically desired for nameof in such situations: nameof(System.Collections.Generic.List) /// </summary> AllNamedTypesOnArityZero = 1 << 13, /// <summary> /// Do not consider symbols that are method type parameters. /// </summary> MustNotBeMethodTypeParameter = 1 << 14, /// <summary> /// Consider only symbols that are abstract or virtual. /// </summary> MustBeAbstractOrVirtual = 1 << 15, } internal static class LookupOptionExtensions { /// <summary> /// Are these options valid in their current combination? /// </summary> /// <remarks> /// Some checks made here: /// /// - Default is valid. /// - If LabelsOnly is set, it must be the only option. /// - If one of MustBeInstance or MustNotBeInstance are set, the other one must not be set. /// - If any of MustNotBeInstance, MustBeInstance, or MustNotBeNonInvocableMember are set, /// the options are considered valid. /// - If MustNotBeNamespace is set, neither NamespaceAliasesOnly nor NamespacesOrTypesOnly must be set. /// - Otherwise, only one of NamespaceAliasesOnly, NamespacesOrTypesOnly, or AllMethodsOnArityZero must be set. /// </remarks> internal static bool AreValid(this LookupOptions options) { if (options == LookupOptions.Default) { return true; } if ((options & LookupOptions.LabelsOnly) != 0) { return options == LookupOptions.LabelsOnly; } // These are exclusive; both must not be present. LookupOptions mustBeAndNotBeInstance = (LookupOptions.MustBeInstance | LookupOptions.MustNotBeInstance); if ((options & mustBeAndNotBeInstance) == mustBeAndNotBeInstance) { return false; } // If MustNotBeNamespace or MustNotBeMethodTypeParameter is set, neither NamespaceAliasesOnly nor NamespacesOrTypesOnly must be set. if ((options & (LookupOptions.MustNotBeNamespace | LookupOptions.MustNotBeMethodTypeParameter)) != 0 && (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly)) != 0) { return false; } LookupOptions onlyOptions = options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.AllMethodsOnArityZero); return OnlyOneBitSet(onlyOptions); } internal static void ThrowIfInvalid(this LookupOptions options) { if (!options.AreValid()) { throw new ArgumentException(CSharpResources.LookupOptionsHasInvalidCombo); } } private static bool OnlyOneBitSet(LookupOptions o) { return (o & (o - 1)) == 0; } internal static bool CanConsiderMembers(this LookupOptions options) { return (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.LabelsOnly)) == 0; } internal static bool CanConsiderLocals(this LookupOptions options) { return (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.LabelsOnly)) == 0; } internal static bool CanConsiderTypes(this LookupOptions options) { return (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.MustBeInvocableIfMember | LookupOptions.MustBeInstance | LookupOptions.LabelsOnly)) == 0; } internal static bool CanConsiderNamespaces(this LookupOptions options) { return (options & (LookupOptions.MustNotBeNamespace | LookupOptions.MustBeInvocableIfMember | LookupOptions.MustBeInstance | LookupOptions.LabelsOnly)) == 0; } internal static bool IsAttributeTypeLookup(this LookupOptions options) { return (options & LookupOptions.AttributeTypeOnly) == LookupOptions.AttributeTypeOnly; } internal static bool IsVerbatimNameAttributeTypeLookup(this LookupOptions options) { return (options & LookupOptions.VerbatimNameAttributeTypeOnly) == LookupOptions.VerbatimNameAttributeTypeOnly; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Options that can be used to modify the symbol lookup mechanism. /// </summary> /// <remarks> /// Multiple options can be combined together. LookupOptions.AreValid checks for valid combinations. /// </remarks> [Flags] internal enum LookupOptions { /// <summary> /// Consider all symbols, using normal accessibility rules. /// </summary> Default = 0, /// <summary> /// Consider only namespace aliases and extern aliases. /// </summary> NamespaceAliasesOnly = 1 << 1, /// <summary> /// Consider only namespaces and types. /// </summary> NamespacesOrTypesOnly = 1 << 2, /// <summary> /// Consider non-members, plus invocable members. /// </summary> MustBeInvocableIfMember = 1 << 3, /// <summary> /// Consider only symbols that are instance members. Valid with IncludeExtensionMethods /// since extension methods are invoked on an instance. /// </summary> MustBeInstance = 1 << 4, /// <summary> /// Do not consider symbols that are instance members. /// </summary> MustNotBeInstance = 1 << 5, /// <summary> /// Do not consider symbols that are namespaces. /// </summary> MustNotBeNamespace = 1 << 6, /// <summary> /// Consider methods of any arity when arity zero is specified. Because type parameters can be inferred, it is /// often desired to consider generic methods when no type arguments were present. /// </summary> AllMethodsOnArityZero = 1 << 7, /// <summary> /// Look only for label symbols. This must be exclusive of all other options. /// </summary> LabelsOnly = 1 << 8, /// <summary> /// Usually, when determining if a member is accessible, both the type of the receiver /// and the type containing the access are used. If this flag is specified, then only /// the containing type will be used (i.e. as if you've written base.XX). /// </summary> UseBaseReferenceAccessibility = 1 << 9, /// <summary> /// Include extension methods. /// </summary> IncludeExtensionMethods = 1 << 10, /// <summary> /// Consider only attribute types. /// </summary> AttributeTypeOnly = (1 << 11) | NamespacesOrTypesOnly, /// <summary> /// Consider lookup name to be a verbatim identifier. /// If this flag is specified, then only one lookup is performed for attribute name: lookup with the given name, /// and attribute name lookup with "Attribute" suffix is skipped. /// </summary> VerbatimNameAttributeTypeOnly = (1 << 12) | AttributeTypeOnly, /// <summary> /// Consider named types of any arity when arity zero is specified. It is specifically desired for nameof in such situations: nameof(System.Collections.Generic.List) /// </summary> AllNamedTypesOnArityZero = 1 << 13, /// <summary> /// Do not consider symbols that are method type parameters. /// </summary> MustNotBeMethodTypeParameter = 1 << 14, /// <summary> /// Consider only symbols that are abstract or virtual. /// </summary> MustBeAbstractOrVirtual = 1 << 15, } internal static class LookupOptionExtensions { /// <summary> /// Are these options valid in their current combination? /// </summary> /// <remarks> /// Some checks made here: /// /// - Default is valid. /// - If LabelsOnly is set, it must be the only option. /// - If one of MustBeInstance or MustNotBeInstance are set, the other one must not be set. /// - If any of MustNotBeInstance, MustBeInstance, or MustNotBeNonInvocableMember are set, /// the options are considered valid. /// - If MustNotBeNamespace is set, neither NamespaceAliasesOnly nor NamespacesOrTypesOnly must be set. /// - Otherwise, only one of NamespaceAliasesOnly, NamespacesOrTypesOnly, or AllMethodsOnArityZero must be set. /// </remarks> internal static bool AreValid(this LookupOptions options) { if (options == LookupOptions.Default) { return true; } if ((options & LookupOptions.LabelsOnly) != 0) { return options == LookupOptions.LabelsOnly; } // These are exclusive; both must not be present. LookupOptions mustBeAndNotBeInstance = (LookupOptions.MustBeInstance | LookupOptions.MustNotBeInstance); if ((options & mustBeAndNotBeInstance) == mustBeAndNotBeInstance) { return false; } // If MustNotBeNamespace or MustNotBeMethodTypeParameter is set, neither NamespaceAliasesOnly nor NamespacesOrTypesOnly must be set. if ((options & (LookupOptions.MustNotBeNamespace | LookupOptions.MustNotBeMethodTypeParameter)) != 0 && (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly)) != 0) { return false; } LookupOptions onlyOptions = options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.AllMethodsOnArityZero); return OnlyOneBitSet(onlyOptions); } internal static void ThrowIfInvalid(this LookupOptions options) { if (!options.AreValid()) { throw new ArgumentException(CSharpResources.LookupOptionsHasInvalidCombo); } } private static bool OnlyOneBitSet(LookupOptions o) { return (o & (o - 1)) == 0; } internal static bool CanConsiderMembers(this LookupOptions options) { return (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.LabelsOnly)) == 0; } internal static bool CanConsiderLocals(this LookupOptions options) { return (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.LabelsOnly)) == 0; } internal static bool CanConsiderTypes(this LookupOptions options) { return (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.MustBeInvocableIfMember | LookupOptions.MustBeInstance | LookupOptions.LabelsOnly)) == 0; } internal static bool CanConsiderNamespaces(this LookupOptions options) { return (options & (LookupOptions.MustNotBeNamespace | LookupOptions.MustBeInvocableIfMember | LookupOptions.MustBeInstance | LookupOptions.LabelsOnly)) == 0; } internal static bool IsAttributeTypeLookup(this LookupOptions options) { return (options & LookupOptions.AttributeTypeOnly) == LookupOptions.AttributeTypeOnly; } internal static bool IsVerbatimNameAttributeTypeLookup(this LookupOptions options) { return (options & LookupOptions.VerbatimNameAttributeTypeOnly) == LookupOptions.VerbatimNameAttributeTypeOnly; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/InternalUtilities/JsonWriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { /// <summary> /// A simple, forward-only JSON writer to avoid adding dependencies to the compiler. /// Used to generate /errorlogger output. /// /// Does not guarantee well-formed JSON if misused. It is the caller's responsibility /// to balance array/object start/end, to only write key-value pairs to objects and /// elements to arrays, etc. /// /// Takes ownership of the given <see cref="TextWriter" /> at construction and handles its disposal. /// </summary> internal sealed class JsonWriter : IDisposable { private readonly TextWriter _output; private int _indent; private Pending _pending; private enum Pending { None, NewLineAndIndent, CommaNewLineAndIndent }; private const string Indentation = " "; public JsonWriter(TextWriter output) { _output = output; _pending = Pending.None; } public void WriteObjectStart() { WriteStart('{'); } public void WriteObjectStart(string key) { WriteKey(key); WriteObjectStart(); } public void WriteObjectEnd() { WriteEnd('}'); } public void WriteArrayStart() { WriteStart('['); } public void WriteArrayStart(string key) { WriteKey(key); WriteArrayStart(); } public void WriteArrayEnd() { WriteEnd(']'); } public void WriteKey(string key) { Write(key); _output.Write(": "); _pending = Pending.None; } public void Write(string key, string? value) { WriteKey(key); Write(value); } public void Write(string key, int value) { WriteKey(key); Write(value); } public void Write(string key, int? value) { WriteKey(key); Write(value); } public void Write(string key, bool value) { WriteKey(key); Write(value); } public void Write(string key, bool? value) { WriteKey(key); Write(value); } public void Write<T>(string key, T value) where T : struct, Enum { WriteKey(key); Write(value.ToString()); } public void WriteInvariant<T>(T value) where T : struct, IFormattable { Write(value.ToString(null, CultureInfo.InvariantCulture)); } public void WriteInvariant<T>(string key, T value) where T : struct, IFormattable { WriteKey(key); WriteInvariant(value); } public void WriteNull(string key) { WriteKey(key); WriteNull(); } public void WriteNull() { WritePending(); _output.Write("null"); _pending = Pending.CommaNewLineAndIndent; } public void Write(string? value) { WritePending(); if (value is null) { _output.Write("null"); } else { _output.Write('"'); _output.Write(EscapeString(value)); _output.Write('"'); } _pending = Pending.CommaNewLineAndIndent; } public void Write(int value) { WritePending(); _output.Write(value.ToString(CultureInfo.InvariantCulture)); _pending = Pending.CommaNewLineAndIndent; } public void Write(int? value) { if (value is { } i) { Write(i); } else { WriteNull(); } } public void Write(bool value) { WritePending(); _output.Write(value ? "true" : "false"); _pending = Pending.CommaNewLineAndIndent; } public void Write(bool? value) { if (value is { } b) { Write(b); } else { WriteNull(); } } public void Write<T>(T value) where T : struct, Enum { Write(value.ToString()); } public void Write<T>(T? value) where T : struct, Enum { if (value is { } e) { Write(e); } else { WriteNull(); } } private void WritePending() { if (_pending == Pending.None) { return; } Debug.Assert(_pending == Pending.NewLineAndIndent || _pending == Pending.CommaNewLineAndIndent); if (_pending == Pending.CommaNewLineAndIndent) { _output.Write(','); } _output.WriteLine(); for (int i = 0; i < _indent; i++) { _output.Write(Indentation); } } private void WriteStart(char c) { WritePending(); _output.Write(c); _pending = Pending.NewLineAndIndent; _indent++; } private void WriteEnd(char c) { _pending = Pending.NewLineAndIndent; _indent--; WritePending(); _output.Write(c); _pending = Pending.CommaNewLineAndIndent; } public void Dispose() { _output.Dispose(); } // String escaping implementation forked from System.Runtime.Serialization.Json to // avoid a large dependency graph for this small amount of code: // // https://github.com/dotnet/corefx/blob/main/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JavaScriptString.cs // internal static string EscapeString(string value) { PooledStringBuilder? pooledBuilder = null; StringBuilder? b = null; if (RoslynString.IsNullOrEmpty(value)) { return string.Empty; } int startIndex = 0; int count = 0; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (c == '\"' || c == '\\' || ShouldAppendAsUnicode(c)) { if (b == null) { RoslynDebug.Assert(pooledBuilder == null); pooledBuilder = PooledStringBuilder.GetInstance(); b = pooledBuilder.Builder; } if (count > 0) { b.Append(value, startIndex, count); } startIndex = i + 1; count = 0; switch (c) { case '\"': b.Append("\\\""); break; case '\\': b.Append("\\\\"); break; default: Debug.Assert(ShouldAppendAsUnicode(c)); AppendCharAsUnicode(b, c); break; } } else { count++; } } if (b == null) { return value; } else { RoslynDebug.Assert(pooledBuilder is object); } if (count > 0) { b.Append(value, startIndex, count); } return pooledBuilder.ToStringAndFree(); } private static void AppendCharAsUnicode(StringBuilder builder, char c) { builder.Append("\\u"); builder.AppendFormat(CultureInfo.InvariantCulture, "{0:x4}", (int)c); } private static bool ShouldAppendAsUnicode(char c) { // Note on newline characters: Newline characters in JSON strings need to be encoded on the way out // See Unicode 6.2, Table 5-1 (http://www.unicode.org/versions/Unicode6.2.0/ch05.pdf]) for the full list. // We only care about NEL, LS, and PS, since the other newline characters are all // control characters so are already encoded. return c < ' ' || c >= (char)0xfffe || // max char (c >= (char)0xd800 && c <= (char)0xdfff) || // between high and low surrogate (c == '\u0085' || c == '\u2028' || c == '\u2029'); // Unicode new line characters } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { /// <summary> /// A simple, forward-only JSON writer to avoid adding dependencies to the compiler. /// Used to generate /errorlogger output. /// /// Does not guarantee well-formed JSON if misused. It is the caller's responsibility /// to balance array/object start/end, to only write key-value pairs to objects and /// elements to arrays, etc. /// /// Takes ownership of the given <see cref="TextWriter" /> at construction and handles its disposal. /// </summary> internal sealed class JsonWriter : IDisposable { private readonly TextWriter _output; private int _indent; private Pending _pending; private enum Pending { None, NewLineAndIndent, CommaNewLineAndIndent }; private const string Indentation = " "; public JsonWriter(TextWriter output) { _output = output; _pending = Pending.None; } public void WriteObjectStart() { WriteStart('{'); } public void WriteObjectStart(string key) { WriteKey(key); WriteObjectStart(); } public void WriteObjectEnd() { WriteEnd('}'); } public void WriteArrayStart() { WriteStart('['); } public void WriteArrayStart(string key) { WriteKey(key); WriteArrayStart(); } public void WriteArrayEnd() { WriteEnd(']'); } public void WriteKey(string key) { Write(key); _output.Write(": "); _pending = Pending.None; } public void Write(string key, string? value) { WriteKey(key); Write(value); } public void Write(string key, int value) { WriteKey(key); Write(value); } public void Write(string key, int? value) { WriteKey(key); Write(value); } public void Write(string key, bool value) { WriteKey(key); Write(value); } public void Write(string key, bool? value) { WriteKey(key); Write(value); } public void Write<T>(string key, T value) where T : struct, Enum { WriteKey(key); Write(value.ToString()); } public void WriteInvariant<T>(T value) where T : struct, IFormattable { Write(value.ToString(null, CultureInfo.InvariantCulture)); } public void WriteInvariant<T>(string key, T value) where T : struct, IFormattable { WriteKey(key); WriteInvariant(value); } public void WriteNull(string key) { WriteKey(key); WriteNull(); } public void WriteNull() { WritePending(); _output.Write("null"); _pending = Pending.CommaNewLineAndIndent; } public void Write(string? value) { WritePending(); if (value is null) { _output.Write("null"); } else { _output.Write('"'); _output.Write(EscapeString(value)); _output.Write('"'); } _pending = Pending.CommaNewLineAndIndent; } public void Write(int value) { WritePending(); _output.Write(value.ToString(CultureInfo.InvariantCulture)); _pending = Pending.CommaNewLineAndIndent; } public void Write(int? value) { if (value is { } i) { Write(i); } else { WriteNull(); } } public void Write(bool value) { WritePending(); _output.Write(value ? "true" : "false"); _pending = Pending.CommaNewLineAndIndent; } public void Write(bool? value) { if (value is { } b) { Write(b); } else { WriteNull(); } } public void Write<T>(T value) where T : struct, Enum { Write(value.ToString()); } public void Write<T>(T? value) where T : struct, Enum { if (value is { } e) { Write(e); } else { WriteNull(); } } private void WritePending() { if (_pending == Pending.None) { return; } Debug.Assert(_pending == Pending.NewLineAndIndent || _pending == Pending.CommaNewLineAndIndent); if (_pending == Pending.CommaNewLineAndIndent) { _output.Write(','); } _output.WriteLine(); for (int i = 0; i < _indent; i++) { _output.Write(Indentation); } } private void WriteStart(char c) { WritePending(); _output.Write(c); _pending = Pending.NewLineAndIndent; _indent++; } private void WriteEnd(char c) { _pending = Pending.NewLineAndIndent; _indent--; WritePending(); _output.Write(c); _pending = Pending.CommaNewLineAndIndent; } public void Dispose() { _output.Dispose(); } // String escaping implementation forked from System.Runtime.Serialization.Json to // avoid a large dependency graph for this small amount of code: // // https://github.com/dotnet/corefx/blob/main/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JavaScriptString.cs // internal static string EscapeString(string value) { PooledStringBuilder? pooledBuilder = null; StringBuilder? b = null; if (RoslynString.IsNullOrEmpty(value)) { return string.Empty; } int startIndex = 0; int count = 0; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (c == '\"' || c == '\\' || ShouldAppendAsUnicode(c)) { if (b == null) { RoslynDebug.Assert(pooledBuilder == null); pooledBuilder = PooledStringBuilder.GetInstance(); b = pooledBuilder.Builder; } if (count > 0) { b.Append(value, startIndex, count); } startIndex = i + 1; count = 0; switch (c) { case '\"': b.Append("\\\""); break; case '\\': b.Append("\\\\"); break; default: Debug.Assert(ShouldAppendAsUnicode(c)); AppendCharAsUnicode(b, c); break; } } else { count++; } } if (b == null) { return value; } else { RoslynDebug.Assert(pooledBuilder is object); } if (count > 0) { b.Append(value, startIndex, count); } return pooledBuilder.ToStringAndFree(); } private static void AppendCharAsUnicode(StringBuilder builder, char c) { builder.Append("\\u"); builder.AppendFormat(CultureInfo.InvariantCulture, "{0:x4}", (int)c); } private static bool ShouldAppendAsUnicode(char c) { // Note on newline characters: Newline characters in JSON strings need to be encoded on the way out // See Unicode 6.2, Table 5-1 (http://www.unicode.org/versions/Unicode6.2.0/ch05.pdf]) for the full list. // We only care about NEL, LS, and PS, since the other newline characters are all // control characters so are already encoded. return c < ' ' || c >= (char)0xfffe || // max char (c >= (char)0xd800 && c <= (char)0xdfff) || // between high and low surrogate (c == '\u0085' || c == '\u2028' || c == '\u2029'); // Unicode new line characters } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Impl/CodeModel/CodeModelProjectCache.CacheEntry.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal sealed partial class CodeModelProjectCache { private struct CacheEntry { // NOTE: The logic here is a little bit tricky. We can't just keep a WeakReference to // something like a ComHandle, since it's not something that our clients keep alive. // instead, we keep a weak reference to the inner managed object, which we know will // always be alive if the outer aggregate is alive. We can't just keep a WeakReference // to the RCW for the outer object either, since in cases where we have a DCOM or native // client, the RCW will be cleaned up, even though there is still a native reference // to the underlying native outer object. // // Instead we make use of an implementation detail of the way the CLR's COM aggregation // works. Namely, if all references to the aggregated object are released, the CLR // responds to QI's for IUnknown with a different object. So, we store the original // value, when we know that we have a client, and then we use that to compare to see // if we still have a client alive. // // NOTE: This is _NOT_ AddRef'd. We use it just to store the integer value of the // IUnknown for comparison purposes. private readonly WeakComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> _fileCodeModelWeakComHandle; public CacheEntry(ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> handle) => _fileCodeModelWeakComHandle = new WeakComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(handle); public EnvDTE80.FileCodeModel2 FileCodeModelRcw { get { return _fileCodeModelWeakComHandle.ComAggregateObject; } } internal bool TryGetFileCodeModelInstanceWithoutCaringWhetherRcwIsAlive(out FileCodeModel fileCodeModel) => _fileCodeModelWeakComHandle.TryGetManagedObjectWithoutCaringWhetherNativeObjectIsAlive(out fileCodeModel); public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? ComHandle { get { return _fileCodeModelWeakComHandle.ComHandle; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal sealed partial class CodeModelProjectCache { private struct CacheEntry { // NOTE: The logic here is a little bit tricky. We can't just keep a WeakReference to // something like a ComHandle, since it's not something that our clients keep alive. // instead, we keep a weak reference to the inner managed object, which we know will // always be alive if the outer aggregate is alive. We can't just keep a WeakReference // to the RCW for the outer object either, since in cases where we have a DCOM or native // client, the RCW will be cleaned up, even though there is still a native reference // to the underlying native outer object. // // Instead we make use of an implementation detail of the way the CLR's COM aggregation // works. Namely, if all references to the aggregated object are released, the CLR // responds to QI's for IUnknown with a different object. So, we store the original // value, when we know that we have a client, and then we use that to compare to see // if we still have a client alive. // // NOTE: This is _NOT_ AddRef'd. We use it just to store the integer value of the // IUnknown for comparison purposes. private readonly WeakComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> _fileCodeModelWeakComHandle; public CacheEntry(ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> handle) => _fileCodeModelWeakComHandle = new WeakComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(handle); public EnvDTE80.FileCodeModel2 FileCodeModelRcw { get { return _fileCodeModelWeakComHandle.ComAggregateObject; } } internal bool TryGetFileCodeModelInstanceWithoutCaringWhetherRcwIsAlive(out FileCodeModel fileCodeModel) => _fileCodeModelWeakComHandle.TryGetManagedObjectWithoutCaringWhetherNativeObjectIsAlive(out fileCodeModel); public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? ComHandle { get { return _fileCodeModelWeakComHandle.ComHandle; } } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/Test/Extensions/ITextExtensionsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public class ITextExtensionsTests { [Fact] public void GetLeadingWhitespaceOfLineAtPosition_EmptyLineReturnsEmptyString() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(string.Empty, 0); Assert.Equal(string.Empty, leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceLineReturnsWhitespace1() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" ", 0); Assert.Equal(" ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceLineReturnsWhitespace2() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("\t\t", 0); Assert.Equal("\t\t", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceLineReturnsWhitespace3() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" \t ", 0); Assert.Equal(" \t ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextLine() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo", 0); Assert.Equal(string.Empty, leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextLineStartingWithWhitespace1() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" Goo", 0); Assert.Equal(" ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextLineStartingWithWhitespace2() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("\t\tGoo", 0); Assert.Equal("\t\t", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextLineStartingWithWhitespace3() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" \t Goo", 0); Assert.Equal(" \t ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_EmptySecondLineReturnsEmptyString() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n", 5); Assert.Equal(string.Empty, leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceSecondLineReturnsWhitespace1() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n ", 5); Assert.Equal(" ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceSecondLineReturnsWhitespace2() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n\t\t", 5); Assert.Equal("\t\t", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceSecondLineReturnsWhitespace3() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n \t ", 5); Assert.Equal(" \t ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLine() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\nGoo", 5); Assert.Equal(string.Empty, leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLineStartingWithWhitespace1() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n Goo", 5); Assert.Equal(" ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLineStartingWithWhitespace2() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n\t\tGoo", 5); Assert.Equal("\t\t", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLineStartingWithWhitespace3() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n \t Goo", 5); Assert.Equal(" \t ", leadingWhitespace); } private static string GetLeadingWhitespaceOfLineAtPosition(string code, int position) { var text = SourceText.From(code); return text.GetLeadingWhitespaceOfLineAtPosition(position); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public class ITextExtensionsTests { [Fact] public void GetLeadingWhitespaceOfLineAtPosition_EmptyLineReturnsEmptyString() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(string.Empty, 0); Assert.Equal(string.Empty, leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceLineReturnsWhitespace1() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" ", 0); Assert.Equal(" ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceLineReturnsWhitespace2() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("\t\t", 0); Assert.Equal("\t\t", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceLineReturnsWhitespace3() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" \t ", 0); Assert.Equal(" \t ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextLine() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo", 0); Assert.Equal(string.Empty, leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextLineStartingWithWhitespace1() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" Goo", 0); Assert.Equal(" ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextLineStartingWithWhitespace2() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("\t\tGoo", 0); Assert.Equal("\t\t", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextLineStartingWithWhitespace3() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" \t Goo", 0); Assert.Equal(" \t ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_EmptySecondLineReturnsEmptyString() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n", 5); Assert.Equal(string.Empty, leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceSecondLineReturnsWhitespace1() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n ", 5); Assert.Equal(" ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceSecondLineReturnsWhitespace2() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n\t\t", 5); Assert.Equal("\t\t", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceSecondLineReturnsWhitespace3() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n \t ", 5); Assert.Equal(" \t ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLine() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\nGoo", 5); Assert.Equal(string.Empty, leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLineStartingWithWhitespace1() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n Goo", 5); Assert.Equal(" ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLineStartingWithWhitespace2() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n\t\tGoo", 5); Assert.Equal("\t\t", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLineStartingWithWhitespace3() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n \t Goo", 5); Assert.Equal(" \t ", leadingWhitespace); } private static string GetLeadingWhitespaceOfLineAtPosition(string code, int position) { var text = SourceText.From(code); return text.GetLeadingWhitespaceOfLineAtPosition(position); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Portable/Emitter/Model/GenericNamespaceTypeInstanceReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Emit { /// <summary> /// Represents a reference to a generic type instantiation that is not nested. /// e.g. MyNamespace.A{int} /// </summary> internal sealed class GenericNamespaceTypeInstanceReference : GenericTypeInstanceReference { public GenericNamespaceTypeInstanceReference(NamedTypeSymbol underlyingNamedType) : base(underlyingNamedType) { } public override Microsoft.Cci.IGenericTypeInstanceReference AsGenericTypeInstanceReference { get { return this; } } public override Microsoft.Cci.INamespaceTypeReference AsNamespaceTypeReference { get { return null; } } public override Microsoft.Cci.INestedTypeReference AsNestedTypeReference { get { return null; } } public override Microsoft.Cci.ISpecializedNestedTypeReference AsSpecializedNestedTypeReference { get { return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Emit { /// <summary> /// Represents a reference to a generic type instantiation that is not nested. /// e.g. MyNamespace.A{int} /// </summary> internal sealed class GenericNamespaceTypeInstanceReference : GenericTypeInstanceReference { public GenericNamespaceTypeInstanceReference(NamedTypeSymbol underlyingNamedType) : base(underlyingNamedType) { } public override Microsoft.Cci.IGenericTypeInstanceReference AsGenericTypeInstanceReference { get { return this; } } public override Microsoft.Cci.INamespaceTypeReference AsNamespaceTypeReference { get { return null; } } public override Microsoft.Cci.INestedTypeReference AsNestedTypeReference { get { return null; } } public override Microsoft.Cci.ISpecializedNestedTypeReference AsSpecializedNestedTypeReference { get { return null; } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/Core.Wpf/Interactive/InteractivePasteCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.ComponentModel.Composition; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Windows; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Interactive { // This command handler must be invoked after the handlers specified in `Order` attribute // (those handlers also implement `ICommandHandler<PasteCommandArgs>`), // because it will intercept the paste command and skip the rest of handlers in chain. [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(PredefinedCommandHandlerNames.InteractivePaste)] [Order(After = PredefinedCommandHandlerNames.Rename)] [Order(After = PredefinedCommandHandlerNames.FormatDocument)] [Order(After = PredefinedCommandHandlerNames.Commit)] [Order(After = PredefinedCompletionNames.CompletionCommandHandler)] internal sealed class InteractivePasteCommandHandler : ICommandHandler<PasteCommandArgs> { // The following two field definitions have to stay in sync with VS editor implementation /// <summary> /// A data format used to tag the contents of the clipboard so that it's clear /// the data has been put in the clipboard by our editor /// </summary> internal const string ClipboardLineBasedCutCopyTag = "VisualStudioEditorOperationsLineCutCopyClipboardTag"; /// <summary> /// A data format used to tag the contents of the clipboard as a box selection. /// This is the same string that was used in VS9 and previous versions. /// </summary> internal const string BoxSelectionCutCopyTag = "MSDEVColumnSelect"; private readonly IEditorOperationsFactoryService _editorOperationsFactoryService; private readonly ITextUndoHistoryRegistry _textUndoHistoryRegistry; // This is for unit test purpose only, do not explicitly set this field otherwise. internal IRoslynClipboard RoslynClipboard; public string DisplayName => EditorFeaturesResources.Paste_in_Interactive; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InteractivePasteCommandHandler(IEditorOperationsFactoryService editorOperationsFactoryService, ITextUndoHistoryRegistry textUndoHistoryRegistry) { _editorOperationsFactoryService = editorOperationsFactoryService; _textUndoHistoryRegistry = textUndoHistoryRegistry; RoslynClipboard = new SystemClipboardWrapper(); } public bool ExecuteCommand(PasteCommandArgs args, CommandExecutionContext context) { // InteractiveWindow handles pasting by itself, which including checks for buffer types, etc. if (!args.TextView.TextBuffer.ContentType.IsOfType(PredefinedInteractiveContentTypes.InteractiveContentTypeName) && RoslynClipboard.ContainsData(InteractiveClipboardFormat.Tag)) { PasteInteractiveFormat(args.TextView); return true; } else { return false; } } public CommandState GetCommandState(PasteCommandArgs args) => CommandState.Unspecified; [MethodImpl(MethodImplOptions.NoInlining)] // Avoid loading InteractiveWindow unless necessary private void PasteInteractiveFormat(ITextView textView) { var editorOperations = _editorOperationsFactoryService.GetEditorOperations(textView); var data = RoslynClipboard.GetDataObject(); Debug.Assert(data != null); var dataHasLineCutCopyTag = data.GetDataPresent(ClipboardLineBasedCutCopyTag); var dataHasBoxCutCopyTag = data.GetDataPresent(BoxSelectionCutCopyTag); Debug.Assert(!(dataHasLineCutCopyTag && dataHasBoxCutCopyTag)); string text; try { text = InteractiveClipboardFormat.Deserialize(RoslynClipboard.GetData(InteractiveClipboardFormat.Tag)); } catch (InvalidDataException) { text = "<bad clipboard data>"; } using var transaction = _textUndoHistoryRegistry.GetHistory(textView.TextBuffer).CreateTransaction(EditorFeaturesResources.Paste); editorOperations.AddBeforeTextBufferChangePrimitive(); if (dataHasLineCutCopyTag && textView.Selection.IsEmpty) { editorOperations.MoveToStartOfLine(extendSelection: false); editorOperations.InsertText(text); } else if (dataHasBoxCutCopyTag) { // If the caret is on a blank line, treat this like a normal stream insertion if (textView.Selection.IsEmpty && !HasNonWhiteSpaceCharacter(textView.Caret.Position.BufferPosition.GetContainingLine())) { // trim the last newline before paste var trimmed = text.Remove(text.LastIndexOf(textView.Options.GetNewLineCharacter())); editorOperations.InsertText(trimmed); } else { editorOperations.InsertTextAsBox(text, out _, out _); } } else { editorOperations.InsertText(text); } editorOperations.AddAfterTextBufferChangePrimitive(); transaction.Complete(); } private static bool HasNonWhiteSpaceCharacter(ITextSnapshotLine line) { var snapshot = line.Snapshot; var start = line.Start.Position; var count = line.Length; for (var i = 0; i < count; i++) { if (!char.IsWhiteSpace(snapshot[start + i])) { return true; } } return false; } // The mock clipboard used in tests will implement this interface internal interface IRoslynClipboard { bool ContainsData(string format); object GetData(string format); IDataObject GetDataObject(); } // In product code, we use this simple wrapper around system clipboard. // Maybe at some point we can elevate this class and interface so they could be shared among Roslyn code base. private class SystemClipboardWrapper : IRoslynClipboard { public bool ContainsData(string format) => Clipboard.ContainsData(format); public object GetData(string format) => Clipboard.GetData(format); public IDataObject GetDataObject() => Clipboard.GetDataObject(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.ComponentModel.Composition; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Windows; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Interactive { // This command handler must be invoked after the handlers specified in `Order` attribute // (those handlers also implement `ICommandHandler<PasteCommandArgs>`), // because it will intercept the paste command and skip the rest of handlers in chain. [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(PredefinedCommandHandlerNames.InteractivePaste)] [Order(After = PredefinedCommandHandlerNames.Rename)] [Order(After = PredefinedCommandHandlerNames.FormatDocument)] [Order(After = PredefinedCommandHandlerNames.Commit)] [Order(After = PredefinedCompletionNames.CompletionCommandHandler)] internal sealed class InteractivePasteCommandHandler : ICommandHandler<PasteCommandArgs> { // The following two field definitions have to stay in sync with VS editor implementation /// <summary> /// A data format used to tag the contents of the clipboard so that it's clear /// the data has been put in the clipboard by our editor /// </summary> internal const string ClipboardLineBasedCutCopyTag = "VisualStudioEditorOperationsLineCutCopyClipboardTag"; /// <summary> /// A data format used to tag the contents of the clipboard as a box selection. /// This is the same string that was used in VS9 and previous versions. /// </summary> internal const string BoxSelectionCutCopyTag = "MSDEVColumnSelect"; private readonly IEditorOperationsFactoryService _editorOperationsFactoryService; private readonly ITextUndoHistoryRegistry _textUndoHistoryRegistry; // This is for unit test purpose only, do not explicitly set this field otherwise. internal IRoslynClipboard RoslynClipboard; public string DisplayName => EditorFeaturesResources.Paste_in_Interactive; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InteractivePasteCommandHandler(IEditorOperationsFactoryService editorOperationsFactoryService, ITextUndoHistoryRegistry textUndoHistoryRegistry) { _editorOperationsFactoryService = editorOperationsFactoryService; _textUndoHistoryRegistry = textUndoHistoryRegistry; RoslynClipboard = new SystemClipboardWrapper(); } public bool ExecuteCommand(PasteCommandArgs args, CommandExecutionContext context) { // InteractiveWindow handles pasting by itself, which including checks for buffer types, etc. if (!args.TextView.TextBuffer.ContentType.IsOfType(PredefinedInteractiveContentTypes.InteractiveContentTypeName) && RoslynClipboard.ContainsData(InteractiveClipboardFormat.Tag)) { PasteInteractiveFormat(args.TextView); return true; } else { return false; } } public CommandState GetCommandState(PasteCommandArgs args) => CommandState.Unspecified; [MethodImpl(MethodImplOptions.NoInlining)] // Avoid loading InteractiveWindow unless necessary private void PasteInteractiveFormat(ITextView textView) { var editorOperations = _editorOperationsFactoryService.GetEditorOperations(textView); var data = RoslynClipboard.GetDataObject(); Debug.Assert(data != null); var dataHasLineCutCopyTag = data.GetDataPresent(ClipboardLineBasedCutCopyTag); var dataHasBoxCutCopyTag = data.GetDataPresent(BoxSelectionCutCopyTag); Debug.Assert(!(dataHasLineCutCopyTag && dataHasBoxCutCopyTag)); string text; try { text = InteractiveClipboardFormat.Deserialize(RoslynClipboard.GetData(InteractiveClipboardFormat.Tag)); } catch (InvalidDataException) { text = "<bad clipboard data>"; } using var transaction = _textUndoHistoryRegistry.GetHistory(textView.TextBuffer).CreateTransaction(EditorFeaturesResources.Paste); editorOperations.AddBeforeTextBufferChangePrimitive(); if (dataHasLineCutCopyTag && textView.Selection.IsEmpty) { editorOperations.MoveToStartOfLine(extendSelection: false); editorOperations.InsertText(text); } else if (dataHasBoxCutCopyTag) { // If the caret is on a blank line, treat this like a normal stream insertion if (textView.Selection.IsEmpty && !HasNonWhiteSpaceCharacter(textView.Caret.Position.BufferPosition.GetContainingLine())) { // trim the last newline before paste var trimmed = text.Remove(text.LastIndexOf(textView.Options.GetNewLineCharacter())); editorOperations.InsertText(trimmed); } else { editorOperations.InsertTextAsBox(text, out _, out _); } } else { editorOperations.InsertText(text); } editorOperations.AddAfterTextBufferChangePrimitive(); transaction.Complete(); } private static bool HasNonWhiteSpaceCharacter(ITextSnapshotLine line) { var snapshot = line.Snapshot; var start = line.Start.Position; var count = line.Length; for (var i = 0; i < count; i++) { if (!char.IsWhiteSpace(snapshot[start + i])) { return true; } } return false; } // The mock clipboard used in tests will implement this interface internal interface IRoslynClipboard { bool ContainsData(string format); object GetData(string format); IDataObject GetDataObject(); } // In product code, we use this simple wrapper around system clipboard. // Maybe at some point we can elevate this class and interface so they could be shared among Roslyn code base. private class SystemClipboardWrapper : IRoslynClipboard { public bool ContainsData(string format) => Clipboard.ContainsData(format); public object GetData(string format) => Clipboard.GetData(format); public IDataObject GetDataObject() => Clipboard.GetDataObject(); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/ExtractClass/ExtractClassDialog.xaml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Windows; using System.Windows.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractClass { /// <summary> /// Interaction logic for ExtractClassDialog.xaml /// </summary> internal partial class ExtractClassDialog : DialogWindow { public string OK => ServicesVSResources.OK; public string Cancel => ServicesVSResources.Cancel; public string SelectMembers => ServicesVSResources.Select_members_colon; public string ExtractClassTitle => ServicesVSResources.Extract_Base_Class; public ExtractClassViewModel ViewModel { get; } public MemberSelection MemberSelectionControl { get; } public ExtractClassDialog(ExtractClassViewModel viewModel) { ViewModel = viewModel; DataContext = ViewModel; MemberSelectionControl = new MemberSelection(ViewModel.MemberSelectionViewModel); Loaded += (s, e) => MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); InitializeComponent(); } private void OK_Click(object sender, RoutedEventArgs e) { if (ViewModel.TrySubmit()) { DialogResult = true; } } private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Windows; using System.Windows.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractClass { /// <summary> /// Interaction logic for ExtractClassDialog.xaml /// </summary> internal partial class ExtractClassDialog : DialogWindow { public string OK => ServicesVSResources.OK; public string Cancel => ServicesVSResources.Cancel; public string SelectMembers => ServicesVSResources.Select_members_colon; public string ExtractClassTitle => ServicesVSResources.Extract_Base_Class; public ExtractClassViewModel ViewModel { get; } public MemberSelection MemberSelectionControl { get; } public ExtractClassDialog(ExtractClassViewModel viewModel) { ViewModel = viewModel; DataContext = ViewModel; MemberSelectionControl = new MemberSelection(ViewModel.MemberSelectionViewModel); Loaded += (s, e) => MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); InitializeComponent(); } private void OK_Click(object sender, RoutedEventArgs e) { if (ViewModel.TrySubmit()) { DialogResult = true; } } private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false; } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Test/Semantic/Semantics/FieldInitializerBindingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class FieldInitializerBindingTests : CompilingTestBase { [Fact] public void NoInitializers() { var source = @" class C { static int s1; int i1; }"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = null; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = null; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } [Fact] public void ConstantInstanceInitializer() { var source = @" class C { static int s1; int i1 = 1; }"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = null; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[] { new ExpectedInitializer("i1", "1", lineNumber: 4), }; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } [Fact] public void ConstantStaticInitializer() { var source = @" class C { static int s1 = 1; int i1; }"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[] { new ExpectedInitializer("s1", "1", lineNumber: 3), }; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = null; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } [Fact] public void ExpressionInstanceInitializer() { var source = @" class C { static int s1; int i1 = 1 + Goo(); static int Goo() { return 1; } }"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = null; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[] { new ExpectedInitializer("i1", "1 + Goo()", lineNumber: 4), }; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } [Fact] public void ExpressionStaticInitializer() { var source = @" class C { static int s1 = 1 + Goo(); int i1; static int Goo() { return 1; } }"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[] { new ExpectedInitializer("s1", "1 + Goo()", lineNumber: 3), }; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = null; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } [Fact] public void InitializerOrder() { var source = @" class C { static int s1 = 1; static int s2 = 2; static int s3 = 3; int i1 = 1; int i2 = 2; int i3 = 3; }"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[] { new ExpectedInitializer("s1", "1", lineNumber: 3), new ExpectedInitializer("s2", "2", lineNumber: 4), new ExpectedInitializer("s3", "3", lineNumber: 5), }; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[] { new ExpectedInitializer("i1", "1", lineNumber: 6), new ExpectedInitializer("i2", "2", lineNumber: 7), new ExpectedInitializer("i3", "3", lineNumber: 8), }; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } [Fact] public void AllPartialClasses() { var source = @" partial class C { static int s1 = 1; int i1 = 1; } partial class C { static int s2 = 2; int i2 = 2; }"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[] { new ExpectedInitializer("s1", "1", lineNumber: 3), new ExpectedInitializer("s2", "2", lineNumber: 8), }; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[] { new ExpectedInitializer("i1", "1", lineNumber: 4), new ExpectedInitializer("i2", "2", lineNumber: 9), }; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } [Fact] public void SomePartialClasses() { var source = @" partial class C { static int s1 = 1; int i1 = 1; } partial class C { static int s2 = 2; int i2 = 2; } partial class C { static int s3; int i3; }"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[] { new ExpectedInitializer("s1", "1", lineNumber: 3), new ExpectedInitializer("s2", "2", lineNumber: 8), }; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[] { new ExpectedInitializer("i1", "1", lineNumber: 4), new ExpectedInitializer("i2", "2", lineNumber: 9), }; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } [Fact] public void Events() { var source = @" class C { static event System.Action e = MakeAction(1); event System.Action f = MakeAction(2); static System.Action MakeAction(int x) { return null; } }}"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[] { new ExpectedInitializer("e", "MakeAction(1)", lineNumber: 3), }; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[] { new ExpectedInitializer("f", "MakeAction(2)", lineNumber: 4), }; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } private static void CompileAndCheckInitializers(string source, IEnumerable<ExpectedInitializer> expectedInstanceInitializers, IEnumerable<ExpectedInitializer> expectedStaticInitializers) { var compilation = CreateCompilation(source); var syntaxTree = compilation.SyntaxTrees.First(); var typeSymbol = (SourceNamedTypeSymbol)compilation.GlobalNamespace.GetMembers("C").Single(); var boundInstanceInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.InstanceInitializers); CheckBoundInitializers(expectedInstanceInitializers, syntaxTree, boundInstanceInitializers, isStatic: false); var boundStaticInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.StaticInitializers); CheckBoundInitializers(expectedStaticInitializers, syntaxTree, boundStaticInitializers, isStatic: true); } private static void CheckBoundInitializers(IEnumerable<ExpectedInitializer> expectedInitializers, SyntaxTree syntaxTree, ImmutableArray<BoundInitializer> boundInitializers, bool isStatic) { if (expectedInitializers == null) { Assert.Equal(0, boundInitializers.Length); } else { Assert.True(!boundInitializers.IsEmpty, "Expected non-null non-empty bound initializers"); int numInitializers = expectedInitializers.Count(); Assert.Equal(numInitializers, boundInitializers.Length); int i = 0; foreach (var expectedInitializer in expectedInitializers) { var boundInit = boundInitializers[i++]; Assert.Equal(BoundKind.FieldEqualsValue, boundInit.Kind); var boundFieldInit = (BoundFieldEqualsValue)boundInit; var initValueSyntax = boundFieldInit.Value.Syntax; Assert.Same(initValueSyntax.Parent, boundInit.Syntax); Assert.Equal(expectedInitializer.InitialValue, initValueSyntax.ToFullString()); var initValueLineNumber = syntaxTree.GetLineSpan(initValueSyntax.Span).StartLinePosition.Line; Assert.Equal(expectedInitializer.LineNumber, initValueLineNumber); Assert.Equal(expectedInitializer.FieldName, boundFieldInit.Field.Name); } } } private static ImmutableArray<BoundInitializer> BindInitializersWithoutDiagnostics(SourceNamedTypeSymbol typeSymbol, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers) { DiagnosticBag diagnostics = DiagnosticBag.GetInstance(); ImportChain unused; var boundInitializers = ArrayBuilder<BoundInitializer>.GetInstance(); Binder.BindRegularCSharpFieldInitializers( typeSymbol.DeclaringCompilation, initializers, boundInitializers, new BindingDiagnosticBag(diagnostics), firstDebugImports: out unused); diagnostics.Verify(); diagnostics.Free(); return boundInitializers.ToImmutableAndFree(); } private class ExpectedInitializer { public string FieldName { get; } public string InitialValue { get; } public int LineNumber { get; } //0-indexed public ExpectedInitializer(string fieldName, string initialValue, int lineNumber) { this.FieldName = fieldName; this.InitialValue = initialValue; this.LineNumber = lineNumber; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class FieldInitializerBindingTests : CompilingTestBase { [Fact] public void NoInitializers() { var source = @" class C { static int s1; int i1; }"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = null; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = null; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } [Fact] public void ConstantInstanceInitializer() { var source = @" class C { static int s1; int i1 = 1; }"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = null; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[] { new ExpectedInitializer("i1", "1", lineNumber: 4), }; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } [Fact] public void ConstantStaticInitializer() { var source = @" class C { static int s1 = 1; int i1; }"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[] { new ExpectedInitializer("s1", "1", lineNumber: 3), }; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = null; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } [Fact] public void ExpressionInstanceInitializer() { var source = @" class C { static int s1; int i1 = 1 + Goo(); static int Goo() { return 1; } }"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = null; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[] { new ExpectedInitializer("i1", "1 + Goo()", lineNumber: 4), }; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } [Fact] public void ExpressionStaticInitializer() { var source = @" class C { static int s1 = 1 + Goo(); int i1; static int Goo() { return 1; } }"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[] { new ExpectedInitializer("s1", "1 + Goo()", lineNumber: 3), }; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = null; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } [Fact] public void InitializerOrder() { var source = @" class C { static int s1 = 1; static int s2 = 2; static int s3 = 3; int i1 = 1; int i2 = 2; int i3 = 3; }"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[] { new ExpectedInitializer("s1", "1", lineNumber: 3), new ExpectedInitializer("s2", "2", lineNumber: 4), new ExpectedInitializer("s3", "3", lineNumber: 5), }; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[] { new ExpectedInitializer("i1", "1", lineNumber: 6), new ExpectedInitializer("i2", "2", lineNumber: 7), new ExpectedInitializer("i3", "3", lineNumber: 8), }; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } [Fact] public void AllPartialClasses() { var source = @" partial class C { static int s1 = 1; int i1 = 1; } partial class C { static int s2 = 2; int i2 = 2; }"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[] { new ExpectedInitializer("s1", "1", lineNumber: 3), new ExpectedInitializer("s2", "2", lineNumber: 8), }; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[] { new ExpectedInitializer("i1", "1", lineNumber: 4), new ExpectedInitializer("i2", "2", lineNumber: 9), }; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } [Fact] public void SomePartialClasses() { var source = @" partial class C { static int s1 = 1; int i1 = 1; } partial class C { static int s2 = 2; int i2 = 2; } partial class C { static int s3; int i3; }"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[] { new ExpectedInitializer("s1", "1", lineNumber: 3), new ExpectedInitializer("s2", "2", lineNumber: 8), }; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[] { new ExpectedInitializer("i1", "1", lineNumber: 4), new ExpectedInitializer("i2", "2", lineNumber: 9), }; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } [Fact] public void Events() { var source = @" class C { static event System.Action e = MakeAction(1); event System.Action f = MakeAction(2); static System.Action MakeAction(int x) { return null; } }}"; IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[] { new ExpectedInitializer("e", "MakeAction(1)", lineNumber: 3), }; IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[] { new ExpectedInitializer("f", "MakeAction(2)", lineNumber: 4), }; CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers); } private static void CompileAndCheckInitializers(string source, IEnumerable<ExpectedInitializer> expectedInstanceInitializers, IEnumerable<ExpectedInitializer> expectedStaticInitializers) { var compilation = CreateCompilation(source); var syntaxTree = compilation.SyntaxTrees.First(); var typeSymbol = (SourceNamedTypeSymbol)compilation.GlobalNamespace.GetMembers("C").Single(); var boundInstanceInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.InstanceInitializers); CheckBoundInitializers(expectedInstanceInitializers, syntaxTree, boundInstanceInitializers, isStatic: false); var boundStaticInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.StaticInitializers); CheckBoundInitializers(expectedStaticInitializers, syntaxTree, boundStaticInitializers, isStatic: true); } private static void CheckBoundInitializers(IEnumerable<ExpectedInitializer> expectedInitializers, SyntaxTree syntaxTree, ImmutableArray<BoundInitializer> boundInitializers, bool isStatic) { if (expectedInitializers == null) { Assert.Equal(0, boundInitializers.Length); } else { Assert.True(!boundInitializers.IsEmpty, "Expected non-null non-empty bound initializers"); int numInitializers = expectedInitializers.Count(); Assert.Equal(numInitializers, boundInitializers.Length); int i = 0; foreach (var expectedInitializer in expectedInitializers) { var boundInit = boundInitializers[i++]; Assert.Equal(BoundKind.FieldEqualsValue, boundInit.Kind); var boundFieldInit = (BoundFieldEqualsValue)boundInit; var initValueSyntax = boundFieldInit.Value.Syntax; Assert.Same(initValueSyntax.Parent, boundInit.Syntax); Assert.Equal(expectedInitializer.InitialValue, initValueSyntax.ToFullString()); var initValueLineNumber = syntaxTree.GetLineSpan(initValueSyntax.Span).StartLinePosition.Line; Assert.Equal(expectedInitializer.LineNumber, initValueLineNumber); Assert.Equal(expectedInitializer.FieldName, boundFieldInit.Field.Name); } } } private static ImmutableArray<BoundInitializer> BindInitializersWithoutDiagnostics(SourceNamedTypeSymbol typeSymbol, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers) { DiagnosticBag diagnostics = DiagnosticBag.GetInstance(); ImportChain unused; var boundInitializers = ArrayBuilder<BoundInitializer>.GetInstance(); Binder.BindRegularCSharpFieldInitializers( typeSymbol.DeclaringCompilation, initializers, boundInitializers, new BindingDiagnosticBag(diagnostics), firstDebugImports: out unused); diagnostics.Verify(); diagnostics.Free(); return boundInitializers.ToImmutableAndFree(); } private class ExpectedInitializer { public string FieldName { get; } public string InitialValue { get; } public int LineNumber { get; } //0-indexed public ExpectedInitializer(string fieldName, string initialValue, int lineNumber) { this.FieldName = fieldName; this.InitialValue = initialValue; this.LineNumber = lineNumber; } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Test/Semantic/Utilities/ValueSetTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { using static BinaryOperatorKind; using static Microsoft.CodeAnalysis.CSharp.ValueSetFactory; /// <summary> /// Test some internal implementation data structures used in <see cref="DecisionDagBuilder"/>. /// </summary> public class ValueSetTests { private static readonly Random Random = new Random(); [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(-1)] [InlineData(-2)] [InlineData(-3)] [InlineData(-4)] [InlineData(int.MinValue)] [InlineData(int.MaxValue)] public void TestGE_01(int i1) { IValueSet<int> values = ForInt.Related(GreaterThanOrEqual, i1); Assert.Equal($"[{i1}..{int.MaxValue}]", values.ToString()); } [Fact] public void TestGE_02() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue, int.MaxValue); IValueSet<int> values = ForInt.Related(GreaterThanOrEqual, i1); Assert.Equal($"[{i1}..{int.MaxValue}]", values.ToString()); } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(-1)] [InlineData(-2)] [InlineData(-3)] [InlineData(-4)] [InlineData(int.MinValue)] [InlineData(int.MaxValue)] public void TestGT_01(int i1) { IValueSet<int> values = ForInt.Related(GreaterThan, i1); Assert.Equal((i1 == int.MaxValue) ? "" : $"[{i1 + 1}..{int.MaxValue}]", values.ToString()); } [Fact] public void TestGT_02() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue, int.MaxValue); IValueSet<int> values = ForInt.Related(GreaterThan, i1); Assert.Equal($"[{i1 + 1}..{int.MaxValue}]", values.ToString()); } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(-1)] [InlineData(-2)] [InlineData(-3)] [InlineData(-4)] [InlineData(int.MinValue)] [InlineData(int.MaxValue)] public void TestLE_01(int i1) { IValueSet<int> values = ForInt.Related(LessThanOrEqual, i1); Assert.Equal($"[{int.MinValue}..{i1}]", values.ToString()); } [Fact] public void TestLE_02() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue, int.MaxValue) + 1; IValueSet<int> values = ForInt.Related(LessThanOrEqual, i1); Assert.Equal($"[{int.MinValue}..{i1}]", values.ToString()); } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(-1)] [InlineData(-2)] [InlineData(-3)] [InlineData(-4)] [InlineData(int.MinValue)] [InlineData(int.MaxValue)] public void TestLT_01(int i1) { IValueSet<int> values = ForInt.Related(LessThan, i1); Assert.Equal((i1 == int.MinValue) ? "" : $"[{int.MinValue}..{i1 - 1}]", values.ToString()); } [Fact] public void TestLT_02() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue, int.MaxValue) + 1; IValueSet<int> values = ForInt.Related(LessThan, i1); Assert.Equal($"[{int.MinValue}..{i1 - 1}]", values.ToString()); } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(-1)] [InlineData(-2)] [InlineData(-3)] [InlineData(-4)] [InlineData(int.MinValue)] [InlineData(int.MaxValue)] public void TestEQ_01(int i1) { IValueSet<int> values = ForInt.Related(Equal, i1); Assert.Equal($"[{i1}..{i1}]", values.ToString()); } [Fact] public void TestEQ_02() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue, int.MaxValue); IValueSet<int> values = ForInt.Related(Equal, i1); Assert.Equal($"[{i1}..{i1}]", values.ToString()); } } [Fact] public void TestIntersect_01() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue + 1, int.MaxValue); int i2 = Random.Next(int.MinValue, int.MaxValue); if (i1 > i2) (i1, i2) = (i2, i1); IValueSet<int> values1 = ForInt.Related(GreaterThanOrEqual, i1).Intersect(ForInt.Related(LessThanOrEqual, i2)); Assert.Equal($"[{i1}..{i2}]", values1.ToString()); IValueSet<int> values2 = ForInt.Related(LessThanOrEqual, i2).Intersect(ForInt.Related(GreaterThanOrEqual, i1)); Assert.Equal(values1, values2); } } [Fact] public void TestIntersect_02() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue + 1, int.MaxValue); int i2 = Random.Next(int.MinValue, int.MaxValue); if (i1 < i2) (i1, i2) = (i2, i1); if (i1 == i2) continue; IValueSet<int> values1 = ForInt.Related(GreaterThanOrEqual, i1).Intersect(ForInt.Related(LessThanOrEqual, i2)); Assert.Equal($"", values1.ToString()); IValueSet<int> values2 = ForInt.Related(LessThanOrEqual, i2).Intersect(ForInt.Related(GreaterThanOrEqual, i1)); Assert.Equal(values1, values2); } } [Fact] public void TestUnion_01() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue + 1, int.MaxValue); int i2 = Random.Next(int.MinValue, int.MaxValue); if (i1 > i2) (i1, i2) = (i2, i1); if ((i1 + 1) >= i2) continue; IValueSet<int> values1 = ForInt.Related(LessThanOrEqual, i1).Union(ForInt.Related(GreaterThanOrEqual, i2)); Assert.Equal($"[{int.MinValue}..{i1}],[{i2}..{int.MaxValue}]", values1.ToString()); IValueSet<int> values2 = ForInt.Related(GreaterThanOrEqual, i2).Union(ForInt.Related(LessThanOrEqual, i1)); Assert.Equal(values1, values2); } } [Fact] public void TestUnion_02() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue + 1, int.MaxValue); int i2 = Random.Next(int.MinValue, int.MaxValue); if (i1 < i2) (i1, i2) = (i2, i1); IValueSet<int> values1 = ForInt.Related(LessThanOrEqual, i1).Union(ForInt.Related(GreaterThanOrEqual, i2)); Assert.Equal($"[{int.MinValue}..{int.MaxValue}]", values1.ToString()); IValueSet<int> values2 = ForInt.Related(GreaterThanOrEqual, i2).Union(ForInt.Related(LessThanOrEqual, i1)); Assert.Equal(values1, values2); } } [Fact] public void TestComplement_01() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue + 1, int.MaxValue); int i2 = Random.Next(int.MinValue, int.MaxValue); if (i1 > i2) (i1, i2) = (i2, i1); if ((i1 + 1) >= i2) continue; IValueSet<int> values1 = ForInt.Related(LessThanOrEqual, i1).Union(ForInt.Related(GreaterThanOrEqual, i2)); Assert.Equal($"[{int.MinValue}..{i1}],[{i2}..{int.MaxValue}]", values1.ToString()); IValueSet<int> values2 = values1.Complement(); Assert.Equal(values1, values2.Complement()); Assert.Equal($"[{i1 + 1}..{i2 - 1}]", values2.ToString()); } } [Fact] public void TestAny_01() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue, int.MaxValue); int i2 = Random.Next(int.MinValue, int.MaxValue); if (i1 > i2) (i1, i2) = (i2, i1); IValueSet<int> values = ForInt.Related(GreaterThanOrEqual, i1).Intersect(ForInt.Related(LessThanOrEqual, i2)); Assert.Equal($"[{i1}..{i2}]", values.ToString()); test(int.MinValue); if (i1 != int.MinValue) test(i1 - 1); test(i1); test(i1 + 1); test(int.MaxValue); if (i2 != int.MinValue) test(i2 - 1); test(i2); test(i2 + 1); void test(int val) { Assert.Equal(val >= i1 && val <= i2, values.Any(Equal, val)); Assert.Equal(val >= i1, values.Any(LessThanOrEqual, val)); Assert.Equal(val > i1, values.Any(LessThan, val)); Assert.Equal(val <= i2, values.Any(GreaterThanOrEqual, val)); Assert.Equal(i2 > val, values.Any(GreaterThan, val)); } } } [Fact] public void TestIsEmpty_01() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue, int.MaxValue); int i2 = Random.Next(int.MinValue, int.MaxValue); IValueSet<int> values = ForInt.Related(GreaterThanOrEqual, i1).Intersect(ForInt.Related(LessThanOrEqual, i2)); Assert.Equal(values.ToString().Length == 0, values.IsEmpty); } } [Fact] public void TestDouble_01() { for (int i = 0; i < 100; i++) { double d1 = Random.NextDouble() * 100 - 50; double d2 = Random.NextDouble() * 100 - 50; if (d1 > d2) (d1, d2) = (d2, d1); IValueSet<double> values = ForDouble.Related(GreaterThanOrEqual, d1).Intersect(ForDouble.Related(LessThanOrEqual, d2)); Assert.Equal(FormattableString.Invariant($"[{d1:G17}..{d2:G17}]"), values.ToString()); } } [Fact] public void TestChar_01() { IValueSet<char> gea1 = ForChar.Related(GreaterThanOrEqual, 'a'); IValueSet<char> lez1 = ForChar.Related(LessThanOrEqual, 'z'); IValueSet<char> gea2 = ForChar.Related(GreaterThanOrEqual, 'A'); IValueSet<char> lez2 = ForChar.Related(LessThanOrEqual, 'Z'); var letters = gea1.Intersect(lez1).Union(gea2.Intersect(lez2)); Assert.Equal("['A'..'Z'],['a'..'z']", letters.ToString()); } [Fact] public void TestDouble_02() { Assert.Equal("[-Inf..-Inf]", ForDouble.Related(LessThan, double.MinValue).ToString()); var lt = ForDouble.Related(LessThan, 0.0); Assert.Equal(FormattableString.Invariant($"[-Inf..{-double.Epsilon:G17}]"), lt.ToString()); var gt = ForDouble.Related(GreaterThan, 0.0); Assert.Equal(FormattableString.Invariant($"[{double.Epsilon:G17}..Inf]"), gt.ToString()); var eq = ForDouble.Related(Equal, 0.0); Assert.Equal("[0..0]", eq.ToString()); var none = lt.Complement().Intersect(gt.Complement()).Intersect(eq.Complement()); Assert.Equal("NaN", none.ToString()); Assert.False(none.IsEmpty); } [Fact] public void TestFloat_01() { Assert.Equal("[-Inf..-Inf]", ForFloat.Related(LessThan, float.MinValue).ToString()); var lt = ForFloat.Related(LessThan, 0.0f); Assert.Equal(FormattableString.Invariant($"[-Inf..{-float.Epsilon:G9}]"), lt.ToString()); var gt = ForFloat.Related(GreaterThan, 0.0f); Assert.Equal(FormattableString.Invariant($"[{float.Epsilon:G9}..Inf]"), gt.ToString()); var eq = ForFloat.Related(Equal, 0.0f); Assert.Equal("[0..0]", eq.ToString()); var none = lt.Complement().Intersect(gt.Complement()).Intersect(eq.Complement()); Assert.Equal("NaN", none.ToString()); Assert.False(none.IsEmpty); } [Fact] public void TestDouble_03() { Assert.Equal("NaN", ForDouble.Related(Equal, double.NaN).ToString()); Assert.Equal("NaN", ForFloat.Related(Equal, float.NaN).ToString()); Assert.True(ForDouble.Related(Equal, double.NaN).Any(Equal, double.NaN)); Assert.True(ForFloat.Related(Equal, float.NaN).Any(Equal, float.NaN)); Assert.Equal("[Inf..Inf]", ForDouble.Related(Equal, double.PositiveInfinity).ToString()); Assert.Equal("[Inf..Inf]", ForFloat.Related(Equal, float.PositiveInfinity).ToString()); Assert.Equal("[-Inf..-Inf]", ForDouble.Related(Equal, double.NegativeInfinity).ToString()); Assert.Equal("[-Inf..-Inf]", ForFloat.Related(Equal, float.NegativeInfinity).ToString()); } [Fact] public void TestDouble_04() { var neg = ForDouble.Related(LessThan, 0.0); Assert.True(neg.Any(LessThan, double.MinValue)); Assert.False(neg.Any(GreaterThan, double.MaxValue)); var mi = ForDouble.Related(Equal, double.NegativeInfinity); Assert.True(mi.All(LessThan, 0.0)); Assert.True(mi.Any(LessThan, 0.0)); Assert.True(mi.All(LessThanOrEqual, 0.0)); Assert.True(mi.Any(LessThanOrEqual, 0.0)); Assert.False(mi.All(GreaterThan, 0.0)); Assert.False(mi.Any(GreaterThan, 0.0)); Assert.False(mi.All(GreaterThanOrEqual, 0.0)); Assert.False(mi.Any(GreaterThanOrEqual, 0.0)); var i = ForDouble.Related(Equal, double.PositiveInfinity); Assert.False(i.All(LessThan, 0.0)); Assert.False(i.Any(LessThan, 0.0)); Assert.False(i.All(LessThanOrEqual, 0.0)); Assert.False(i.Any(LessThanOrEqual, 0.0)); Assert.True(i.All(GreaterThan, 0.0)); Assert.True(i.Any(GreaterThan, 0.0)); Assert.True(i.All(GreaterThanOrEqual, 0.0)); Assert.True(i.Any(GreaterThanOrEqual, 0.0)); } [Fact] public void TestString_01() { var notaset = ForString.Related(Equal, "a").Complement(); var bset = ForString.Related(Equal, "b"); var intersect = bset.Intersect(notaset); Assert.False(intersect.Any(Equal, "c")); } [Fact] public void TestBool_Cov_01() { var t = ForBool.Related(Equal, true); var f = ForBool.Related(Equal, false); var em = t.Intersect(f); Assert.True(em.IsEmpty); var q = t.Intersect(t); Assert.Same(t, q); IValueSet b = t; Assert.Same(b.Intersect(b), b); Assert.Same(b.Union(b), b); } [Fact] public void TestByte_Cov_01() { var s = ForByte.Related(GreaterThan, 10).Intersect(ForByte.Related(LessThan, 100)); Assert.Equal("[11..99]", s.ToString()); } [Fact] public void TestString_Cov_01() { var s1 = ForString.Related(Equal, "a"); var s2 = ForString.Related(Equal, "b"); Assert.True(s1.Intersect(s2).IsEmpty); Assert.True(s1.Complement().Union(s2.Complement()).Complement().IsEmpty); Assert.Equal(s1.Union(s2).Complement(), s1.Complement().Intersect(s2.Complement())); IValueSet b = s1; Assert.Same(b.Intersect(b), b); Assert.Same(b.Union(b), b); Assert.False(s1.Union(s2).All(Equal, "a")); } [Fact] public void TestDouble_Cov_01() { var s1 = ForDouble.Related(LessThan, 3.14d); IValueSet b = s1; Assert.Same(s1, s1.Intersect(s1)); Assert.Same(s1, s1.Union(s1)); var s2 = ForDouble.Related(GreaterThan, 31.4d); var s3 = b.Complement().Intersect(s2.Complement()); Assert.Equal("NaN,[3.1400000000000001..31.399999999999999]", s3.ToString()); var s4 = b.Union(s2).Complement(); Assert.Equal(s3, s4); } [Fact] public void TestLong_Cov_01() { var s1 = ForLong.Related(LessThan, 2); Assert.Equal($"[{long.MinValue}..1]", s1.ToString()); Assert.True(s1.All(LessThan, 2)); Assert.True(s1.All(LessThanOrEqual, 1)); Assert.False(s1.All(GreaterThan, 0)); Assert.False(s1.All(GreaterThanOrEqual, 0)); Assert.False(s1.All(Equal, 0)); Assert.False(s1.All(LessThan, -10)); Assert.False(s1.All(LessThanOrEqual, -10)); Assert.False(s1.All(GreaterThan, -10)); Assert.False(s1.All(GreaterThanOrEqual, -10)); Assert.False(s1.All(Equal, -10)); Assert.True(s1.All(LessThan, 10)); Assert.True(s1.All(LessThanOrEqual, 10)); Assert.False(s1.All(GreaterThan, 10)); Assert.False(s1.All(GreaterThanOrEqual, 10)); Assert.False(s1.All(Equal, 10)); var s2 = ForLong.Related(GreaterThan, -5).Intersect(s1); Assert.Equal($"[-4..1]", s2.ToString()); Assert.False(s2.All(LessThan, -10)); Assert.False(s2.All(LessThanOrEqual, -10)); Assert.True(s2.All(GreaterThan, -10)); Assert.True(s2.All(GreaterThanOrEqual, -10)); Assert.False(s2.All(Equal, -10)); Assert.True(s2.All(LessThan, 10)); Assert.True(s2.All(LessThanOrEqual, 10)); Assert.False(s2.All(GreaterThan, 10)); Assert.False(s2.All(GreaterThanOrEqual, 10)); Assert.False(s2.All(Equal, 10)); } [Fact] public void TestNext_Cov_01() { Assert.Equal("[10..100]", ForSByte.Related(GreaterThanOrEqual, 10).Intersect(ForSByte.Related(LessThanOrEqual, 100)).ToString()); Assert.Equal("[10..100]", ForShort.Related(GreaterThanOrEqual, 10).Intersect(ForShort.Related(LessThanOrEqual, 100)).ToString()); Assert.Equal("[10..100]", ForUInt.Related(GreaterThanOrEqual, 10).Intersect(ForUInt.Related(LessThanOrEqual, 100)).ToString()); Assert.Equal("[10..100]", ForULong.Related(GreaterThanOrEqual, 10).Intersect(ForULong.Related(LessThanOrEqual, 100)).ToString()); Assert.Equal("[10..100]", ForUShort.Related(GreaterThanOrEqual, 10).Intersect(ForUShort.Related(LessThanOrEqual, 100)).ToString()); Assert.Equal("[10..100]", ForFloat.Related(GreaterThanOrEqual, 10).Intersect(ForFloat.Related(LessThanOrEqual, 100)).ToString()); Assert.Equal("[-100..-10]", ForFloat.Related(GreaterThanOrEqual, -100).Intersect(ForFloat.Related(LessThanOrEqual, -10)).ToString()); Assert.Equal("[-10..10]", ForFloat.Related(GreaterThanOrEqual, -10).Intersect(ForFloat.Related(LessThanOrEqual, 10)).ToString()); } [Fact] public void TestAPI_01() { Assert.Same(ForByte, ForSpecialType(SpecialType.System_Byte)); Assert.Same(ForSByte, ForSpecialType(SpecialType.System_SByte)); Assert.Same(ForShort, ForSpecialType(SpecialType.System_Int16)); Assert.Same(ForUShort, ForSpecialType(SpecialType.System_UInt16)); Assert.Same(ForInt, ForSpecialType(SpecialType.System_Int32)); Assert.Same(ForUInt, ForSpecialType(SpecialType.System_UInt32)); Assert.Same(ForLong, ForSpecialType(SpecialType.System_Int64)); Assert.Same(ForULong, ForSpecialType(SpecialType.System_UInt64)); Assert.Same(ForFloat, ForSpecialType(SpecialType.System_Single)); Assert.Same(ForDouble, ForSpecialType(SpecialType.System_Double)); Assert.Same(ForString, ForSpecialType(SpecialType.System_String)); Assert.Same(ForDecimal, ForSpecialType(SpecialType.System_Decimal)); Assert.Same(ForChar, ForSpecialType(SpecialType.System_Char)); Assert.Same(ForBool, ForSpecialType(SpecialType.System_Boolean)); Assert.Same(ForNint, ForSpecialType(SpecialType.System_IntPtr, isNative: true)); Assert.Same(ForNuint, ForSpecialType(SpecialType.System_UIntPtr, isNative: true)); Assert.Null(ForSpecialType(SpecialType.System_Enum)); } [Fact] public void TestDecimalRelations_01() { Assert.Equal("[-79228162514264337593543950335..-0.0000000000000000000000000001]", ForDecimal.Related(LessThan, 0.0m).ToString()); Assert.Equal("[-79228162514264337593543950335..0.0000000000000000000000000000]", ForDecimal.Related(LessThanOrEqual, 0.0m).ToString()); Assert.Equal("[0.0000000000000000000000000001..79228162514264337593543950335]", ForDecimal.Related(GreaterThan, 0.0m).ToString()); Assert.Equal("[0.0000000000000000000000000000..79228162514264337593543950335]", ForDecimal.Related(GreaterThanOrEqual, 0.0m).ToString()); } [Fact] public void TestNintRelations_01() { Assert.Equal("Small,[-2147483648..9]", ForNint.Related(LessThan, 10).ToString()); Assert.Equal("Small,[-2147483648..10]", ForNint.Related(LessThanOrEqual, 10).ToString()); Assert.Equal("[11..2147483647],Large", ForNint.Related(GreaterThan, 10).ToString()); Assert.Equal("[10..2147483647],Large", ForNint.Related(GreaterThanOrEqual, 10).ToString()); } [Fact] public void TestNuintRelations_01() { Assert.Equal("[0..9]", ForNuint.Related(LessThan, 10).ToString()); Assert.Equal("[0..10]", ForNuint.Related(LessThanOrEqual, 10).ToString()); Assert.Equal("[11..4294967295],Large", ForNuint.Related(GreaterThan, 10).ToString()); Assert.Equal("[10..4294967295],Large", ForNuint.Related(GreaterThanOrEqual, 10).ToString()); } [Fact] public void TestDecimalEdges_01() { for (byte scale = 0; scale < 29; scale++) { var l = new decimal(~0, ~0, ~0, false, scale); check(l); l = new decimal(~0, ~0, ~0, true, scale); check(l); } for (byte scale = 0; scale < 29; scale++) { var l = new decimal(unchecked((int)0x99999999), unchecked((int)0x99999999), 0x19999999, false, scale); check(l); l = new decimal(unchecked((int)0x99999999), unchecked((int)0x99999999), 0x19999999, true, scale); check(l); l = new decimal(unchecked((int)0x99999998), unchecked((int)0x99999999), 0x19999999, false, scale); check(l); l = new decimal(unchecked((int)0x99999998), unchecked((int)0x99999999), 0x19999999, true, scale); check(l); l = new decimal(unchecked((int)0x9999999A), unchecked((int)0x99999999), 0x19999999, false, scale); check(l); l = new decimal(unchecked((int)0x9999999A), unchecked((int)0x99999999), 0x19999999, true, scale); check(l); } for (int high = 0; high < 2; high++) { for (int mid = 0; mid < 2; mid++) { for (int p2 = 0; p2 < 32; p2++) { int low = 1 << p2; var l = new decimal(low, mid, high, false, 28); check(l); l = new decimal(low, mid, high, true, 28); check(l); } } } void check(decimal d) { Assert.False(ForDecimal.Related(LessThan, d).Any(Equal, d)); Assert.True(ForDecimal.Related(LessThanOrEqual, d).Any(Equal, d)); Assert.False(ForDecimal.Related(GreaterThan, d).Any(Equal, d)); Assert.True(ForDecimal.Related(GreaterThanOrEqual, d).Any(Equal, d)); } } [Fact] public void TestNumbers_Fuzz_01() { var Random = new Random(123445); foreach (var fac in new IValueSetFactory[] { ForByte, ForSByte, ForShort, ForUShort, ForInt, ForUInt, ForLong, ForULong, ForFloat, ForDouble, ForDecimal, ForNint, ForNuint, ForChar, ForLength, }) { for (int i = 0; i < 100; i++) { var s1 = fac.Random(10, Random); var s2 = fac.Random(10, Random); var u1 = s1.Union(s2); var u2 = s1.Complement().Intersect(s2.Complement()).Complement(); Assert.Equal(u1, u2); var i1 = s1.Intersect(s2); var i2 = s1.Complement().Union(s2.Complement()).Complement(); Assert.Equal(i1, i2); } } } [Fact] public void TestNumbers_Fuzz_02() { foreach (var fac in new IValueSetFactory[] { ForByte, ForSByte, ForShort, ForUShort, ForInt, ForUInt, ForLong, ForULong, ForDecimal, ForNint, ForNuint, ForChar, ForLength }) { for (int i = 0; i < 100; i++) { ConstantValue value = fac.RandomValue(Random); var s1 = fac.Related(LessThan, value); var s2 = fac.Related(GreaterThanOrEqual, value); Assert.Equal(s1.Complement(), s2); Assert.Equal(s2.Complement(), s1); Assert.True(s2.Any(Equal, value)); Assert.False(s1.Any(Equal, value)); Assert.True(s1.All(LessThan, value)); Assert.False(s2.Any(LessThan, value)); Assert.True(s2.All(GreaterThanOrEqual, value)); Assert.False(s1.Any(GreaterThanOrEqual, value)); s1 = fac.Related(GreaterThan, value); s2 = fac.Related(LessThanOrEqual, value); Assert.Equal(s1.Complement(), s2); Assert.Equal(s2.Complement(), s1); Assert.True(s2.Any(Equal, value)); Assert.False(s1.Any(Equal, value)); Assert.True(s1.All(GreaterThan, value)); Assert.False(s2.Any(GreaterThan, value)); Assert.True(s2.All(LessThanOrEqual, value)); Assert.False(s1.Any(LessThanOrEqual, value)); } } } [Fact] public void TestString_Fuzz_02() { for (int i = 0; i < 100; i++) { var s1 = ForString.Random(9, Random); var s2 = ForString.Random(11, Random); Assert.Equal(s1.Complement().Complement(), s1); var u1 = s1.Union(s2); var u2 = s1.Complement().Intersect(s2.Complement()).Complement(); var u3 = s2.Union(s1); var u4 = s2.Complement().Intersect(s1.Complement()).Complement(); Assert.Equal(u1, u2); Assert.Equal(u1, u3); Assert.Equal(u1, u4); var i1 = s1.Intersect(s2); var i2 = s1.Complement().Union(s2.Complement()).Complement(); var i3 = s2.Intersect(s1); var i4 = s2.Complement().Union(s1.Complement()).Complement(); Assert.Equal(i1, i2); Assert.Equal(i1, i3); Assert.Equal(i1, i4); s1 = s1.Complement(); u1 = s1.Union(s2); u2 = s1.Complement().Intersect(s2.Complement()).Complement(); u3 = s2.Union(s1); u4 = s2.Complement().Intersect(s1.Complement()).Complement(); Assert.Equal(u1, u2); Assert.Equal(u1, u3); Assert.Equal(u1, u4); i1 = s1.Intersect(s2); i2 = s1.Complement().Union(s2.Complement()).Complement(); i3 = s2.Intersect(s1); i4 = s2.Complement().Union(s1.Complement()).Complement(); Assert.Equal(i1, i2); Assert.Equal(i1, i3); Assert.Equal(i1, i4); s2 = s2.Complement(); u1 = s1.Union(s2); u2 = s1.Complement().Intersect(s2.Complement()).Complement(); u3 = s2.Union(s1); u4 = s2.Complement().Intersect(s1.Complement()).Complement(); Assert.Equal(u1, u2); Assert.Equal(u1, u3); Assert.Equal(u1, u4); i1 = s1.Intersect(s2); i2 = s1.Complement().Union(s2.Complement()).Complement(); i3 = s2.Intersect(s1); i4 = s2.Complement().Union(s1.Complement()).Complement(); Assert.Equal(i1, i2); Assert.Equal(i1, i3); Assert.Equal(i1, i4); } } [Fact] public void TestAnyFuzz_01() { for (int i = 0; i < 100; i++) { var s1 = ForInt.Related(BinaryOperatorKind.Equal, i); Assert.True(s1.Any(LessThan, i + 1)); Assert.False(s1.Any(LessThan, i)); Assert.False(s1.Any(LessThan, i - 1)); Assert.True(s1.Any(LessThanOrEqual, i + 1)); Assert.True(s1.Any(LessThanOrEqual, i)); Assert.False(s1.Any(LessThanOrEqual, i - 1)); Assert.False(s1.Any(GreaterThan, i + 1)); Assert.False(s1.Any(GreaterThan, i)); Assert.True(s1.Any(GreaterThan, i - 1)); Assert.False(s1.Any(GreaterThanOrEqual, i + 1)); Assert.True(s1.Any(GreaterThanOrEqual, i)); Assert.True(s1.Any(GreaterThanOrEqual, i - 1)); } } [Fact] public void TestAnyFuzz_02() { for (int i = 0; i < 100; i++) { int j = Random.Next(); var s1 = ForInt.Related(BinaryOperatorKind.Equal, j); Assert.True(s1.Any(LessThan, j + 1)); Assert.False(s1.Any(LessThan, j)); Assert.False(s1.Any(LessThan, j - 1)); Assert.True(s1.Any(LessThanOrEqual, j + 1)); Assert.True(s1.Any(LessThanOrEqual, j)); Assert.False(s1.Any(LessThanOrEqual, j - 1)); Assert.False(s1.Any(GreaterThan, j + 1)); Assert.False(s1.Any(GreaterThan, j)); Assert.True(s1.Any(GreaterThan, j - 1)); Assert.False(s1.Any(GreaterThanOrEqual, j + 1)); Assert.True(s1.Any(GreaterThanOrEqual, j)); Assert.True(s1.Any(GreaterThanOrEqual, j - 1)); } } [Fact] public void TestAllFuzz_01() { for (int i = 0; i < 100; i++) { var s1 = ForInt.Related(BinaryOperatorKind.LessThan, i); Assert.True(s1.All(LessThan, i + 1)); Assert.True(s1.All(LessThan, i)); Assert.False(s1.All(LessThan, i - 1)); Assert.True(s1.All(LessThanOrEqual, i + 1)); Assert.True(s1.All(LessThanOrEqual, i)); Assert.True(s1.All(LessThanOrEqual, i - 1)); Assert.False(s1.All(LessThanOrEqual, i - 2)); s1 = ForInt.Related(BinaryOperatorKind.GreaterThan, i); Assert.False(s1.All(GreaterThan, i + 1)); Assert.True(s1.All(GreaterThan, i)); Assert.True(s1.All(GreaterThan, i - 1)); Assert.False(s1.All(GreaterThanOrEqual, i + 2)); Assert.True(s1.All(GreaterThanOrEqual, i + 1)); Assert.True(s1.All(GreaterThanOrEqual, i)); Assert.True(s1.All(GreaterThanOrEqual, i - 1)); } } [Fact] public void TestAllFuzz_02() { for (int i = 0; i < 100; i++) { int j = Random.Next(0, int.MaxValue - 1); var s1 = ForInt.Related(BinaryOperatorKind.LessThan, j); Assert.True(s1.All(LessThan, j + 1)); Assert.True(s1.All(LessThan, j)); Assert.False(s1.All(LessThan, j - 1)); Assert.True(s1.All(LessThanOrEqual, j + 1)); Assert.True(s1.All(LessThanOrEqual, j)); Assert.True(s1.All(LessThanOrEqual, j - 1)); Assert.False(s1.All(LessThanOrEqual, j - 2)); s1 = ForInt.Related(BinaryOperatorKind.GreaterThan, j); Assert.False(s1.All(GreaterThan, j + 1)); Assert.True(s1.All(GreaterThan, j)); Assert.True(s1.All(GreaterThan, j - 1)); Assert.False(s1.All(GreaterThanOrEqual, j + 2)); Assert.True(s1.All(GreaterThanOrEqual, j + 1)); Assert.True(s1.All(GreaterThanOrEqual, j)); Assert.True(s1.All(GreaterThanOrEqual, j - 1)); } } [Fact] public void TestAllFuzz_03() { for (int i = 0; i < 100; i++) { var s1 = ForInt.Related(BinaryOperatorKind.Equal, i); Assert.True(s1.All(LessThan, i + 1)); Assert.False(s1.All(LessThan, i)); Assert.False(s1.All(LessThan, i - 1)); Assert.True(s1.All(LessThanOrEqual, i + 1)); Assert.True(s1.All(LessThanOrEqual, i)); Assert.False(s1.All(LessThanOrEqual, i - 1)); Assert.False(s1.All(GreaterThan, i + 1)); Assert.False(s1.All(GreaterThan, i)); Assert.True(s1.All(GreaterThan, i - 1)); Assert.False(s1.All(GreaterThanOrEqual, i + 1)); Assert.True(s1.All(GreaterThanOrEqual, i)); Assert.True(s1.All(GreaterThanOrEqual, i - 1)); } } [Fact] public void TestAllFuzz_04() { for (int i = 0; i < 100; i++) { int j = Random.Next(0, int.MaxValue - 1); var s1 = ForInt.Related(BinaryOperatorKind.Equal, j); Assert.True(s1.All(LessThan, j + 1)); Assert.False(s1.All(LessThan, j)); Assert.False(s1.All(LessThan, j - 1)); Assert.True(s1.All(LessThanOrEqual, j + 1)); Assert.True(s1.All(LessThanOrEqual, j)); Assert.False(s1.All(LessThanOrEqual, j - 1)); Assert.False(s1.All(GreaterThan, j + 1)); Assert.False(s1.All(GreaterThan, j)); Assert.True(s1.All(GreaterThan, j - 1)); Assert.False(s1.All(GreaterThanOrEqual, j + 1)); Assert.True(s1.All(GreaterThanOrEqual, j)); Assert.True(s1.All(GreaterThanOrEqual, j - 1)); } } [Fact] public void DoNotCrashOnBadInput() { // For error recovery, do not throw exceptions on bad inputs. var ctors = new IValueSetFactory[] { ForByte, ForSByte, ForChar, ForShort, ForUShort, ForInt, ForUInt, ForLong, ForULong, ForBool, ForFloat, ForDouble, ForString, ForDecimal, ForNint, ForNuint, ForLength, }; ConstantValue badConstant = ConstantValue.Bad; foreach (IValueSetFactory fac in ctors) { foreach (BinaryOperatorKind relation in new[] { LessThan, Equal, NotEqual }) { IValueSet set = fac.Related(relation, badConstant); _ = set.All(relation, badConstant); _ = set.Any(relation, badConstant); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { using static BinaryOperatorKind; using static Microsoft.CodeAnalysis.CSharp.ValueSetFactory; /// <summary> /// Test some internal implementation data structures used in <see cref="DecisionDagBuilder"/>. /// </summary> public class ValueSetTests { private static readonly Random Random = new Random(); [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(-1)] [InlineData(-2)] [InlineData(-3)] [InlineData(-4)] [InlineData(int.MinValue)] [InlineData(int.MaxValue)] public void TestGE_01(int i1) { IValueSet<int> values = ForInt.Related(GreaterThanOrEqual, i1); Assert.Equal($"[{i1}..{int.MaxValue}]", values.ToString()); } [Fact] public void TestGE_02() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue, int.MaxValue); IValueSet<int> values = ForInt.Related(GreaterThanOrEqual, i1); Assert.Equal($"[{i1}..{int.MaxValue}]", values.ToString()); } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(-1)] [InlineData(-2)] [InlineData(-3)] [InlineData(-4)] [InlineData(int.MinValue)] [InlineData(int.MaxValue)] public void TestGT_01(int i1) { IValueSet<int> values = ForInt.Related(GreaterThan, i1); Assert.Equal((i1 == int.MaxValue) ? "" : $"[{i1 + 1}..{int.MaxValue}]", values.ToString()); } [Fact] public void TestGT_02() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue, int.MaxValue); IValueSet<int> values = ForInt.Related(GreaterThan, i1); Assert.Equal($"[{i1 + 1}..{int.MaxValue}]", values.ToString()); } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(-1)] [InlineData(-2)] [InlineData(-3)] [InlineData(-4)] [InlineData(int.MinValue)] [InlineData(int.MaxValue)] public void TestLE_01(int i1) { IValueSet<int> values = ForInt.Related(LessThanOrEqual, i1); Assert.Equal($"[{int.MinValue}..{i1}]", values.ToString()); } [Fact] public void TestLE_02() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue, int.MaxValue) + 1; IValueSet<int> values = ForInt.Related(LessThanOrEqual, i1); Assert.Equal($"[{int.MinValue}..{i1}]", values.ToString()); } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(-1)] [InlineData(-2)] [InlineData(-3)] [InlineData(-4)] [InlineData(int.MinValue)] [InlineData(int.MaxValue)] public void TestLT_01(int i1) { IValueSet<int> values = ForInt.Related(LessThan, i1); Assert.Equal((i1 == int.MinValue) ? "" : $"[{int.MinValue}..{i1 - 1}]", values.ToString()); } [Fact] public void TestLT_02() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue, int.MaxValue) + 1; IValueSet<int> values = ForInt.Related(LessThan, i1); Assert.Equal($"[{int.MinValue}..{i1 - 1}]", values.ToString()); } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(-1)] [InlineData(-2)] [InlineData(-3)] [InlineData(-4)] [InlineData(int.MinValue)] [InlineData(int.MaxValue)] public void TestEQ_01(int i1) { IValueSet<int> values = ForInt.Related(Equal, i1); Assert.Equal($"[{i1}..{i1}]", values.ToString()); } [Fact] public void TestEQ_02() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue, int.MaxValue); IValueSet<int> values = ForInt.Related(Equal, i1); Assert.Equal($"[{i1}..{i1}]", values.ToString()); } } [Fact] public void TestIntersect_01() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue + 1, int.MaxValue); int i2 = Random.Next(int.MinValue, int.MaxValue); if (i1 > i2) (i1, i2) = (i2, i1); IValueSet<int> values1 = ForInt.Related(GreaterThanOrEqual, i1).Intersect(ForInt.Related(LessThanOrEqual, i2)); Assert.Equal($"[{i1}..{i2}]", values1.ToString()); IValueSet<int> values2 = ForInt.Related(LessThanOrEqual, i2).Intersect(ForInt.Related(GreaterThanOrEqual, i1)); Assert.Equal(values1, values2); } } [Fact] public void TestIntersect_02() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue + 1, int.MaxValue); int i2 = Random.Next(int.MinValue, int.MaxValue); if (i1 < i2) (i1, i2) = (i2, i1); if (i1 == i2) continue; IValueSet<int> values1 = ForInt.Related(GreaterThanOrEqual, i1).Intersect(ForInt.Related(LessThanOrEqual, i2)); Assert.Equal($"", values1.ToString()); IValueSet<int> values2 = ForInt.Related(LessThanOrEqual, i2).Intersect(ForInt.Related(GreaterThanOrEqual, i1)); Assert.Equal(values1, values2); } } [Fact] public void TestUnion_01() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue + 1, int.MaxValue); int i2 = Random.Next(int.MinValue, int.MaxValue); if (i1 > i2) (i1, i2) = (i2, i1); if ((i1 + 1) >= i2) continue; IValueSet<int> values1 = ForInt.Related(LessThanOrEqual, i1).Union(ForInt.Related(GreaterThanOrEqual, i2)); Assert.Equal($"[{int.MinValue}..{i1}],[{i2}..{int.MaxValue}]", values1.ToString()); IValueSet<int> values2 = ForInt.Related(GreaterThanOrEqual, i2).Union(ForInt.Related(LessThanOrEqual, i1)); Assert.Equal(values1, values2); } } [Fact] public void TestUnion_02() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue + 1, int.MaxValue); int i2 = Random.Next(int.MinValue, int.MaxValue); if (i1 < i2) (i1, i2) = (i2, i1); IValueSet<int> values1 = ForInt.Related(LessThanOrEqual, i1).Union(ForInt.Related(GreaterThanOrEqual, i2)); Assert.Equal($"[{int.MinValue}..{int.MaxValue}]", values1.ToString()); IValueSet<int> values2 = ForInt.Related(GreaterThanOrEqual, i2).Union(ForInt.Related(LessThanOrEqual, i1)); Assert.Equal(values1, values2); } } [Fact] public void TestComplement_01() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue + 1, int.MaxValue); int i2 = Random.Next(int.MinValue, int.MaxValue); if (i1 > i2) (i1, i2) = (i2, i1); if ((i1 + 1) >= i2) continue; IValueSet<int> values1 = ForInt.Related(LessThanOrEqual, i1).Union(ForInt.Related(GreaterThanOrEqual, i2)); Assert.Equal($"[{int.MinValue}..{i1}],[{i2}..{int.MaxValue}]", values1.ToString()); IValueSet<int> values2 = values1.Complement(); Assert.Equal(values1, values2.Complement()); Assert.Equal($"[{i1 + 1}..{i2 - 1}]", values2.ToString()); } } [Fact] public void TestAny_01() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue, int.MaxValue); int i2 = Random.Next(int.MinValue, int.MaxValue); if (i1 > i2) (i1, i2) = (i2, i1); IValueSet<int> values = ForInt.Related(GreaterThanOrEqual, i1).Intersect(ForInt.Related(LessThanOrEqual, i2)); Assert.Equal($"[{i1}..{i2}]", values.ToString()); test(int.MinValue); if (i1 != int.MinValue) test(i1 - 1); test(i1); test(i1 + 1); test(int.MaxValue); if (i2 != int.MinValue) test(i2 - 1); test(i2); test(i2 + 1); void test(int val) { Assert.Equal(val >= i1 && val <= i2, values.Any(Equal, val)); Assert.Equal(val >= i1, values.Any(LessThanOrEqual, val)); Assert.Equal(val > i1, values.Any(LessThan, val)); Assert.Equal(val <= i2, values.Any(GreaterThanOrEqual, val)); Assert.Equal(i2 > val, values.Any(GreaterThan, val)); } } } [Fact] public void TestIsEmpty_01() { for (int i = 0; i < 100; i++) { int i1 = Random.Next(int.MinValue, int.MaxValue); int i2 = Random.Next(int.MinValue, int.MaxValue); IValueSet<int> values = ForInt.Related(GreaterThanOrEqual, i1).Intersect(ForInt.Related(LessThanOrEqual, i2)); Assert.Equal(values.ToString().Length == 0, values.IsEmpty); } } [Fact] public void TestDouble_01() { for (int i = 0; i < 100; i++) { double d1 = Random.NextDouble() * 100 - 50; double d2 = Random.NextDouble() * 100 - 50; if (d1 > d2) (d1, d2) = (d2, d1); IValueSet<double> values = ForDouble.Related(GreaterThanOrEqual, d1).Intersect(ForDouble.Related(LessThanOrEqual, d2)); Assert.Equal(FormattableString.Invariant($"[{d1:G17}..{d2:G17}]"), values.ToString()); } } [Fact] public void TestChar_01() { IValueSet<char> gea1 = ForChar.Related(GreaterThanOrEqual, 'a'); IValueSet<char> lez1 = ForChar.Related(LessThanOrEqual, 'z'); IValueSet<char> gea2 = ForChar.Related(GreaterThanOrEqual, 'A'); IValueSet<char> lez2 = ForChar.Related(LessThanOrEqual, 'Z'); var letters = gea1.Intersect(lez1).Union(gea2.Intersect(lez2)); Assert.Equal("['A'..'Z'],['a'..'z']", letters.ToString()); } [Fact] public void TestDouble_02() { Assert.Equal("[-Inf..-Inf]", ForDouble.Related(LessThan, double.MinValue).ToString()); var lt = ForDouble.Related(LessThan, 0.0); Assert.Equal(FormattableString.Invariant($"[-Inf..{-double.Epsilon:G17}]"), lt.ToString()); var gt = ForDouble.Related(GreaterThan, 0.0); Assert.Equal(FormattableString.Invariant($"[{double.Epsilon:G17}..Inf]"), gt.ToString()); var eq = ForDouble.Related(Equal, 0.0); Assert.Equal("[0..0]", eq.ToString()); var none = lt.Complement().Intersect(gt.Complement()).Intersect(eq.Complement()); Assert.Equal("NaN", none.ToString()); Assert.False(none.IsEmpty); } [Fact] public void TestFloat_01() { Assert.Equal("[-Inf..-Inf]", ForFloat.Related(LessThan, float.MinValue).ToString()); var lt = ForFloat.Related(LessThan, 0.0f); Assert.Equal(FormattableString.Invariant($"[-Inf..{-float.Epsilon:G9}]"), lt.ToString()); var gt = ForFloat.Related(GreaterThan, 0.0f); Assert.Equal(FormattableString.Invariant($"[{float.Epsilon:G9}..Inf]"), gt.ToString()); var eq = ForFloat.Related(Equal, 0.0f); Assert.Equal("[0..0]", eq.ToString()); var none = lt.Complement().Intersect(gt.Complement()).Intersect(eq.Complement()); Assert.Equal("NaN", none.ToString()); Assert.False(none.IsEmpty); } [Fact] public void TestDouble_03() { Assert.Equal("NaN", ForDouble.Related(Equal, double.NaN).ToString()); Assert.Equal("NaN", ForFloat.Related(Equal, float.NaN).ToString()); Assert.True(ForDouble.Related(Equal, double.NaN).Any(Equal, double.NaN)); Assert.True(ForFloat.Related(Equal, float.NaN).Any(Equal, float.NaN)); Assert.Equal("[Inf..Inf]", ForDouble.Related(Equal, double.PositiveInfinity).ToString()); Assert.Equal("[Inf..Inf]", ForFloat.Related(Equal, float.PositiveInfinity).ToString()); Assert.Equal("[-Inf..-Inf]", ForDouble.Related(Equal, double.NegativeInfinity).ToString()); Assert.Equal("[-Inf..-Inf]", ForFloat.Related(Equal, float.NegativeInfinity).ToString()); } [Fact] public void TestDouble_04() { var neg = ForDouble.Related(LessThan, 0.0); Assert.True(neg.Any(LessThan, double.MinValue)); Assert.False(neg.Any(GreaterThan, double.MaxValue)); var mi = ForDouble.Related(Equal, double.NegativeInfinity); Assert.True(mi.All(LessThan, 0.0)); Assert.True(mi.Any(LessThan, 0.0)); Assert.True(mi.All(LessThanOrEqual, 0.0)); Assert.True(mi.Any(LessThanOrEqual, 0.0)); Assert.False(mi.All(GreaterThan, 0.0)); Assert.False(mi.Any(GreaterThan, 0.0)); Assert.False(mi.All(GreaterThanOrEqual, 0.0)); Assert.False(mi.Any(GreaterThanOrEqual, 0.0)); var i = ForDouble.Related(Equal, double.PositiveInfinity); Assert.False(i.All(LessThan, 0.0)); Assert.False(i.Any(LessThan, 0.0)); Assert.False(i.All(LessThanOrEqual, 0.0)); Assert.False(i.Any(LessThanOrEqual, 0.0)); Assert.True(i.All(GreaterThan, 0.0)); Assert.True(i.Any(GreaterThan, 0.0)); Assert.True(i.All(GreaterThanOrEqual, 0.0)); Assert.True(i.Any(GreaterThanOrEqual, 0.0)); } [Fact] public void TestString_01() { var notaset = ForString.Related(Equal, "a").Complement(); var bset = ForString.Related(Equal, "b"); var intersect = bset.Intersect(notaset); Assert.False(intersect.Any(Equal, "c")); } [Fact] public void TestBool_Cov_01() { var t = ForBool.Related(Equal, true); var f = ForBool.Related(Equal, false); var em = t.Intersect(f); Assert.True(em.IsEmpty); var q = t.Intersect(t); Assert.Same(t, q); IValueSet b = t; Assert.Same(b.Intersect(b), b); Assert.Same(b.Union(b), b); } [Fact] public void TestByte_Cov_01() { var s = ForByte.Related(GreaterThan, 10).Intersect(ForByte.Related(LessThan, 100)); Assert.Equal("[11..99]", s.ToString()); } [Fact] public void TestString_Cov_01() { var s1 = ForString.Related(Equal, "a"); var s2 = ForString.Related(Equal, "b"); Assert.True(s1.Intersect(s2).IsEmpty); Assert.True(s1.Complement().Union(s2.Complement()).Complement().IsEmpty); Assert.Equal(s1.Union(s2).Complement(), s1.Complement().Intersect(s2.Complement())); IValueSet b = s1; Assert.Same(b.Intersect(b), b); Assert.Same(b.Union(b), b); Assert.False(s1.Union(s2).All(Equal, "a")); } [Fact] public void TestDouble_Cov_01() { var s1 = ForDouble.Related(LessThan, 3.14d); IValueSet b = s1; Assert.Same(s1, s1.Intersect(s1)); Assert.Same(s1, s1.Union(s1)); var s2 = ForDouble.Related(GreaterThan, 31.4d); var s3 = b.Complement().Intersect(s2.Complement()); Assert.Equal("NaN,[3.1400000000000001..31.399999999999999]", s3.ToString()); var s4 = b.Union(s2).Complement(); Assert.Equal(s3, s4); } [Fact] public void TestLong_Cov_01() { var s1 = ForLong.Related(LessThan, 2); Assert.Equal($"[{long.MinValue}..1]", s1.ToString()); Assert.True(s1.All(LessThan, 2)); Assert.True(s1.All(LessThanOrEqual, 1)); Assert.False(s1.All(GreaterThan, 0)); Assert.False(s1.All(GreaterThanOrEqual, 0)); Assert.False(s1.All(Equal, 0)); Assert.False(s1.All(LessThan, -10)); Assert.False(s1.All(LessThanOrEqual, -10)); Assert.False(s1.All(GreaterThan, -10)); Assert.False(s1.All(GreaterThanOrEqual, -10)); Assert.False(s1.All(Equal, -10)); Assert.True(s1.All(LessThan, 10)); Assert.True(s1.All(LessThanOrEqual, 10)); Assert.False(s1.All(GreaterThan, 10)); Assert.False(s1.All(GreaterThanOrEqual, 10)); Assert.False(s1.All(Equal, 10)); var s2 = ForLong.Related(GreaterThan, -5).Intersect(s1); Assert.Equal($"[-4..1]", s2.ToString()); Assert.False(s2.All(LessThan, -10)); Assert.False(s2.All(LessThanOrEqual, -10)); Assert.True(s2.All(GreaterThan, -10)); Assert.True(s2.All(GreaterThanOrEqual, -10)); Assert.False(s2.All(Equal, -10)); Assert.True(s2.All(LessThan, 10)); Assert.True(s2.All(LessThanOrEqual, 10)); Assert.False(s2.All(GreaterThan, 10)); Assert.False(s2.All(GreaterThanOrEqual, 10)); Assert.False(s2.All(Equal, 10)); } [Fact] public void TestNext_Cov_01() { Assert.Equal("[10..100]", ForSByte.Related(GreaterThanOrEqual, 10).Intersect(ForSByte.Related(LessThanOrEqual, 100)).ToString()); Assert.Equal("[10..100]", ForShort.Related(GreaterThanOrEqual, 10).Intersect(ForShort.Related(LessThanOrEqual, 100)).ToString()); Assert.Equal("[10..100]", ForUInt.Related(GreaterThanOrEqual, 10).Intersect(ForUInt.Related(LessThanOrEqual, 100)).ToString()); Assert.Equal("[10..100]", ForULong.Related(GreaterThanOrEqual, 10).Intersect(ForULong.Related(LessThanOrEqual, 100)).ToString()); Assert.Equal("[10..100]", ForUShort.Related(GreaterThanOrEqual, 10).Intersect(ForUShort.Related(LessThanOrEqual, 100)).ToString()); Assert.Equal("[10..100]", ForFloat.Related(GreaterThanOrEqual, 10).Intersect(ForFloat.Related(LessThanOrEqual, 100)).ToString()); Assert.Equal("[-100..-10]", ForFloat.Related(GreaterThanOrEqual, -100).Intersect(ForFloat.Related(LessThanOrEqual, -10)).ToString()); Assert.Equal("[-10..10]", ForFloat.Related(GreaterThanOrEqual, -10).Intersect(ForFloat.Related(LessThanOrEqual, 10)).ToString()); } [Fact] public void TestAPI_01() { Assert.Same(ForByte, ForSpecialType(SpecialType.System_Byte)); Assert.Same(ForSByte, ForSpecialType(SpecialType.System_SByte)); Assert.Same(ForShort, ForSpecialType(SpecialType.System_Int16)); Assert.Same(ForUShort, ForSpecialType(SpecialType.System_UInt16)); Assert.Same(ForInt, ForSpecialType(SpecialType.System_Int32)); Assert.Same(ForUInt, ForSpecialType(SpecialType.System_UInt32)); Assert.Same(ForLong, ForSpecialType(SpecialType.System_Int64)); Assert.Same(ForULong, ForSpecialType(SpecialType.System_UInt64)); Assert.Same(ForFloat, ForSpecialType(SpecialType.System_Single)); Assert.Same(ForDouble, ForSpecialType(SpecialType.System_Double)); Assert.Same(ForString, ForSpecialType(SpecialType.System_String)); Assert.Same(ForDecimal, ForSpecialType(SpecialType.System_Decimal)); Assert.Same(ForChar, ForSpecialType(SpecialType.System_Char)); Assert.Same(ForBool, ForSpecialType(SpecialType.System_Boolean)); Assert.Same(ForNint, ForSpecialType(SpecialType.System_IntPtr, isNative: true)); Assert.Same(ForNuint, ForSpecialType(SpecialType.System_UIntPtr, isNative: true)); Assert.Null(ForSpecialType(SpecialType.System_Enum)); } [Fact] public void TestDecimalRelations_01() { Assert.Equal("[-79228162514264337593543950335..-0.0000000000000000000000000001]", ForDecimal.Related(LessThan, 0.0m).ToString()); Assert.Equal("[-79228162514264337593543950335..0.0000000000000000000000000000]", ForDecimal.Related(LessThanOrEqual, 0.0m).ToString()); Assert.Equal("[0.0000000000000000000000000001..79228162514264337593543950335]", ForDecimal.Related(GreaterThan, 0.0m).ToString()); Assert.Equal("[0.0000000000000000000000000000..79228162514264337593543950335]", ForDecimal.Related(GreaterThanOrEqual, 0.0m).ToString()); } [Fact] public void TestNintRelations_01() { Assert.Equal("Small,[-2147483648..9]", ForNint.Related(LessThan, 10).ToString()); Assert.Equal("Small,[-2147483648..10]", ForNint.Related(LessThanOrEqual, 10).ToString()); Assert.Equal("[11..2147483647],Large", ForNint.Related(GreaterThan, 10).ToString()); Assert.Equal("[10..2147483647],Large", ForNint.Related(GreaterThanOrEqual, 10).ToString()); } [Fact] public void TestNuintRelations_01() { Assert.Equal("[0..9]", ForNuint.Related(LessThan, 10).ToString()); Assert.Equal("[0..10]", ForNuint.Related(LessThanOrEqual, 10).ToString()); Assert.Equal("[11..4294967295],Large", ForNuint.Related(GreaterThan, 10).ToString()); Assert.Equal("[10..4294967295],Large", ForNuint.Related(GreaterThanOrEqual, 10).ToString()); } [Fact] public void TestDecimalEdges_01() { for (byte scale = 0; scale < 29; scale++) { var l = new decimal(~0, ~0, ~0, false, scale); check(l); l = new decimal(~0, ~0, ~0, true, scale); check(l); } for (byte scale = 0; scale < 29; scale++) { var l = new decimal(unchecked((int)0x99999999), unchecked((int)0x99999999), 0x19999999, false, scale); check(l); l = new decimal(unchecked((int)0x99999999), unchecked((int)0x99999999), 0x19999999, true, scale); check(l); l = new decimal(unchecked((int)0x99999998), unchecked((int)0x99999999), 0x19999999, false, scale); check(l); l = new decimal(unchecked((int)0x99999998), unchecked((int)0x99999999), 0x19999999, true, scale); check(l); l = new decimal(unchecked((int)0x9999999A), unchecked((int)0x99999999), 0x19999999, false, scale); check(l); l = new decimal(unchecked((int)0x9999999A), unchecked((int)0x99999999), 0x19999999, true, scale); check(l); } for (int high = 0; high < 2; high++) { for (int mid = 0; mid < 2; mid++) { for (int p2 = 0; p2 < 32; p2++) { int low = 1 << p2; var l = new decimal(low, mid, high, false, 28); check(l); l = new decimal(low, mid, high, true, 28); check(l); } } } void check(decimal d) { Assert.False(ForDecimal.Related(LessThan, d).Any(Equal, d)); Assert.True(ForDecimal.Related(LessThanOrEqual, d).Any(Equal, d)); Assert.False(ForDecimal.Related(GreaterThan, d).Any(Equal, d)); Assert.True(ForDecimal.Related(GreaterThanOrEqual, d).Any(Equal, d)); } } [Fact] public void TestNumbers_Fuzz_01() { var Random = new Random(123445); foreach (var fac in new IValueSetFactory[] { ForByte, ForSByte, ForShort, ForUShort, ForInt, ForUInt, ForLong, ForULong, ForFloat, ForDouble, ForDecimal, ForNint, ForNuint, ForChar, ForLength, }) { for (int i = 0; i < 100; i++) { var s1 = fac.Random(10, Random); var s2 = fac.Random(10, Random); var u1 = s1.Union(s2); var u2 = s1.Complement().Intersect(s2.Complement()).Complement(); Assert.Equal(u1, u2); var i1 = s1.Intersect(s2); var i2 = s1.Complement().Union(s2.Complement()).Complement(); Assert.Equal(i1, i2); } } } [Fact] public void TestNumbers_Fuzz_02() { foreach (var fac in new IValueSetFactory[] { ForByte, ForSByte, ForShort, ForUShort, ForInt, ForUInt, ForLong, ForULong, ForDecimal, ForNint, ForNuint, ForChar, ForLength }) { for (int i = 0; i < 100; i++) { ConstantValue value = fac.RandomValue(Random); var s1 = fac.Related(LessThan, value); var s2 = fac.Related(GreaterThanOrEqual, value); Assert.Equal(s1.Complement(), s2); Assert.Equal(s2.Complement(), s1); Assert.True(s2.Any(Equal, value)); Assert.False(s1.Any(Equal, value)); Assert.True(s1.All(LessThan, value)); Assert.False(s2.Any(LessThan, value)); Assert.True(s2.All(GreaterThanOrEqual, value)); Assert.False(s1.Any(GreaterThanOrEqual, value)); s1 = fac.Related(GreaterThan, value); s2 = fac.Related(LessThanOrEqual, value); Assert.Equal(s1.Complement(), s2); Assert.Equal(s2.Complement(), s1); Assert.True(s2.Any(Equal, value)); Assert.False(s1.Any(Equal, value)); Assert.True(s1.All(GreaterThan, value)); Assert.False(s2.Any(GreaterThan, value)); Assert.True(s2.All(LessThanOrEqual, value)); Assert.False(s1.Any(LessThanOrEqual, value)); } } } [Fact] public void TestString_Fuzz_02() { for (int i = 0; i < 100; i++) { var s1 = ForString.Random(9, Random); var s2 = ForString.Random(11, Random); Assert.Equal(s1.Complement().Complement(), s1); var u1 = s1.Union(s2); var u2 = s1.Complement().Intersect(s2.Complement()).Complement(); var u3 = s2.Union(s1); var u4 = s2.Complement().Intersect(s1.Complement()).Complement(); Assert.Equal(u1, u2); Assert.Equal(u1, u3); Assert.Equal(u1, u4); var i1 = s1.Intersect(s2); var i2 = s1.Complement().Union(s2.Complement()).Complement(); var i3 = s2.Intersect(s1); var i4 = s2.Complement().Union(s1.Complement()).Complement(); Assert.Equal(i1, i2); Assert.Equal(i1, i3); Assert.Equal(i1, i4); s1 = s1.Complement(); u1 = s1.Union(s2); u2 = s1.Complement().Intersect(s2.Complement()).Complement(); u3 = s2.Union(s1); u4 = s2.Complement().Intersect(s1.Complement()).Complement(); Assert.Equal(u1, u2); Assert.Equal(u1, u3); Assert.Equal(u1, u4); i1 = s1.Intersect(s2); i2 = s1.Complement().Union(s2.Complement()).Complement(); i3 = s2.Intersect(s1); i4 = s2.Complement().Union(s1.Complement()).Complement(); Assert.Equal(i1, i2); Assert.Equal(i1, i3); Assert.Equal(i1, i4); s2 = s2.Complement(); u1 = s1.Union(s2); u2 = s1.Complement().Intersect(s2.Complement()).Complement(); u3 = s2.Union(s1); u4 = s2.Complement().Intersect(s1.Complement()).Complement(); Assert.Equal(u1, u2); Assert.Equal(u1, u3); Assert.Equal(u1, u4); i1 = s1.Intersect(s2); i2 = s1.Complement().Union(s2.Complement()).Complement(); i3 = s2.Intersect(s1); i4 = s2.Complement().Union(s1.Complement()).Complement(); Assert.Equal(i1, i2); Assert.Equal(i1, i3); Assert.Equal(i1, i4); } } [Fact] public void TestAnyFuzz_01() { for (int i = 0; i < 100; i++) { var s1 = ForInt.Related(BinaryOperatorKind.Equal, i); Assert.True(s1.Any(LessThan, i + 1)); Assert.False(s1.Any(LessThan, i)); Assert.False(s1.Any(LessThan, i - 1)); Assert.True(s1.Any(LessThanOrEqual, i + 1)); Assert.True(s1.Any(LessThanOrEqual, i)); Assert.False(s1.Any(LessThanOrEqual, i - 1)); Assert.False(s1.Any(GreaterThan, i + 1)); Assert.False(s1.Any(GreaterThan, i)); Assert.True(s1.Any(GreaterThan, i - 1)); Assert.False(s1.Any(GreaterThanOrEqual, i + 1)); Assert.True(s1.Any(GreaterThanOrEqual, i)); Assert.True(s1.Any(GreaterThanOrEqual, i - 1)); } } [Fact] public void TestAnyFuzz_02() { for (int i = 0; i < 100; i++) { int j = Random.Next(); var s1 = ForInt.Related(BinaryOperatorKind.Equal, j); Assert.True(s1.Any(LessThan, j + 1)); Assert.False(s1.Any(LessThan, j)); Assert.False(s1.Any(LessThan, j - 1)); Assert.True(s1.Any(LessThanOrEqual, j + 1)); Assert.True(s1.Any(LessThanOrEqual, j)); Assert.False(s1.Any(LessThanOrEqual, j - 1)); Assert.False(s1.Any(GreaterThan, j + 1)); Assert.False(s1.Any(GreaterThan, j)); Assert.True(s1.Any(GreaterThan, j - 1)); Assert.False(s1.Any(GreaterThanOrEqual, j + 1)); Assert.True(s1.Any(GreaterThanOrEqual, j)); Assert.True(s1.Any(GreaterThanOrEqual, j - 1)); } } [Fact] public void TestAllFuzz_01() { for (int i = 0; i < 100; i++) { var s1 = ForInt.Related(BinaryOperatorKind.LessThan, i); Assert.True(s1.All(LessThan, i + 1)); Assert.True(s1.All(LessThan, i)); Assert.False(s1.All(LessThan, i - 1)); Assert.True(s1.All(LessThanOrEqual, i + 1)); Assert.True(s1.All(LessThanOrEqual, i)); Assert.True(s1.All(LessThanOrEqual, i - 1)); Assert.False(s1.All(LessThanOrEqual, i - 2)); s1 = ForInt.Related(BinaryOperatorKind.GreaterThan, i); Assert.False(s1.All(GreaterThan, i + 1)); Assert.True(s1.All(GreaterThan, i)); Assert.True(s1.All(GreaterThan, i - 1)); Assert.False(s1.All(GreaterThanOrEqual, i + 2)); Assert.True(s1.All(GreaterThanOrEqual, i + 1)); Assert.True(s1.All(GreaterThanOrEqual, i)); Assert.True(s1.All(GreaterThanOrEqual, i - 1)); } } [Fact] public void TestAllFuzz_02() { for (int i = 0; i < 100; i++) { int j = Random.Next(0, int.MaxValue - 1); var s1 = ForInt.Related(BinaryOperatorKind.LessThan, j); Assert.True(s1.All(LessThan, j + 1)); Assert.True(s1.All(LessThan, j)); Assert.False(s1.All(LessThan, j - 1)); Assert.True(s1.All(LessThanOrEqual, j + 1)); Assert.True(s1.All(LessThanOrEqual, j)); Assert.True(s1.All(LessThanOrEqual, j - 1)); Assert.False(s1.All(LessThanOrEqual, j - 2)); s1 = ForInt.Related(BinaryOperatorKind.GreaterThan, j); Assert.False(s1.All(GreaterThan, j + 1)); Assert.True(s1.All(GreaterThan, j)); Assert.True(s1.All(GreaterThan, j - 1)); Assert.False(s1.All(GreaterThanOrEqual, j + 2)); Assert.True(s1.All(GreaterThanOrEqual, j + 1)); Assert.True(s1.All(GreaterThanOrEqual, j)); Assert.True(s1.All(GreaterThanOrEqual, j - 1)); } } [Fact] public void TestAllFuzz_03() { for (int i = 0; i < 100; i++) { var s1 = ForInt.Related(BinaryOperatorKind.Equal, i); Assert.True(s1.All(LessThan, i + 1)); Assert.False(s1.All(LessThan, i)); Assert.False(s1.All(LessThan, i - 1)); Assert.True(s1.All(LessThanOrEqual, i + 1)); Assert.True(s1.All(LessThanOrEqual, i)); Assert.False(s1.All(LessThanOrEqual, i - 1)); Assert.False(s1.All(GreaterThan, i + 1)); Assert.False(s1.All(GreaterThan, i)); Assert.True(s1.All(GreaterThan, i - 1)); Assert.False(s1.All(GreaterThanOrEqual, i + 1)); Assert.True(s1.All(GreaterThanOrEqual, i)); Assert.True(s1.All(GreaterThanOrEqual, i - 1)); } } [Fact] public void TestAllFuzz_04() { for (int i = 0; i < 100; i++) { int j = Random.Next(0, int.MaxValue - 1); var s1 = ForInt.Related(BinaryOperatorKind.Equal, j); Assert.True(s1.All(LessThan, j + 1)); Assert.False(s1.All(LessThan, j)); Assert.False(s1.All(LessThan, j - 1)); Assert.True(s1.All(LessThanOrEqual, j + 1)); Assert.True(s1.All(LessThanOrEqual, j)); Assert.False(s1.All(LessThanOrEqual, j - 1)); Assert.False(s1.All(GreaterThan, j + 1)); Assert.False(s1.All(GreaterThan, j)); Assert.True(s1.All(GreaterThan, j - 1)); Assert.False(s1.All(GreaterThanOrEqual, j + 1)); Assert.True(s1.All(GreaterThanOrEqual, j)); Assert.True(s1.All(GreaterThanOrEqual, j - 1)); } } [Fact] public void DoNotCrashOnBadInput() { // For error recovery, do not throw exceptions on bad inputs. var ctors = new IValueSetFactory[] { ForByte, ForSByte, ForChar, ForShort, ForUShort, ForInt, ForUInt, ForLong, ForULong, ForBool, ForFloat, ForDouble, ForString, ForDecimal, ForNint, ForNuint, ForLength, }; ConstantValue badConstant = ConstantValue.Bad; foreach (IValueSetFactory fac in ctors) { foreach (BinaryOperatorKind relation in new[] { LessThan, Equal, NotEqual }) { IValueSet set = fac.Related(relation, badConstant); _ = set.All(relation, badConstant); _ = set.Any(relation, badConstant); } } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Test/Symbol/Symbols/UnsignedRightShiftTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class UnsignedRightShiftTests : CSharpTestBase { [Theory] [InlineData("char", "char", "ushort.MaxValue", "int", "uint")] [InlineData("char", "sbyte", "ushort.MaxValue", "int", "uint")] [InlineData("char", "short", "ushort.MaxValue", "int", "uint")] [InlineData("char", "int", "ushort.MaxValue", "int", "uint")] [InlineData("char", "byte", "ushort.MaxValue", "int", "uint")] [InlineData("char", "ushort", "ushort.MaxValue", "int", "uint")] [InlineData("sbyte", "char", "sbyte.MinValue", "int", "uint")] [InlineData("sbyte", "sbyte", "sbyte.MinValue", "int", "uint")] [InlineData("sbyte", "short", "sbyte.MinValue", "int", "uint")] [InlineData("sbyte", "int", "sbyte.MinValue", "int", "uint")] [InlineData("sbyte", "byte", "sbyte.MinValue", "int", "uint")] [InlineData("sbyte", "ushort", "sbyte.MinValue", "int", "uint")] [InlineData("short", "char", "short.MinValue", "int", "uint")] [InlineData("short", "sbyte", "short.MinValue", "int", "uint")] [InlineData("short", "short", "short.MinValue", "int", "uint")] [InlineData("short", "int", "short.MinValue", "int", "uint")] [InlineData("short", "byte", "short.MinValue", "int", "uint")] [InlineData("short", "ushort", "short.MinValue", "int", "uint")] [InlineData("int", "char", "int.MinValue", "int", "uint")] [InlineData("int", "sbyte", "int.MinValue", "int", "uint")] [InlineData("int", "short", "int.MinValue", "int", "uint")] [InlineData("int", "int", "int.MinValue", "int", "uint")] [InlineData("int", "byte", "int.MinValue", "int", "uint")] [InlineData("int", "ushort", "int.MinValue", "int", "uint")] [InlineData("long", "char", "long.MinValue", "long", "ulong")] [InlineData("long", "sbyte", "long.MinValue", "long", "ulong")] [InlineData("long", "short", "long.MinValue", "long", "ulong")] [InlineData("long", "int", "long.MinValue", "long", "ulong")] [InlineData("long", "byte", "long.MinValue", "long", "ulong")] [InlineData("long", "ushort", "long.MinValue", "long", "ulong")] [InlineData("byte", "char", "byte.MaxValue", "int", "uint")] [InlineData("byte", "sbyte", "byte.MaxValue", "int", "uint")] [InlineData("byte", "short", "byte.MaxValue", "int", "uint")] [InlineData("byte", "int", "byte.MaxValue", "int", "uint")] [InlineData("byte", "byte", "byte.MaxValue", "int", "uint")] [InlineData("byte", "ushort", "byte.MaxValue", "int", "uint")] [InlineData("ushort", "char", "ushort.MaxValue", "int", "uint")] [InlineData("ushort", "sbyte", "ushort.MaxValue", "int", "uint")] [InlineData("ushort", "short", "ushort.MaxValue", "int", "uint")] [InlineData("ushort", "int", "ushort.MaxValue", "int", "uint")] [InlineData("ushort", "byte", "ushort.MaxValue", "int", "uint")] [InlineData("ushort", "ushort", "ushort.MaxValue", "int", "uint")] [InlineData("uint", "char", "uint.MaxValue", "uint", "uint")] [InlineData("uint", "sbyte", "uint.MaxValue", "uint", "uint")] [InlineData("uint", "short", "uint.MaxValue", "uint", "uint")] [InlineData("uint", "int", "uint.MaxValue", "uint", "uint")] [InlineData("uint", "byte", "uint.MaxValue", "uint", "uint")] [InlineData("uint", "ushort", "uint.MaxValue", "uint", "uint")] [InlineData("ulong", "char", "ulong.MaxValue", "ulong", "ulong")] [InlineData("ulong", "sbyte", "ulong.MaxValue", "ulong", "ulong")] [InlineData("ulong", "short", "ulong.MaxValue", "ulong", "ulong")] [InlineData("ulong", "int", "ulong.MaxValue", "ulong", "ulong")] [InlineData("ulong", "byte", "ulong.MaxValue", "ulong", "ulong")] [InlineData("ulong", "ushort", "ulong.MaxValue", "ulong", "ulong")] [InlineData("nint", "char", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint", "nuint")] [InlineData("nint", "sbyte", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint", "nuint")] [InlineData("nint", "short", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint", "nuint")] [InlineData("nint", "int", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint", "nuint")] [InlineData("nint", "byte", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint", "nuint")] [InlineData("nint", "ushort", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint", "nuint")] [InlineData("nuint", "char", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint", "nuint")] [InlineData("nuint", "sbyte", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint", "nuint")] [InlineData("nuint", "short", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint", "nuint")] [InlineData("nuint", "int", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint", "nuint")] [InlineData("nuint", "byte", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint", "nuint")] [InlineData("nuint", "ushort", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint", "nuint")] public void BuiltIn_01(string left, string right, string leftValue, string result, string unsignedResult) { var source1 = @" class C { static void Main() { var x = (" + left + @")" + leftValue + @"; var y = (" + right + @")1; var z1 = x >>> y; var z2 = x >> y; if (z1 == unchecked((" + result + @")(((" + unsignedResult + @")(" + result + @")x) >> y))) System.Console.WriteLine(""Passed 1""); if (x > 0 ? z1 == z2 : z1 != z2) System.Console.WriteLine(""Passed 2""); if (z1.GetType() == z2.GetType() && z1.GetType() == typeof(" + result + @")) System.Console.WriteLine(""Passed 3""); } " + result + @" Test1(" + left + @" x, " + right + @" y) => x >>> y; " + result + @" Test2(" + left + @" x, " + right + @" y) => x >> y; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(compilation1, expectedOutput: @" Passed 1 Passed 2 Passed 3 ").VerifyDiagnostics(); string actualIL = verifier.VisualizeIL("C.Test2"); verifier.VerifyIL("C.Test1", actualIL.Replace("shr.un", "shr").Replace("shr", "shr.un")); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftExpression).First(); var shift = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.RightShiftExpression).First(); Assert.Equal("x >>> y", unsignedShift.ToString()); Assert.Equal("x >> y", shift.ToString()); var unsignedShiftSymbol = (IMethodSymbol)model.GetSymbolInfo(unsignedShift).Symbol; var shiftSymbol = (IMethodSymbol)model.GetSymbolInfo(shift).Symbol; Assert.Equal("op_UnsignedRightShift", unsignedShiftSymbol.Name); Assert.Equal("op_RightShift", shiftSymbol.Name); Assert.Same(shiftSymbol.ReturnType, unsignedShiftSymbol.ReturnType); Assert.Same(shiftSymbol.Parameters[0].Type, unsignedShiftSymbol.Parameters[0].Type); Assert.Same(shiftSymbol.Parameters[1].Type, unsignedShiftSymbol.Parameters[1].Type); Assert.Same(shiftSymbol.ContainingSymbol, unsignedShiftSymbol.ContainingSymbol); } [Theory] [InlineData("object", "object")] [InlineData("object", "string")] [InlineData("object", "bool")] [InlineData("object", "char")] [InlineData("object", "sbyte")] [InlineData("object", "short")] [InlineData("object", "int")] [InlineData("object", "long")] [InlineData("object", "byte")] [InlineData("object", "ushort")] [InlineData("object", "uint")] [InlineData("object", "ulong")] [InlineData("object", "nint")] [InlineData("object", "nuint")] [InlineData("object", "float")] [InlineData("object", "double")] [InlineData("object", "decimal")] [InlineData("string", "object")] [InlineData("string", "string")] [InlineData("string", "bool")] [InlineData("string", "char")] [InlineData("string", "sbyte")] [InlineData("string", "short")] [InlineData("string", "int")] [InlineData("string", "long")] [InlineData("string", "byte")] [InlineData("string", "ushort")] [InlineData("string", "uint")] [InlineData("string", "ulong")] [InlineData("string", "nint")] [InlineData("string", "nuint")] [InlineData("string", "float")] [InlineData("string", "double")] [InlineData("string", "decimal")] [InlineData("bool", "object")] [InlineData("bool", "string")] [InlineData("bool", "bool")] [InlineData("bool", "char")] [InlineData("bool", "sbyte")] [InlineData("bool", "short")] [InlineData("bool", "int")] [InlineData("bool", "long")] [InlineData("bool", "byte")] [InlineData("bool", "ushort")] [InlineData("bool", "uint")] [InlineData("bool", "ulong")] [InlineData("bool", "nint")] [InlineData("bool", "nuint")] [InlineData("bool", "float")] [InlineData("bool", "double")] [InlineData("bool", "decimal")] [InlineData("char", "object")] [InlineData("char", "string")] [InlineData("char", "bool")] [InlineData("char", "long")] [InlineData("char", "uint")] [InlineData("char", "ulong")] [InlineData("char", "nint")] [InlineData("char", "nuint")] [InlineData("char", "float")] [InlineData("char", "double")] [InlineData("char", "decimal")] [InlineData("sbyte", "object")] [InlineData("sbyte", "string")] [InlineData("sbyte", "bool")] [InlineData("sbyte", "long")] [InlineData("sbyte", "uint")] [InlineData("sbyte", "ulong")] [InlineData("sbyte", "nint")] [InlineData("sbyte", "nuint")] [InlineData("sbyte", "float")] [InlineData("sbyte", "double")] [InlineData("sbyte", "decimal")] [InlineData("short", "object")] [InlineData("short", "string")] [InlineData("short", "bool")] [InlineData("short", "long")] [InlineData("short", "uint")] [InlineData("short", "ulong")] [InlineData("short", "nint")] [InlineData("short", "nuint")] [InlineData("short", "float")] [InlineData("short", "double")] [InlineData("short", "decimal")] [InlineData("int", "object")] [InlineData("int", "string")] [InlineData("int", "bool")] [InlineData("int", "long")] [InlineData("int", "uint")] [InlineData("int", "ulong")] [InlineData("int", "nint")] [InlineData("int", "nuint")] [InlineData("int", "float")] [InlineData("int", "double")] [InlineData("int", "decimal")] [InlineData("long", "object")] [InlineData("long", "string")] [InlineData("long", "bool")] [InlineData("long", "long")] [InlineData("long", "uint")] [InlineData("long", "ulong")] [InlineData("long", "nint")] [InlineData("long", "nuint")] [InlineData("long", "float")] [InlineData("long", "double")] [InlineData("long", "decimal")] [InlineData("byte", "object")] [InlineData("byte", "string")] [InlineData("byte", "bool")] [InlineData("byte", "long")] [InlineData("byte", "uint")] [InlineData("byte", "ulong")] [InlineData("byte", "nint")] [InlineData("byte", "nuint")] [InlineData("byte", "float")] [InlineData("byte", "double")] [InlineData("byte", "decimal")] [InlineData("ushort", "object")] [InlineData("ushort", "string")] [InlineData("ushort", "bool")] [InlineData("ushort", "long")] [InlineData("ushort", "uint")] [InlineData("ushort", "ulong")] [InlineData("ushort", "nint")] [InlineData("ushort", "nuint")] [InlineData("ushort", "float")] [InlineData("ushort", "double")] [InlineData("ushort", "decimal")] [InlineData("uint", "object")] [InlineData("uint", "string")] [InlineData("uint", "bool")] [InlineData("uint", "long")] [InlineData("uint", "uint")] [InlineData("uint", "ulong")] [InlineData("uint", "nint")] [InlineData("uint", "nuint")] [InlineData("uint", "float")] [InlineData("uint", "double")] [InlineData("uint", "decimal")] [InlineData("ulong", "object")] [InlineData("ulong", "string")] [InlineData("ulong", "bool")] [InlineData("ulong", "long")] [InlineData("ulong", "uint")] [InlineData("ulong", "ulong")] [InlineData("ulong", "nint")] [InlineData("ulong", "nuint")] [InlineData("ulong", "float")] [InlineData("ulong", "double")] [InlineData("ulong", "decimal")] [InlineData("nint", "object")] [InlineData("nint", "string")] [InlineData("nint", "bool")] [InlineData("nint", "long")] [InlineData("nint", "uint")] [InlineData("nint", "ulong")] [InlineData("nint", "nint")] [InlineData("nint", "nuint")] [InlineData("nint", "float")] [InlineData("nint", "double")] [InlineData("nint", "decimal")] [InlineData("nuint", "object")] [InlineData("nuint", "string")] [InlineData("nuint", "bool")] [InlineData("nuint", "long")] [InlineData("nuint", "uint")] [InlineData("nuint", "ulong")] [InlineData("nuint", "nint")] [InlineData("nuint", "nuint")] [InlineData("nuint", "float")] [InlineData("nuint", "double")] [InlineData("nuint", "decimal")] [InlineData("float", "object")] [InlineData("float", "string")] [InlineData("float", "bool")] [InlineData("float", "char")] [InlineData("float", "sbyte")] [InlineData("float", "short")] [InlineData("float", "int")] [InlineData("float", "long")] [InlineData("float", "byte")] [InlineData("float", "ushort")] [InlineData("float", "uint")] [InlineData("float", "ulong")] [InlineData("float", "nint")] [InlineData("float", "nuint")] [InlineData("float", "float")] [InlineData("float", "double")] [InlineData("float", "decimal")] [InlineData("double", "object")] [InlineData("double", "string")] [InlineData("double", "bool")] [InlineData("double", "char")] [InlineData("double", "sbyte")] [InlineData("double", "short")] [InlineData("double", "int")] [InlineData("double", "long")] [InlineData("double", "byte")] [InlineData("double", "ushort")] [InlineData("double", "uint")] [InlineData("double", "ulong")] [InlineData("double", "nint")] [InlineData("double", "nuint")] [InlineData("double", "float")] [InlineData("double", "double")] [InlineData("double", "decimal")] [InlineData("decimal", "object")] [InlineData("decimal", "string")] [InlineData("decimal", "bool")] [InlineData("decimal", "char")] [InlineData("decimal", "sbyte")] [InlineData("decimal", "short")] [InlineData("decimal", "int")] [InlineData("decimal", "long")] [InlineData("decimal", "byte")] [InlineData("decimal", "ushort")] [InlineData("decimal", "uint")] [InlineData("decimal", "ulong")] [InlineData("decimal", "nint")] [InlineData("decimal", "nuint")] [InlineData("decimal", "float")] [InlineData("decimal", "double")] [InlineData("decimal", "decimal")] public void BuiltIn_02(string left, string right) { var source1 = @" class C { static void Main() { " + left + @" x = default; " + right + @" y = default; var z1 = x >> y; var z2 = x >>> y; } } "; var expected = new[] { // (8,18): error CS0019: Operator '>>' cannot be applied to operands of type 'object' and 'object' // var z1 = x >> y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >> y").WithArguments(">>", left, right).WithLocation(8, 18), // (9,18): error CS0019: Operator '>>>' cannot be applied to operands of type 'object' and 'object' // var z2 = x >>> y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>> y").WithArguments(">>>", left, right).WithLocation(9, 18) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyEmitDiagnostics(expected); } [Theory] [InlineData("char", "char", "ushort.MaxValue", "int")] [InlineData("char", "sbyte", "ushort.MaxValue", "int")] [InlineData("char", "short", "ushort.MaxValue", "int")] [InlineData("char", "int", "ushort.MaxValue", "int")] [InlineData("char", "byte", "ushort.MaxValue", "int")] [InlineData("char", "ushort", "ushort.MaxValue", "int")] [InlineData("sbyte", "char", "sbyte.MinValue", "int")] [InlineData("sbyte", "sbyte", "sbyte.MinValue", "int")] [InlineData("sbyte", "short", "sbyte.MinValue", "int")] [InlineData("sbyte", "int", "sbyte.MinValue", "int")] [InlineData("sbyte", "byte", "sbyte.MinValue", "int")] [InlineData("sbyte", "ushort", "sbyte.MinValue", "int")] [InlineData("short", "char", "short.MinValue", "int")] [InlineData("short", "sbyte", "short.MinValue", "int")] [InlineData("short", "short", "short.MinValue", "int")] [InlineData("short", "int", "short.MinValue", "int")] [InlineData("short", "byte", "short.MinValue", "int")] [InlineData("short", "ushort", "short.MinValue", "int")] [InlineData("int", "char", "int.MinValue", "int")] [InlineData("int", "sbyte", "int.MinValue", "int")] [InlineData("int", "short", "int.MinValue", "int")] [InlineData("int", "int", "int.MinValue", "int")] [InlineData("int", "byte", "int.MinValue", "int")] [InlineData("int", "ushort", "int.MinValue", "int")] [InlineData("long", "char", "long.MinValue", "long")] [InlineData("long", "sbyte", "long.MinValue", "long")] [InlineData("long", "short", "long.MinValue", "long")] [InlineData("long", "int", "long.MinValue", "long")] [InlineData("long", "byte", "long.MinValue", "long")] [InlineData("long", "ushort", "long.MinValue", "long")] [InlineData("byte", "char", "byte.MaxValue", "int")] [InlineData("byte", "sbyte", "byte.MaxValue", "int")] [InlineData("byte", "short", "byte.MaxValue", "int")] [InlineData("byte", "int", "byte.MaxValue", "int")] [InlineData("byte", "byte", "byte.MaxValue", "int")] [InlineData("byte", "ushort", "byte.MaxValue", "int")] [InlineData("ushort", "char", "ushort.MaxValue", "int")] [InlineData("ushort", "sbyte", "ushort.MaxValue", "int")] [InlineData("ushort", "short", "ushort.MaxValue", "int")] [InlineData("ushort", "int", "ushort.MaxValue", "int")] [InlineData("ushort", "byte", "ushort.MaxValue", "int")] [InlineData("ushort", "ushort", "ushort.MaxValue", "int")] [InlineData("uint", "char", "uint.MaxValue", "uint")] [InlineData("uint", "sbyte", "uint.MaxValue", "uint")] [InlineData("uint", "short", "uint.MaxValue", "uint")] [InlineData("uint", "int", "uint.MaxValue", "uint")] [InlineData("uint", "byte", "uint.MaxValue", "uint")] [InlineData("uint", "ushort", "uint.MaxValue", "uint")] [InlineData("ulong", "char", "ulong.MaxValue", "ulong")] [InlineData("ulong", "sbyte", "ulong.MaxValue", "ulong")] [InlineData("ulong", "short", "ulong.MaxValue", "ulong")] [InlineData("ulong", "int", "ulong.MaxValue", "ulong")] [InlineData("ulong", "byte", "ulong.MaxValue", "ulong")] [InlineData("ulong", "ushort", "ulong.MaxValue", "ulong")] [InlineData("nint", "char", "int.MaxValue", "nint")] [InlineData("nint", "sbyte", "int.MaxValue", "nint")] [InlineData("nint", "short", "int.MaxValue", "nint")] [InlineData("nint", "int", "int.MaxValue", "nint")] [InlineData("nint", "byte", "int.MaxValue", "nint")] [InlineData("nint", "ushort", "int.MaxValue", "nint")] [InlineData("nuint", "char", "uint.MaxValue", "nuint")] [InlineData("nuint", "sbyte", "uint.MaxValue", "nuint")] [InlineData("nuint", "short", "uint.MaxValue", "nuint")] [InlineData("nuint", "int", "uint.MaxValue", "nuint")] [InlineData("nuint", "byte", "uint.MaxValue", "nuint")] [InlineData("nuint", "ushort", "uint.MaxValue", "nuint")] [InlineData("nint", "char", "0", "nint")] [InlineData("nint", "sbyte", "0", "nint")] [InlineData("nint", "short", "0", "nint")] [InlineData("nint", "int", "0", "nint")] [InlineData("nint", "byte", "0", "nint")] [InlineData("nint", "ushort", "0", "nint")] public void BuiltIn_ConstantFolding_01(string left, string right, string leftValue, string result) { var source1 = @" class C { static void Main() { const " + left + @" x = (" + left + @")(" + leftValue + @"); const " + result + @" y = x >>> (" + right + @")1; var z1 = x; var z2 = z1 >>> (" + right + @")1; if (y == z2) System.Console.WriteLine(""Passed 1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation1, expectedOutput: @" Passed 1 ").VerifyDiagnostics(); } [Theory] [InlineData("int.MinValue")] [InlineData("-1")] [InlineData("-100")] public void BuiltIn_ConstantFolding_02(string leftValue) { var source1 = @" #pragma warning disable CS0219 // The variable 'y' is assigned but its value is never used class C { static void Main() { const nint x = (nint)(" + leftValue + @"); const nint y = x >>> 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); compilation1.VerifyDiagnostics( // (9,24): error CS0133: The expression being assigned to 'y' must be constant // const nint y = x >>> 1; Diagnostic(ErrorCode.ERR_NotConstantExpression, "x >>> 1").WithArguments("y").WithLocation(9, 24) ); } [Theory] [InlineData("char", "char", "ushort.MaxValue")] [InlineData("char", "sbyte", "ushort.MaxValue")] [InlineData("char", "short", "ushort.MaxValue")] [InlineData("char", "int", "ushort.MaxValue")] [InlineData("char", "byte", "ushort.MaxValue")] [InlineData("char", "ushort", "ushort.MaxValue")] [InlineData("sbyte", "char", "sbyte.MinValue")] [InlineData("sbyte", "sbyte", "sbyte.MinValue")] [InlineData("sbyte", "short", "sbyte.MinValue")] [InlineData("sbyte", "int", "sbyte.MinValue")] [InlineData("sbyte", "byte", "sbyte.MinValue")] [InlineData("sbyte", "ushort", "sbyte.MinValue")] [InlineData("short", "char", "short.MinValue")] [InlineData("short", "sbyte", "short.MinValue")] [InlineData("short", "short", "short.MinValue")] [InlineData("short", "int", "short.MinValue")] [InlineData("short", "byte", "short.MinValue")] [InlineData("short", "ushort", "short.MinValue")] [InlineData("int", "char", "int.MinValue")] [InlineData("int", "sbyte", "int.MinValue")] [InlineData("int", "short", "int.MinValue")] [InlineData("int", "int", "int.MinValue")] [InlineData("int", "byte", "int.MinValue")] [InlineData("int", "ushort", "int.MinValue")] [InlineData("long", "char", "long.MinValue")] [InlineData("long", "sbyte", "long.MinValue")] [InlineData("long", "short", "long.MinValue")] [InlineData("long", "int", "long.MinValue")] [InlineData("long", "byte", "long.MinValue")] [InlineData("long", "ushort", "long.MinValue")] [InlineData("byte", "char", "byte.MaxValue")] [InlineData("byte", "sbyte", "byte.MaxValue")] [InlineData("byte", "short", "byte.MaxValue")] [InlineData("byte", "int", "byte.MaxValue")] [InlineData("byte", "byte", "byte.MaxValue")] [InlineData("byte", "ushort", "byte.MaxValue")] [InlineData("ushort", "char", "ushort.MaxValue")] [InlineData("ushort", "sbyte", "ushort.MaxValue")] [InlineData("ushort", "short", "ushort.MaxValue")] [InlineData("ushort", "int", "ushort.MaxValue")] [InlineData("ushort", "byte", "ushort.MaxValue")] [InlineData("ushort", "ushort", "ushort.MaxValue")] [InlineData("uint", "char", "uint.MaxValue")] [InlineData("uint", "sbyte", "uint.MaxValue")] [InlineData("uint", "short", "uint.MaxValue")] [InlineData("uint", "int", "uint.MaxValue")] [InlineData("uint", "byte", "uint.MaxValue")] [InlineData("uint", "ushort", "uint.MaxValue")] [InlineData("ulong", "char", "ulong.MaxValue")] [InlineData("ulong", "sbyte", "ulong.MaxValue")] [InlineData("ulong", "short", "ulong.MaxValue")] [InlineData("ulong", "int", "ulong.MaxValue")] [InlineData("ulong", "byte", "ulong.MaxValue")] [InlineData("ulong", "ushort", "ulong.MaxValue")] [InlineData("nint", "char", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "sbyte", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "short", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "int", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "byte", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "ushort", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nuint", "char", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "sbyte", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "short", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "int", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "byte", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "ushort", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] public void BuiltIn_CompoundAssignment_01(string left, string right, string leftValue) { var source1 = @" class C { static void Main() { var x = (" + left + @")" + leftValue + @"; var y = (" + right + @")1; var z1 = x; z1 >>>= y; if (z1 == (" + left + @")(x >>> y)) System.Console.WriteLine(""Passed 1""); z1 >>= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation1, expectedOutput: @" Passed 1 ").VerifyDiagnostics(); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftAssignmentExpression).First(); var shift = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.RightShiftAssignmentExpression).First(); Assert.Equal("z1 >>>= y", unsignedShift.ToString()); Assert.Equal("z1 >>= y", shift.ToString()); var unsignedShiftSymbol = (IMethodSymbol)model.GetSymbolInfo(unsignedShift).Symbol; var shiftSymbol = (IMethodSymbol)model.GetSymbolInfo(shift).Symbol; Assert.Equal("op_UnsignedRightShift", unsignedShiftSymbol.Name); Assert.Equal("op_RightShift", shiftSymbol.Name); Assert.Same(shiftSymbol.ReturnType, unsignedShiftSymbol.ReturnType); Assert.Same(shiftSymbol.Parameters[0].Type, unsignedShiftSymbol.Parameters[0].Type); Assert.Same(shiftSymbol.Parameters[1].Type, unsignedShiftSymbol.Parameters[1].Type); Assert.Same(shiftSymbol.ContainingSymbol, unsignedShiftSymbol.ContainingSymbol); } [Theory] [InlineData("object", "object")] [InlineData("object", "string")] [InlineData("object", "bool")] [InlineData("object", "char")] [InlineData("object", "sbyte")] [InlineData("object", "short")] [InlineData("object", "int")] [InlineData("object", "long")] [InlineData("object", "byte")] [InlineData("object", "ushort")] [InlineData("object", "uint")] [InlineData("object", "ulong")] [InlineData("object", "nint")] [InlineData("object", "nuint")] [InlineData("object", "float")] [InlineData("object", "double")] [InlineData("object", "decimal")] [InlineData("string", "object")] [InlineData("string", "string")] [InlineData("string", "bool")] [InlineData("string", "char")] [InlineData("string", "sbyte")] [InlineData("string", "short")] [InlineData("string", "int")] [InlineData("string", "long")] [InlineData("string", "byte")] [InlineData("string", "ushort")] [InlineData("string", "uint")] [InlineData("string", "ulong")] [InlineData("string", "nint")] [InlineData("string", "nuint")] [InlineData("string", "float")] [InlineData("string", "double")] [InlineData("string", "decimal")] [InlineData("bool", "object")] [InlineData("bool", "string")] [InlineData("bool", "bool")] [InlineData("bool", "char")] [InlineData("bool", "sbyte")] [InlineData("bool", "short")] [InlineData("bool", "int")] [InlineData("bool", "long")] [InlineData("bool", "byte")] [InlineData("bool", "ushort")] [InlineData("bool", "uint")] [InlineData("bool", "ulong")] [InlineData("bool", "nint")] [InlineData("bool", "nuint")] [InlineData("bool", "float")] [InlineData("bool", "double")] [InlineData("bool", "decimal")] [InlineData("char", "object")] [InlineData("char", "string")] [InlineData("char", "bool")] [InlineData("char", "long")] [InlineData("char", "uint")] [InlineData("char", "ulong")] [InlineData("char", "nint")] [InlineData("char", "nuint")] [InlineData("char", "float")] [InlineData("char", "double")] [InlineData("char", "decimal")] [InlineData("sbyte", "object")] [InlineData("sbyte", "string")] [InlineData("sbyte", "bool")] [InlineData("sbyte", "long")] [InlineData("sbyte", "uint")] [InlineData("sbyte", "ulong")] [InlineData("sbyte", "nint")] [InlineData("sbyte", "nuint")] [InlineData("sbyte", "float")] [InlineData("sbyte", "double")] [InlineData("sbyte", "decimal")] [InlineData("short", "object")] [InlineData("short", "string")] [InlineData("short", "bool")] [InlineData("short", "long")] [InlineData("short", "uint")] [InlineData("short", "ulong")] [InlineData("short", "nint")] [InlineData("short", "nuint")] [InlineData("short", "float")] [InlineData("short", "double")] [InlineData("short", "decimal")] [InlineData("int", "object")] [InlineData("int", "string")] [InlineData("int", "bool")] [InlineData("int", "long")] [InlineData("int", "uint")] [InlineData("int", "ulong")] [InlineData("int", "nint")] [InlineData("int", "nuint")] [InlineData("int", "float")] [InlineData("int", "double")] [InlineData("int", "decimal")] [InlineData("long", "object")] [InlineData("long", "string")] [InlineData("long", "bool")] [InlineData("long", "long")] [InlineData("long", "uint")] [InlineData("long", "ulong")] [InlineData("long", "nint")] [InlineData("long", "nuint")] [InlineData("long", "float")] [InlineData("long", "double")] [InlineData("long", "decimal")] [InlineData("byte", "object")] [InlineData("byte", "string")] [InlineData("byte", "bool")] [InlineData("byte", "long")] [InlineData("byte", "uint")] [InlineData("byte", "ulong")] [InlineData("byte", "nint")] [InlineData("byte", "nuint")] [InlineData("byte", "float")] [InlineData("byte", "double")] [InlineData("byte", "decimal")] [InlineData("ushort", "object")] [InlineData("ushort", "string")] [InlineData("ushort", "bool")] [InlineData("ushort", "long")] [InlineData("ushort", "uint")] [InlineData("ushort", "ulong")] [InlineData("ushort", "nint")] [InlineData("ushort", "nuint")] [InlineData("ushort", "float")] [InlineData("ushort", "double")] [InlineData("ushort", "decimal")] [InlineData("uint", "object")] [InlineData("uint", "string")] [InlineData("uint", "bool")] [InlineData("uint", "long")] [InlineData("uint", "uint")] [InlineData("uint", "ulong")] [InlineData("uint", "nint")] [InlineData("uint", "nuint")] [InlineData("uint", "float")] [InlineData("uint", "double")] [InlineData("uint", "decimal")] [InlineData("ulong", "object")] [InlineData("ulong", "string")] [InlineData("ulong", "bool")] [InlineData("ulong", "long")] [InlineData("ulong", "uint")] [InlineData("ulong", "ulong")] [InlineData("ulong", "nint")] [InlineData("ulong", "nuint")] [InlineData("ulong", "float")] [InlineData("ulong", "double")] [InlineData("ulong", "decimal")] [InlineData("nint", "object")] [InlineData("nint", "string")] [InlineData("nint", "bool")] [InlineData("nint", "long")] [InlineData("nint", "uint")] [InlineData("nint", "ulong")] [InlineData("nint", "nint")] [InlineData("nint", "nuint")] [InlineData("nint", "float")] [InlineData("nint", "double")] [InlineData("nint", "decimal")] [InlineData("nuint", "object")] [InlineData("nuint", "string")] [InlineData("nuint", "bool")] [InlineData("nuint", "long")] [InlineData("nuint", "uint")] [InlineData("nuint", "ulong")] [InlineData("nuint", "nint")] [InlineData("nuint", "nuint")] [InlineData("nuint", "float")] [InlineData("nuint", "double")] [InlineData("nuint", "decimal")] [InlineData("float", "object")] [InlineData("float", "string")] [InlineData("float", "bool")] [InlineData("float", "char")] [InlineData("float", "sbyte")] [InlineData("float", "short")] [InlineData("float", "int")] [InlineData("float", "long")] [InlineData("float", "byte")] [InlineData("float", "ushort")] [InlineData("float", "uint")] [InlineData("float", "ulong")] [InlineData("float", "nint")] [InlineData("float", "nuint")] [InlineData("float", "float")] [InlineData("float", "double")] [InlineData("float", "decimal")] [InlineData("double", "object")] [InlineData("double", "string")] [InlineData("double", "bool")] [InlineData("double", "char")] [InlineData("double", "sbyte")] [InlineData("double", "short")] [InlineData("double", "int")] [InlineData("double", "long")] [InlineData("double", "byte")] [InlineData("double", "ushort")] [InlineData("double", "uint")] [InlineData("double", "ulong")] [InlineData("double", "nint")] [InlineData("double", "nuint")] [InlineData("double", "float")] [InlineData("double", "double")] [InlineData("double", "decimal")] [InlineData("decimal", "object")] [InlineData("decimal", "string")] [InlineData("decimal", "bool")] [InlineData("decimal", "char")] [InlineData("decimal", "sbyte")] [InlineData("decimal", "short")] [InlineData("decimal", "int")] [InlineData("decimal", "long")] [InlineData("decimal", "byte")] [InlineData("decimal", "ushort")] [InlineData("decimal", "uint")] [InlineData("decimal", "ulong")] [InlineData("decimal", "nint")] [InlineData("decimal", "nuint")] [InlineData("decimal", "float")] [InlineData("decimal", "double")] [InlineData("decimal", "decimal")] public void BuiltIn_CompoundAssignment_02(string left, string right) { var source1 = @" class C { static void Main() { " + left + @" x = default; " + right + @" y = default; x >>= y; x >>>= y; } } "; var expected = new[] { // (8,9): error CS0019: Operator '>>=' cannot be applied to operands of type 'double' and 'char' // x >>= y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>= y").WithArguments(">>=", left, right).WithLocation(8, 9), // (9,9): error CS0019: Operator '>>>=' cannot be applied to operands of type 'double' and 'char' // x >>>= y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>>= y").WithArguments(">>>=", left, right).WithLocation(9, 9) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyEmitDiagnostics(expected); } [Fact] public void BuiltIn_CompoundAssignment_CollectionInitializerElement() { var source1 = @" class C { static void Main() { var x = int.MinValue; var y = new System.Collections.Generic.List<int>() { x >>= 1, x >>>= 1 }; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (8,13): error CS0747: Invalid initializer member declarator // x >>= 1, Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "x >>= 1").WithLocation(8, 13), // (9,13): error CS0747: Invalid initializer member declarator // x >>>= 1 Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "x >>>= 1").WithLocation(9, 13) ); } [Fact] public void BuiltIn_ExpressionTree_01() { var source1 = @" class C { static void Main() { System.Linq.Expressions.Expression<System.Func<int, int, int>> e = (x, y) => x >>> y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (6,86): error CS7053: An expression tree may not contain '>>>' // System.Linq.Expressions.Expression<System.Func<int, int, int>> e = (x, y) => x >>> y; Diagnostic(ErrorCode.ERR_FeatureNotValidInExpressionTree, "x >>> y").WithArguments(">>>").WithLocation(6, 86) ); } [Fact] public void BuiltIn_CompoundAssignment_ExpressionTree_01() { var source1 = @" class C { static void Main() { System.Linq.Expressions.Expression<System.Func<int, int, int>> e = (x, y) => x >>>= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (6,86): error CS0832: An expression tree may not contain an assignment operator // System.Linq.Expressions.Expression<System.Func<int, int, int>> e = (x, y) => x >>>= y; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "x >>>= y").WithLocation(6, 86) ); } [Fact] public void BuiltIn_Dynamic_01() { var source1 = @" class C { static void Main(dynamic x, int y) { _ = x >>> y; _ = y >>> x; _ = x >>> x; } } "; var expected = new[] { // (6,13): error CS0019: Operator '>>>' cannot be applied to operands of type 'dynamic' and 'int' // _ = x >>> y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>> y").WithArguments(">>>", "dynamic", "int").WithLocation(6, 13), // (7,13): error CS0019: Operator '>>>' cannot be applied to operands of type 'int' and 'dynamic' // _ = y >>> x; Diagnostic(ErrorCode.ERR_BadBinaryOps, "y >>> x").WithArguments(">>>", "int", "dynamic").WithLocation(7, 13), // (8,13): error CS0019: Operator '>>>' cannot be applied to operands of type 'dynamic' and 'dynamic' // _ = x >>> x; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>> x").WithArguments(">>>", "dynamic", "dynamic").WithLocation(8, 13) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyEmitDiagnostics(expected); } [Fact] public void BuiltIn_CompoundAssignment_Dynamic_01() { var source1 = @" class C { static void Main(dynamic x, int y) { x >>>= y; y >>>= x; x >>>= x; } } "; var expected = new[] { // (6,9): error CS0019: Operator '>>>=' cannot be applied to operands of type 'dynamic' and 'int' // x >>>= y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>>= y").WithArguments(">>>=", "dynamic", "int").WithLocation(6, 9), // (7,9): error CS0019: Operator '>>>=' cannot be applied to operands of type 'int' and 'dynamic' // y >>>= x; Diagnostic(ErrorCode.ERR_BadBinaryOps, "y >>>= x").WithArguments(">>>=", "int", "dynamic").WithLocation(7, 9), // (8,9): error CS0019: Operator '>>>=' cannot be applied to operands of type 'dynamic' and 'dynamic' // x >>>= x; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>>= x").WithArguments(">>>=", "dynamic", "dynamic").WithLocation(8, 9) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyEmitDiagnostics(expected); } [Theory] [InlineData("char", "char", "ushort.MaxValue", "int")] [InlineData("char", "sbyte", "ushort.MaxValue", "int")] [InlineData("char", "short", "ushort.MaxValue", "int")] [InlineData("char", "int", "ushort.MaxValue", "int")] [InlineData("char", "byte", "ushort.MaxValue", "int")] [InlineData("char", "ushort", "ushort.MaxValue", "int")] [InlineData("sbyte", "char", "sbyte.MinValue", "int")] [InlineData("sbyte", "sbyte", "sbyte.MinValue", "int")] [InlineData("sbyte", "short", "sbyte.MinValue", "int")] [InlineData("sbyte", "int", "sbyte.MinValue", "int")] [InlineData("sbyte", "byte", "sbyte.MinValue", "int")] [InlineData("sbyte", "ushort", "sbyte.MinValue", "int")] [InlineData("short", "char", "short.MinValue", "int")] [InlineData("short", "sbyte", "short.MinValue", "int")] [InlineData("short", "short", "short.MinValue", "int")] [InlineData("short", "int", "short.MinValue", "int")] [InlineData("short", "byte", "short.MinValue", "int")] [InlineData("short", "ushort", "short.MinValue", "int")] [InlineData("int", "char", "int.MinValue", "int")] [InlineData("int", "sbyte", "int.MinValue", "int")] [InlineData("int", "short", "int.MinValue", "int")] [InlineData("int", "int", "int.MinValue", "int")] [InlineData("int", "byte", "int.MinValue", "int")] [InlineData("int", "ushort", "int.MinValue", "int")] [InlineData("long", "char", "long.MinValue", "long")] [InlineData("long", "sbyte", "long.MinValue", "long")] [InlineData("long", "short", "long.MinValue", "long")] [InlineData("long", "int", "long.MinValue", "long")] [InlineData("long", "byte", "long.MinValue", "long")] [InlineData("long", "ushort", "long.MinValue", "long")] [InlineData("byte", "char", "byte.MaxValue", "int")] [InlineData("byte", "sbyte", "byte.MaxValue", "int")] [InlineData("byte", "short", "byte.MaxValue", "int")] [InlineData("byte", "int", "byte.MaxValue", "int")] [InlineData("byte", "byte", "byte.MaxValue", "int")] [InlineData("byte", "ushort", "byte.MaxValue", "int")] [InlineData("ushort", "char", "ushort.MaxValue", "int")] [InlineData("ushort", "sbyte", "ushort.MaxValue", "int")] [InlineData("ushort", "short", "ushort.MaxValue", "int")] [InlineData("ushort", "int", "ushort.MaxValue", "int")] [InlineData("ushort", "byte", "ushort.MaxValue", "int")] [InlineData("ushort", "ushort", "ushort.MaxValue", "int")] [InlineData("uint", "char", "uint.MaxValue", "uint")] [InlineData("uint", "sbyte", "uint.MaxValue", "uint")] [InlineData("uint", "short", "uint.MaxValue", "uint")] [InlineData("uint", "int", "uint.MaxValue", "uint")] [InlineData("uint", "byte", "uint.MaxValue", "uint")] [InlineData("uint", "ushort", "uint.MaxValue", "uint")] [InlineData("ulong", "char", "ulong.MaxValue", "ulong")] [InlineData("ulong", "sbyte", "ulong.MaxValue", "ulong")] [InlineData("ulong", "short", "ulong.MaxValue", "ulong")] [InlineData("ulong", "int", "ulong.MaxValue", "ulong")] [InlineData("ulong", "byte", "ulong.MaxValue", "ulong")] [InlineData("ulong", "ushort", "ulong.MaxValue", "ulong")] [InlineData("nint", "char", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint")] [InlineData("nint", "sbyte", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint")] [InlineData("nint", "short", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint")] [InlineData("nint", "int", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint")] [InlineData("nint", "byte", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint")] [InlineData("nint", "ushort", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint")] [InlineData("nuint", "char", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint")] [InlineData("nuint", "sbyte", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint")] [InlineData("nuint", "short", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint")] [InlineData("nuint", "int", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint")] [InlineData("nuint", "byte", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint")] [InlineData("nuint", "ushort", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint")] public void BuiltIn_Lifted_01(string left, string right, string leftValue, string result) { var nullableLeft = left + "?"; var nullableRight = right + "?"; var nullableResult = result + "?"; var source1 = @" class C { static void Main() { var x = (" + nullableLeft + @")" + leftValue + @"; var y = (" + nullableRight + @")1; var z1 = x >>> y; var z2 = x >> y; if (z1 == (x.Value >>> y.Value)) System.Console.WriteLine(""Passed 1""); if (GetType(z1) == GetType(z2) && GetType(z1) == typeof(" + nullableResult + @")) System.Console.WriteLine(""Passed 2""); if (Test1(x, null) == null) System.Console.WriteLine(""Passed 3""); if (Test1(null, y) == null) System.Console.WriteLine(""Passed 4""); if (Test1(null, null) == null) System.Console.WriteLine(""Passed 5""); } static " + nullableResult + @" Test1(" + nullableLeft + @" x, " + nullableRight + @" y) => x >>> y; static " + nullableResult + @" Test2(" + nullableLeft + @" x, " + nullableRight + @" y) => x >> y; static System.Type GetType<T>(T x) => typeof(T); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(compilation1, expectedOutput: @" Passed 1 Passed 2 Passed 3 Passed 4 Passed 5 ").VerifyDiagnostics(); string actualIL = verifier.VisualizeIL("C.Test2"); verifier.VerifyIL("C.Test1", actualIL.Replace("shr.un", "shr").Replace("shr", "shr.un")); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftExpression).First(); var shift = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.RightShiftExpression).First(); Assert.Equal("x >>> y", unsignedShift.ToString()); Assert.Equal("x >> y", shift.ToString()); var unsignedShiftSymbol = (IMethodSymbol)model.GetSymbolInfo(unsignedShift).Symbol; var shiftSymbol = (IMethodSymbol)model.GetSymbolInfo(shift).Symbol; Assert.Equal("op_UnsignedRightShift", unsignedShiftSymbol.Name); Assert.Equal("op_RightShift", shiftSymbol.Name); Assert.Same(shiftSymbol.ReturnType, unsignedShiftSymbol.ReturnType); Assert.Same(shiftSymbol.Parameters[0].Type, unsignedShiftSymbol.Parameters[0].Type); Assert.Same(shiftSymbol.Parameters[1].Type, unsignedShiftSymbol.Parameters[1].Type); Assert.Same(shiftSymbol.ContainingSymbol, unsignedShiftSymbol.ContainingSymbol); } [Theory] [InlineData("object", "object")] [InlineData("object", "string")] [InlineData("object", "bool")] [InlineData("object", "char")] [InlineData("object", "sbyte")] [InlineData("object", "short")] [InlineData("object", "int")] [InlineData("object", "long")] [InlineData("object", "byte")] [InlineData("object", "ushort")] [InlineData("object", "uint")] [InlineData("object", "ulong")] [InlineData("object", "nint")] [InlineData("object", "nuint")] [InlineData("object", "float")] [InlineData("object", "double")] [InlineData("object", "decimal")] [InlineData("string", "object")] [InlineData("string", "string")] [InlineData("string", "bool")] [InlineData("string", "char")] [InlineData("string", "sbyte")] [InlineData("string", "short")] [InlineData("string", "int")] [InlineData("string", "long")] [InlineData("string", "byte")] [InlineData("string", "ushort")] [InlineData("string", "uint")] [InlineData("string", "ulong")] [InlineData("string", "nint")] [InlineData("string", "nuint")] [InlineData("string", "float")] [InlineData("string", "double")] [InlineData("string", "decimal")] [InlineData("bool", "object")] [InlineData("bool", "string")] [InlineData("bool", "bool")] [InlineData("bool", "char")] [InlineData("bool", "sbyte")] [InlineData("bool", "short")] [InlineData("bool", "int")] [InlineData("bool", "long")] [InlineData("bool", "byte")] [InlineData("bool", "ushort")] [InlineData("bool", "uint")] [InlineData("bool", "ulong")] [InlineData("bool", "nint")] [InlineData("bool", "nuint")] [InlineData("bool", "float")] [InlineData("bool", "double")] [InlineData("bool", "decimal")] [InlineData("char", "object")] [InlineData("char", "string")] [InlineData("char", "bool")] [InlineData("char", "long")] [InlineData("char", "uint")] [InlineData("char", "ulong")] [InlineData("char", "nint")] [InlineData("char", "nuint")] [InlineData("char", "float")] [InlineData("char", "double")] [InlineData("char", "decimal")] [InlineData("sbyte", "object")] [InlineData("sbyte", "string")] [InlineData("sbyte", "bool")] [InlineData("sbyte", "long")] [InlineData("sbyte", "uint")] [InlineData("sbyte", "ulong")] [InlineData("sbyte", "nint")] [InlineData("sbyte", "nuint")] [InlineData("sbyte", "float")] [InlineData("sbyte", "double")] [InlineData("sbyte", "decimal")] [InlineData("short", "object")] [InlineData("short", "string")] [InlineData("short", "bool")] [InlineData("short", "long")] [InlineData("short", "uint")] [InlineData("short", "ulong")] [InlineData("short", "nint")] [InlineData("short", "nuint")] [InlineData("short", "float")] [InlineData("short", "double")] [InlineData("short", "decimal")] [InlineData("int", "object")] [InlineData("int", "string")] [InlineData("int", "bool")] [InlineData("int", "long")] [InlineData("int", "uint")] [InlineData("int", "ulong")] [InlineData("int", "nint")] [InlineData("int", "nuint")] [InlineData("int", "float")] [InlineData("int", "double")] [InlineData("int", "decimal")] [InlineData("long", "object")] [InlineData("long", "string")] [InlineData("long", "bool")] [InlineData("long", "long")] [InlineData("long", "uint")] [InlineData("long", "ulong")] [InlineData("long", "nint")] [InlineData("long", "nuint")] [InlineData("long", "float")] [InlineData("long", "double")] [InlineData("long", "decimal")] [InlineData("byte", "object")] [InlineData("byte", "string")] [InlineData("byte", "bool")] [InlineData("byte", "long")] [InlineData("byte", "uint")] [InlineData("byte", "ulong")] [InlineData("byte", "nint")] [InlineData("byte", "nuint")] [InlineData("byte", "float")] [InlineData("byte", "double")] [InlineData("byte", "decimal")] [InlineData("ushort", "object")] [InlineData("ushort", "string")] [InlineData("ushort", "bool")] [InlineData("ushort", "long")] [InlineData("ushort", "uint")] [InlineData("ushort", "ulong")] [InlineData("ushort", "nint")] [InlineData("ushort", "nuint")] [InlineData("ushort", "float")] [InlineData("ushort", "double")] [InlineData("ushort", "decimal")] [InlineData("uint", "object")] [InlineData("uint", "string")] [InlineData("uint", "bool")] [InlineData("uint", "long")] [InlineData("uint", "uint")] [InlineData("uint", "ulong")] [InlineData("uint", "nint")] [InlineData("uint", "nuint")] [InlineData("uint", "float")] [InlineData("uint", "double")] [InlineData("uint", "decimal")] [InlineData("ulong", "object")] [InlineData("ulong", "string")] [InlineData("ulong", "bool")] [InlineData("ulong", "long")] [InlineData("ulong", "uint")] [InlineData("ulong", "ulong")] [InlineData("ulong", "nint")] [InlineData("ulong", "nuint")] [InlineData("ulong", "float")] [InlineData("ulong", "double")] [InlineData("ulong", "decimal")] [InlineData("nint", "object")] [InlineData("nint", "string")] [InlineData("nint", "bool")] [InlineData("nint", "long")] [InlineData("nint", "uint")] [InlineData("nint", "ulong")] [InlineData("nint", "nint")] [InlineData("nint", "nuint")] [InlineData("nint", "float")] [InlineData("nint", "double")] [InlineData("nint", "decimal")] [InlineData("nuint", "object")] [InlineData("nuint", "string")] [InlineData("nuint", "bool")] [InlineData("nuint", "long")] [InlineData("nuint", "uint")] [InlineData("nuint", "ulong")] [InlineData("nuint", "nint")] [InlineData("nuint", "nuint")] [InlineData("nuint", "float")] [InlineData("nuint", "double")] [InlineData("nuint", "decimal")] [InlineData("float", "object")] [InlineData("float", "string")] [InlineData("float", "bool")] [InlineData("float", "char")] [InlineData("float", "sbyte")] [InlineData("float", "short")] [InlineData("float", "int")] [InlineData("float", "long")] [InlineData("float", "byte")] [InlineData("float", "ushort")] [InlineData("float", "uint")] [InlineData("float", "ulong")] [InlineData("float", "nint")] [InlineData("float", "nuint")] [InlineData("float", "float")] [InlineData("float", "double")] [InlineData("float", "decimal")] [InlineData("double", "object")] [InlineData("double", "string")] [InlineData("double", "bool")] [InlineData("double", "char")] [InlineData("double", "sbyte")] [InlineData("double", "short")] [InlineData("double", "int")] [InlineData("double", "long")] [InlineData("double", "byte")] [InlineData("double", "ushort")] [InlineData("double", "uint")] [InlineData("double", "ulong")] [InlineData("double", "nint")] [InlineData("double", "nuint")] [InlineData("double", "float")] [InlineData("double", "double")] [InlineData("double", "decimal")] [InlineData("decimal", "object")] [InlineData("decimal", "string")] [InlineData("decimal", "bool")] [InlineData("decimal", "char")] [InlineData("decimal", "sbyte")] [InlineData("decimal", "short")] [InlineData("decimal", "int")] [InlineData("decimal", "long")] [InlineData("decimal", "byte")] [InlineData("decimal", "ushort")] [InlineData("decimal", "uint")] [InlineData("decimal", "ulong")] [InlineData("decimal", "nint")] [InlineData("decimal", "nuint")] [InlineData("decimal", "float")] [InlineData("decimal", "double")] [InlineData("decimal", "decimal")] public void BuiltIn_Lifted_02(string left, string right) { var nullableLeft = NullableIfPossible(left); var nullableRight = NullableIfPossible(right); var source1 = @" class C { static void Main() { " + nullableLeft + @" x = default; " + nullableRight + @" y = default; var z1 = x >> y; var z2 = x >>> y; } } "; var expected = new[] { // (8,18): error CS0019: Operator '>>' cannot be applied to operands of type 'object' and 'object' // var z1 = x >> y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >> y").WithArguments(">>", nullableLeft, nullableRight).WithLocation(8, 18), // (9,18): error CS0019: Operator '>>>' cannot be applied to operands of type 'object' and 'object' // var z2 = x >>> y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>> y").WithArguments(">>>", nullableLeft, nullableRight).WithLocation(9, 18) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyEmitDiagnostics(expected); } private static string NullableIfPossible(string type) { switch (type) { case "object": case "string": return type; default: return type + "?"; } } [Theory] [InlineData("char", "char", "ushort.MaxValue")] [InlineData("char", "sbyte", "ushort.MaxValue")] [InlineData("char", "short", "ushort.MaxValue")] [InlineData("char", "int", "ushort.MaxValue")] [InlineData("char", "byte", "ushort.MaxValue")] [InlineData("char", "ushort", "ushort.MaxValue")] [InlineData("sbyte", "char", "sbyte.MinValue")] [InlineData("sbyte", "sbyte", "sbyte.MinValue")] [InlineData("sbyte", "short", "sbyte.MinValue")] [InlineData("sbyte", "int", "sbyte.MinValue")] [InlineData("sbyte", "byte", "sbyte.MinValue")] [InlineData("sbyte", "ushort", "sbyte.MinValue")] [InlineData("short", "char", "short.MinValue")] [InlineData("short", "sbyte", "short.MinValue")] [InlineData("short", "short", "short.MinValue")] [InlineData("short", "int", "short.MinValue")] [InlineData("short", "byte", "short.MinValue")] [InlineData("short", "ushort", "short.MinValue")] [InlineData("int", "char", "int.MinValue")] [InlineData("int", "sbyte", "int.MinValue")] [InlineData("int", "short", "int.MinValue")] [InlineData("int", "int", "int.MinValue")] [InlineData("int", "byte", "int.MinValue")] [InlineData("int", "ushort", "int.MinValue")] [InlineData("long", "char", "long.MinValue")] [InlineData("long", "sbyte", "long.MinValue")] [InlineData("long", "short", "long.MinValue")] [InlineData("long", "int", "long.MinValue")] [InlineData("long", "byte", "long.MinValue")] [InlineData("long", "ushort", "long.MinValue")] [InlineData("byte", "char", "byte.MaxValue")] [InlineData("byte", "sbyte", "byte.MaxValue")] [InlineData("byte", "short", "byte.MaxValue")] [InlineData("byte", "int", "byte.MaxValue")] [InlineData("byte", "byte", "byte.MaxValue")] [InlineData("byte", "ushort", "byte.MaxValue")] [InlineData("ushort", "char", "ushort.MaxValue")] [InlineData("ushort", "sbyte", "ushort.MaxValue")] [InlineData("ushort", "short", "ushort.MaxValue")] [InlineData("ushort", "int", "ushort.MaxValue")] [InlineData("ushort", "byte", "ushort.MaxValue")] [InlineData("ushort", "ushort", "ushort.MaxValue")] [InlineData("uint", "char", "uint.MaxValue")] [InlineData("uint", "sbyte", "uint.MaxValue")] [InlineData("uint", "short", "uint.MaxValue")] [InlineData("uint", "int", "uint.MaxValue")] [InlineData("uint", "byte", "uint.MaxValue")] [InlineData("uint", "ushort", "uint.MaxValue")] [InlineData("ulong", "char", "ulong.MaxValue")] [InlineData("ulong", "sbyte", "ulong.MaxValue")] [InlineData("ulong", "short", "ulong.MaxValue")] [InlineData("ulong", "int", "ulong.MaxValue")] [InlineData("ulong", "byte", "ulong.MaxValue")] [InlineData("ulong", "ushort", "ulong.MaxValue")] [InlineData("nint", "char", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "sbyte", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "short", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "int", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "byte", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "ushort", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nuint", "char", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "sbyte", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "short", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "int", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "byte", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "ushort", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] public void BuiltIn_Lifted_CompoundAssignment_01(string left, string right, string leftValue) { var nullableLeft = left + "?"; var nullableRight = right + "?"; var source1 = @" class C { static void Main() { var x = (" + nullableLeft + @")" + leftValue + @"; var y = (" + nullableRight + @")1; var z1 = x; z1 >>>= y; if (z1 == (" + left + @")(x.Value >>> y.Value)) System.Console.WriteLine(""Passed 1""); z1 >>= y; z1 = null; z1 >>>= y; if (z1 == null) System.Console.WriteLine(""Passed 2""); y = null; z1 >>>= y; if (z1 == null) System.Console.WriteLine(""Passed 3""); z1 = x; z1 >>>= y; if (z1 == null) System.Console.WriteLine(""Passed 4""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation1, expectedOutput: @" Passed 1 Passed 2 Passed 3 Passed 4 ").VerifyDiagnostics(); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftAssignmentExpression).First(); var shift = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.RightShiftAssignmentExpression).First(); Assert.Equal("z1 >>>= y", unsignedShift.ToString()); Assert.Equal("z1 >>= y", shift.ToString()); var unsignedShiftSymbol = (IMethodSymbol)model.GetSymbolInfo(unsignedShift).Symbol; var shiftSymbol = (IMethodSymbol)model.GetSymbolInfo(shift).Symbol; Assert.Equal("op_UnsignedRightShift", unsignedShiftSymbol.Name); Assert.Equal("op_RightShift", shiftSymbol.Name); Assert.Same(shiftSymbol.ReturnType, unsignedShiftSymbol.ReturnType); Assert.Same(shiftSymbol.Parameters[0].Type, unsignedShiftSymbol.Parameters[0].Type); Assert.Same(shiftSymbol.Parameters[1].Type, unsignedShiftSymbol.Parameters[1].Type); Assert.Same(shiftSymbol.ContainingSymbol, unsignedShiftSymbol.ContainingSymbol); } [Theory] [InlineData("object", "object")] [InlineData("object", "string")] [InlineData("object", "bool")] [InlineData("object", "char")] [InlineData("object", "sbyte")] [InlineData("object", "short")] [InlineData("object", "int")] [InlineData("object", "long")] [InlineData("object", "byte")] [InlineData("object", "ushort")] [InlineData("object", "uint")] [InlineData("object", "ulong")] [InlineData("object", "nint")] [InlineData("object", "nuint")] [InlineData("object", "float")] [InlineData("object", "double")] [InlineData("object", "decimal")] [InlineData("string", "object")] [InlineData("string", "string")] [InlineData("string", "bool")] [InlineData("string", "char")] [InlineData("string", "sbyte")] [InlineData("string", "short")] [InlineData("string", "int")] [InlineData("string", "long")] [InlineData("string", "byte")] [InlineData("string", "ushort")] [InlineData("string", "uint")] [InlineData("string", "ulong")] [InlineData("string", "nint")] [InlineData("string", "nuint")] [InlineData("string", "float")] [InlineData("string", "double")] [InlineData("string", "decimal")] [InlineData("bool", "object")] [InlineData("bool", "string")] [InlineData("bool", "bool")] [InlineData("bool", "char")] [InlineData("bool", "sbyte")] [InlineData("bool", "short")] [InlineData("bool", "int")] [InlineData("bool", "long")] [InlineData("bool", "byte")] [InlineData("bool", "ushort")] [InlineData("bool", "uint")] [InlineData("bool", "ulong")] [InlineData("bool", "nint")] [InlineData("bool", "nuint")] [InlineData("bool", "float")] [InlineData("bool", "double")] [InlineData("bool", "decimal")] [InlineData("char", "object")] [InlineData("char", "string")] [InlineData("char", "bool")] [InlineData("char", "long")] [InlineData("char", "uint")] [InlineData("char", "ulong")] [InlineData("char", "nint")] [InlineData("char", "nuint")] [InlineData("char", "float")] [InlineData("char", "double")] [InlineData("char", "decimal")] [InlineData("sbyte", "object")] [InlineData("sbyte", "string")] [InlineData("sbyte", "bool")] [InlineData("sbyte", "long")] [InlineData("sbyte", "uint")] [InlineData("sbyte", "ulong")] [InlineData("sbyte", "nint")] [InlineData("sbyte", "nuint")] [InlineData("sbyte", "float")] [InlineData("sbyte", "double")] [InlineData("sbyte", "decimal")] [InlineData("short", "object")] [InlineData("short", "string")] [InlineData("short", "bool")] [InlineData("short", "long")] [InlineData("short", "uint")] [InlineData("short", "ulong")] [InlineData("short", "nint")] [InlineData("short", "nuint")] [InlineData("short", "float")] [InlineData("short", "double")] [InlineData("short", "decimal")] [InlineData("int", "object")] [InlineData("int", "string")] [InlineData("int", "bool")] [InlineData("int", "long")] [InlineData("int", "uint")] [InlineData("int", "ulong")] [InlineData("int", "nint")] [InlineData("int", "nuint")] [InlineData("int", "float")] [InlineData("int", "double")] [InlineData("int", "decimal")] [InlineData("long", "object")] [InlineData("long", "string")] [InlineData("long", "bool")] [InlineData("long", "long")] [InlineData("long", "uint")] [InlineData("long", "ulong")] [InlineData("long", "nint")] [InlineData("long", "nuint")] [InlineData("long", "float")] [InlineData("long", "double")] [InlineData("long", "decimal")] [InlineData("byte", "object")] [InlineData("byte", "string")] [InlineData("byte", "bool")] [InlineData("byte", "long")] [InlineData("byte", "uint")] [InlineData("byte", "ulong")] [InlineData("byte", "nint")] [InlineData("byte", "nuint")] [InlineData("byte", "float")] [InlineData("byte", "double")] [InlineData("byte", "decimal")] [InlineData("ushort", "object")] [InlineData("ushort", "string")] [InlineData("ushort", "bool")] [InlineData("ushort", "long")] [InlineData("ushort", "uint")] [InlineData("ushort", "ulong")] [InlineData("ushort", "nint")] [InlineData("ushort", "nuint")] [InlineData("ushort", "float")] [InlineData("ushort", "double")] [InlineData("ushort", "decimal")] [InlineData("uint", "object")] [InlineData("uint", "string")] [InlineData("uint", "bool")] [InlineData("uint", "long")] [InlineData("uint", "uint")] [InlineData("uint", "ulong")] [InlineData("uint", "nint")] [InlineData("uint", "nuint")] [InlineData("uint", "float")] [InlineData("uint", "double")] [InlineData("uint", "decimal")] [InlineData("ulong", "object")] [InlineData("ulong", "string")] [InlineData("ulong", "bool")] [InlineData("ulong", "long")] [InlineData("ulong", "uint")] [InlineData("ulong", "ulong")] [InlineData("ulong", "nint")] [InlineData("ulong", "nuint")] [InlineData("ulong", "float")] [InlineData("ulong", "double")] [InlineData("ulong", "decimal")] [InlineData("nint", "object")] [InlineData("nint", "string")] [InlineData("nint", "bool")] [InlineData("nint", "long")] [InlineData("nint", "uint")] [InlineData("nint", "ulong")] [InlineData("nint", "nint")] [InlineData("nint", "nuint")] [InlineData("nint", "float")] [InlineData("nint", "double")] [InlineData("nint", "decimal")] [InlineData("nuint", "object")] [InlineData("nuint", "string")] [InlineData("nuint", "bool")] [InlineData("nuint", "long")] [InlineData("nuint", "uint")] [InlineData("nuint", "ulong")] [InlineData("nuint", "nint")] [InlineData("nuint", "nuint")] [InlineData("nuint", "float")] [InlineData("nuint", "double")] [InlineData("nuint", "decimal")] [InlineData("float", "object")] [InlineData("float", "string")] [InlineData("float", "bool")] [InlineData("float", "char")] [InlineData("float", "sbyte")] [InlineData("float", "short")] [InlineData("float", "int")] [InlineData("float", "long")] [InlineData("float", "byte")] [InlineData("float", "ushort")] [InlineData("float", "uint")] [InlineData("float", "ulong")] [InlineData("float", "nint")] [InlineData("float", "nuint")] [InlineData("float", "float")] [InlineData("float", "double")] [InlineData("float", "decimal")] [InlineData("double", "object")] [InlineData("double", "string")] [InlineData("double", "bool")] [InlineData("double", "char")] [InlineData("double", "sbyte")] [InlineData("double", "short")] [InlineData("double", "int")] [InlineData("double", "long")] [InlineData("double", "byte")] [InlineData("double", "ushort")] [InlineData("double", "uint")] [InlineData("double", "ulong")] [InlineData("double", "nint")] [InlineData("double", "nuint")] [InlineData("double", "float")] [InlineData("double", "double")] [InlineData("double", "decimal")] [InlineData("decimal", "object")] [InlineData("decimal", "string")] [InlineData("decimal", "bool")] [InlineData("decimal", "char")] [InlineData("decimal", "sbyte")] [InlineData("decimal", "short")] [InlineData("decimal", "int")] [InlineData("decimal", "long")] [InlineData("decimal", "byte")] [InlineData("decimal", "ushort")] [InlineData("decimal", "uint")] [InlineData("decimal", "ulong")] [InlineData("decimal", "nint")] [InlineData("decimal", "nuint")] [InlineData("decimal", "float")] [InlineData("decimal", "double")] [InlineData("decimal", "decimal")] public void BuiltIn_Lifted_CompoundAssignment_02(string left, string right) { var nullableLeft = NullableIfPossible(left); var nullableRight = NullableIfPossible(right); var source1 = @" class C { static void Main() { " + nullableLeft + @" x = default; " + nullableRight + @" y = default; x >>= y; x >>>= y; } } "; var expected = new[] { // (8,9): error CS0019: Operator '>>=' cannot be applied to operands of type 'double' and 'char' // x >>= y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>= y").WithArguments(">>=", nullableLeft, nullableRight).WithLocation(8, 9), // (9,9): error CS0019: Operator '>>>=' cannot be applied to operands of type 'double' and 'char' // x >>>= y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>>= y").WithArguments(">>>=", nullableLeft, nullableRight).WithLocation(9, 9) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyEmitDiagnostics(expected); } [Fact] public void BuiltIn_CompoundAssignment_CollectionInitializerElement_Lifted() { var source1 = @" class C { static void Main() { int? x = int.MinValue; var y = new System.Collections.Generic.List<int?>() { x >>= 1, x >>>= 1 }; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (8,13): error CS0747: Invalid initializer member declarator // x >>= 1, Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "x >>= 1").WithLocation(8, 13), // (9,13): error CS0747: Invalid initializer member declarator // x >>>= 1 Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "x >>>= 1").WithLocation(9, 13) ); } [Fact] public void BuiltIn_Lifted_ExpressionTree_01() { var source1 = @" class C { static void Main() { System.Linq.Expressions.Expression<System.Func<int?, int?, int?>> e = (x, y) => x >>> y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (6,89): error CS7053: An expression tree may not contain '>>>' // System.Linq.Expressions.Expression<System.Func<int?, int?, int?>> e = (x, y) => x >>> y; Diagnostic(ErrorCode.ERR_FeatureNotValidInExpressionTree, "x >>> y").WithArguments(">>>").WithLocation(6, 89) ); } [Fact] public void BuiltIn_Lifted_CompoundAssignment_ExpressionTree_01() { var source1 = @" class C { static void Main() { System.Linq.Expressions.Expression<System.Func<int?, int?, int?>> e = (x, y) => x >>>= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (6,89): error CS0832: An expression tree may not contain an assignment operator // System.Linq.Expressions.Expression<System.Func<int?, int?, int?>> e = (x, y) => x >>>= y; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "x >>>= y").WithLocation(6, 89) ); } [Fact] public void UserDefined_01() { var source0 = @" public class C1 { public static C1 operator >>>(C1 x, int y) { System.Console.WriteLine("">>>""); return x; } public static C1 operator >>(C1 x, int y) { System.Console.WriteLine("">>""); return x; } } "; var source1 = @" class C { static void Main() { Test1(new C1(), 1); } static C1 Test1(C1 x, int y) => x >>> y; static C1 Test2(C1 x, int y) => x >> y; } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(compilation1, expectedOutput: @">>>").VerifyDiagnostics(); string actualIL = verifier.VisualizeIL("C.Test2"); verifier.VerifyIL("C.Test1", actualIL.Replace("op_RightShift", "op_UnsignedRightShift")); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftExpression).First(); Assert.Equal("x >>> y", unsignedShift.ToString()); Assert.Equal("C1 C1.op_UnsignedRightShift(C1 x, System.Int32 y)", model.GetSymbolInfo(unsignedShift).Symbol.ToTestDisplayString()); Assert.Equal(MethodKind.UserDefinedOperator, compilation1.GetMember<MethodSymbol>("C1.op_UnsignedRightShift").MethodKind); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { compilation0.ToMetadataReference() }, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation2, expectedOutput: @">>>").VerifyDiagnostics(); Assert.Equal(MethodKind.UserDefinedOperator, compilation2.GetMember<MethodSymbol>("C1.op_UnsignedRightShift").MethodKind); var compilation3 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { compilation0.EmitToImageReference() }, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation3, expectedOutput: @">>>").VerifyDiagnostics(); Assert.Equal(MethodKind.UserDefinedOperator, compilation3.GetMember<MethodSymbol>("C1.op_UnsignedRightShift").MethodKind); } [Fact] public void UserDefined_02() { // The IL is equivalent to: // public class C1 // { // public static C1 operator >>>(C1 x, int y) // { // System.Console.WriteLine("">>>""); // return x; // } // } var ilSource = @" .class public auto ansi beforefieldinit C1 extends [mscorlib]System.Object { .method public hidebysig specialname static class C1 op_UnsignedRightShift ( class C1 x, int32 y ) cil managed { .maxstack 8 IL_0000: ldstr "">>>"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldarg.0 IL_000b: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } } "; var source1 = @" class C { static void Main() { Test1(new C1(), 1); } static C1 Test1(C1 x, int y) => C1.op_UnsignedRightShift(x, y); } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); // This code was previously allowed. We are accepting this source breaking change. compilation1.VerifyDiagnostics( // (9,40): error CS0571: 'C1.operator >>>(C1, int)': cannot explicitly call operator or accessor // static C1 Test1(C1 x, int y) => C1.op_UnsignedRightShift(x, y); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_UnsignedRightShift").WithArguments("C1.operator >>>(C1, int)").WithLocation(9, 40) ); } [Fact] public void UserDefined_03() { var source1 = @" public class C1 { public static void operator >>>(C1 x, int y) { throw null; } public static void operator >>(C1 x, int y) { throw null; } } public class C2 { public static C2 operator >>>(C1 x, int y) { throw null; } public static C2 operator >>(C1 x, int y) { throw null; } } public class C3 { public static C3 operator >>>(C3 x, C2 y) { throw null; } public static C3 operator >>(C3 x, C2 y) { throw null; } } public class C4 { public static int operator >>>(C4 x, int y) { throw null; } public static int operator >>(C4 x, int y) { throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyDiagnostics( // (4,33): error CS0590: User-defined operators cannot return void // public static void operator >>>(C1 x, int y) Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, ">>>").WithLocation(4, 33), // (9,33): error CS0590: User-defined operators cannot return void // public static void operator >>(C1 x, int y) Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, ">>").WithLocation(9, 33), // (17,31): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type // public static C2 operator >>>(C1 x, int y) Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, ">>>").WithLocation(17, 31), // (22,31): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type // public static C2 operator >>(C1 x, int y) Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, ">>").WithLocation(22, 31) ); } [Fact] public void UserDefined_04() { var source1 = @" public class C1 { public static C1 operator >>>(C1 x, int y) { throw null; } public static C1 op_UnsignedRightShift(C1 x, int y) { throw null; } } public class C2 { public static C2 op_UnsignedRightShift(C2 x, int y) { throw null; } public static C2 operator >>>(C2 x, int y) { throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyDiagnostics( // (9,22): error CS0111: Type 'C1' already defines a member called 'op_UnsignedRightShift' with the same parameter types // public static C1 op_UnsignedRightShift(C1 x, int y) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_UnsignedRightShift").WithArguments("op_UnsignedRightShift", "C1").WithLocation(9, 22), // (22,31): error CS0111: Type 'C2' already defines a member called 'op_UnsignedRightShift' with the same parameter types // public static C2 operator >>>(C2 x, int y) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, ">>>").WithArguments("op_UnsignedRightShift", "C2").WithLocation(22, 31) ); } [Fact] public void UserDefined_05() { var source0 = @" public struct C1 { public static C1 operator >>>(C1? x, int? y) { System.Console.WriteLine("">>>""); return x.Value; } public static C1 operator >>(C1? x, int? y) { System.Console.WriteLine("">>""); return x.Value; } } "; var source1 = @" class C { static void Main() { Test1(new C1(), 1); } static C1 Test1(C1? x, int? y) => x >>> y; static C1 Test2(C1? x, int? y) => x >> y; } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(compilation1, expectedOutput: @">>>").VerifyDiagnostics(); string actualIL = verifier.VisualizeIL("C.Test2"); verifier.VerifyIL("C.Test1", actualIL.Replace("op_RightShift", "op_UnsignedRightShift")); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftExpression).First(); Assert.Equal("x >>> y", unsignedShift.ToString()); Assert.Equal("C1 C1.op_UnsignedRightShift(C1? x, System.Int32? y)", model.GetSymbolInfo(unsignedShift).Symbol.ToTestDisplayString()); Assert.Equal(MethodKind.UserDefinedOperator, compilation1.GetMember<MethodSymbol>("C1.op_UnsignedRightShift").MethodKind); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { compilation0.ToMetadataReference() }, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation2, expectedOutput: @">>>").VerifyDiagnostics(); Assert.Equal(MethodKind.UserDefinedOperator, compilation2.GetMember<MethodSymbol>("C1.op_UnsignedRightShift").MethodKind); var compilation3 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { compilation0.EmitToImageReference() }, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation3, expectedOutput: @">>>").VerifyDiagnostics(); Assert.Equal(MethodKind.UserDefinedOperator, compilation3.GetMember<MethodSymbol>("C1.op_UnsignedRightShift").MethodKind); } [Fact] public void UserDefined_06() { var source0 = @" public class C1 { public static C1 op_UnsignedRightShift(C1 x, int y) { return x; } } "; var source1 = @" class C { static C1 Test1(C1 x, int y) => x >>> y; } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { compilation0.ToMetadataReference() }, parseOptions: TestOptions.RegularPreview); compilation2.VerifyDiagnostics( // (4,37): error CS0019: Operator '>>>' cannot be applied to operands of type 'C1' and 'int' // static C1 Test1(C1 x, int y) => x >>> y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>> y").WithArguments(">>>", "C1", "int").WithLocation(4, 37) ); var compilation3 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { compilation0.EmitToImageReference() }, parseOptions: TestOptions.RegularPreview); compilation3.VerifyDiagnostics( // (4,37): error CS0019: Operator '>>>' cannot be applied to operands of type 'C1' and 'int' // static C1 Test1(C1 x, int y) => x >>> y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>> y").WithArguments(">>>", "C1", "int").WithLocation(4, 37) ); } [Fact] public void UserDefined_ExpressionTree_01() { var source1 = @" public class C1 { public static C1 operator >>>(C1 x, int y) { return x; } } class C { static void Main() { System.Linq.Expressions.Expression<System.Func<C1, int, C1>> e = (x, y) => x >>> y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (14,84): error CS7053: An expression tree may not contain '>>>' // System.Linq.Expressions.Expression<System.Func<C1, int, C1>> e = (x, y) => x >>> y; Diagnostic(ErrorCode.ERR_FeatureNotValidInExpressionTree, "x >>> y").WithArguments(">>>").WithLocation(14, 84) ); } [Fact] public void UserDefined_CompountAssignment_01() { var source1 = @" public class C1 { public int F; public static C1 operator >>>(C1 x, int y) { return new C1() { F = x.F >>> y }; } public static C1 operator >>(C1 x, int y) { return x; } } class C { static void Main() { if (Test1(new C1() { F = int.MinValue }, 1).F == (int.MinValue >>> 1)) System.Console.WriteLine(""Passed 1""); } static C1 Test1(C1 x, int y) { x >>>= y; return x; } static C1 Test2(C1 x, int y) { x >>= y; return x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(compilation1, expectedOutput: @"Passed 1").VerifyDiagnostics(); string actualIL = verifier.VisualizeIL("C.Test2"); verifier.VerifyIL("C.Test1", actualIL.Replace("op_RightShift", "op_UnsignedRightShift")); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftAssignmentExpression).First(); Assert.Equal("x >>>= y", unsignedShift.ToString()); Assert.Equal("C1 C1.op_UnsignedRightShift(C1 x, System.Int32 y)", model.GetSymbolInfo(unsignedShift).Symbol.ToTestDisplayString()); } [Fact] public void UserDefined_CompoundAssignment_ExpressionTree_01() { var source1 = @" public class C1 { public static C1 operator >>>(C1 x, int y) { return x; } } class C { static void Main() { System.Linq.Expressions.Expression<System.Func<C1, int, C1>> e = (x, y) => x >>>= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (14,84): error CS0832: An expression tree may not contain an assignment operator // System.Linq.Expressions.Expression<System.Func<C1, int, C1>> e = (x, y) => x >>>= y; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "x >>>= y").WithLocation(14, 84) ); } [Fact] public void UserDefined_CompoundAssignment_CollectionInitializerElement() { var source1 = @" public class C1 { public static C1 operator >>>(C1 x, int y) { return x; } public static C1 operator >>(C1 x, int y) { return x; } } class C { static void Main() { var x = new C1(); var y = new System.Collections.Generic.List<C1>() { x >>= 1, x >>>= 1 }; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (21,13): error CS0747: Invalid initializer member declarator // x >>= 1, Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "x >>= 1").WithLocation(21, 13), // (22,13): error CS0747: Invalid initializer member declarator // x >>>= 1 Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "x >>>= 1").WithLocation(22, 13) ); } [Fact] public void UserDefined_Lifted_01() { var source0 = @" public struct C1 { public static C1 operator >>>(C1 x, int y) { System.Console.WriteLine("">>>""); return x; } public static C1 operator >>(C1 x, int y) { System.Console.WriteLine("">>""); return x; } } "; var source1 = @" class C { static void Main() { if (Test1(new C1(), 1) is not null) System.Console.WriteLine(""Passed 1""); if (Test1(null, 1) is null) System.Console.WriteLine(""Passed 2""); if (Test1(new C1(), null) is null) System.Console.WriteLine(""Passed 3""); if (Test1(null, null) is null) System.Console.WriteLine(""Passed 4""); } static C1? Test1(C1? x, int? y) => x >>> y; static C1? Test2(C1? x, int? y) => x >> y; } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(compilation1, expectedOutput: @" >>> Passed 1 Passed 2 Passed 3 Passed 4 ").VerifyDiagnostics(); string actualIL = verifier.VisualizeIL("C.Test2"); verifier.VerifyIL("C.Test1", actualIL.Replace("op_RightShift", "op_UnsignedRightShift")); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftExpression).First(); Assert.Equal("x >>> y", unsignedShift.ToString()); Assert.Equal("C1 C1.op_UnsignedRightShift(C1 x, System.Int32 y)", model.GetSymbolInfo(unsignedShift).Symbol.ToTestDisplayString()); } [Fact] public void UserDefined_Lifted_ExpressionTree_01() { var source1 = @" public struct C1 { public static C1 operator >>>(C1 x, int y) { return x; } } class C { static void Main() { System.Linq.Expressions.Expression<System.Func<C1?, int?, C1?>> e = (x, y) => x >>> y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (14,87): error CS7053: An expression tree may not contain '>>>' // System.Linq.Expressions.Expression<System.Func<C1?, int?, C1?>> e = (x, y) => x >>> y; Diagnostic(ErrorCode.ERR_FeatureNotValidInExpressionTree, "x >>> y").WithArguments(">>>").WithLocation(14, 87) ); } [Fact] public void UserDefined_Lifted_CompountAssignment_01() { var source1 = @" public struct C1 { public int F; public static C1 operator >>>(C1 x, int y) { return new C1() { F = x.F >>> y }; } public static C1 operator >>(C1 x, int y) { return x; } } class C { static void Main() { if (Test1(new C1() { F = int.MinValue }, 1).Value.F == (int.MinValue >>> 1)) System.Console.WriteLine(""Passed 1""); if (Test1(null, 1) is null) System.Console.WriteLine(""Passed 2""); if (Test1(new C1(), null) is null) System.Console.WriteLine(""Passed 3""); if (Test1(null, null) is null) System.Console.WriteLine(""Passed 4""); } static C1? Test1(C1? x, int? y) { x >>>= y; return x; } static C1? Test2(C1? x, int? y) { x >>= y; return x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(compilation1, expectedOutput: @" Passed 1 Passed 2 Passed 3 Passed 4 ").VerifyDiagnostics(); string actualIL = verifier.VisualizeIL("C.Test2"); verifier.VerifyIL("C.Test1", actualIL.Replace("op_RightShift", "op_UnsignedRightShift")); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftAssignmentExpression).First(); Assert.Equal("x >>>= y", unsignedShift.ToString()); Assert.Equal("C1 C1.op_UnsignedRightShift(C1 x, System.Int32 y)", model.GetSymbolInfo(unsignedShift).Symbol.ToTestDisplayString()); } [Fact] public void UserDefined_Lifted_CompoundAssignment_ExpressionTree_01() { var source1 = @" public struct C1 { public static C1 operator >>>(C1 x, int y) { return x; } } class C { static void Main() { System.Linq.Expressions.Expression<System.Func<C1?, int?, C1?>> e = (x, y) => x >>>= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (14,87): error CS0832: An expression tree may not contain an assignment operator // System.Linq.Expressions.Expression<System.Func<C1?, int?, C1?>> e = (x, y) => x >>>= y; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "x >>>= y").WithLocation(14, 87) ); } [Fact] public void UserDefined_Lifted_CompoundAssignment_CollectionInitializerElement() { var source1 = @" public struct C1 { public static C1 operator >>>(C1 x, int y) { return x; } public static C1 operator >>(C1 x, int y) { return x; } } class C { static void Main() { C1? x = new C1(); var y = new System.Collections.Generic.List<C1?>() { x >>= 1, x >>>= 1 }; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (21,13): error CS0747: Invalid initializer member declarator // x >>= 1, Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "x >>= 1").WithLocation(21, 13), // (22,13): error CS0747: Invalid initializer member declarator // x >>>= 1 Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "x >>>= 1").WithLocation(22, 13) ); } [Fact] public void CRef_NoParameters_01() { var source = @" /// <summary> /// See <see cref=""operator >>>""/>. /// </summary> class C { public static C operator >>>(C c, int y) { return null; } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var expectedSymbol = compilation.SourceModule.GlobalNamespace.GetTypeMember("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind != MethodKind.Constructor).First(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation); Assert.Equal(expectedSymbol, actualSymbol); compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.Regular10.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics( // (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute 'operator >>>' // /// See <see cref="operator >>>"/>. Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "operator >>>").WithArguments("operator >>>").WithLocation(3, 20), // (3,29): warning CS1658: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.. See also error CS8652. // /// See <see cref="operator >>>"/>. Diagnostic(ErrorCode.WRN_ErrorOverride, ">>>").WithArguments("The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.", "8652").WithLocation(3, 29), // (7,30): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public static C operator >>>(C c, int y) Diagnostic(ErrorCode.ERR_FeatureInPreview, ">>>").WithArguments("unsigned right shift").WithLocation(7, 30) ); crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); expectedSymbol = compilation.SourceModule.GlobalNamespace.GetTypeMember("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind != MethodKind.Constructor).First(); actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation); Assert.Equal(expectedSymbol, actualSymbol); compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularNext.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(); crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); expectedSymbol = compilation.SourceModule.GlobalNamespace.GetTypeMember("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind != MethodKind.Constructor).First(); actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation); Assert.Equal(expectedSymbol, actualSymbol); } [Fact] public void CRef_NoParameters_02() { var source = @" /// <summary> /// See <see cref=""operator >>>""/>. /// </summary> class C { public static C operator >>(C c, int y) { return null; } } "; var expected = new[] { // (3,20): warning CS1574: XML comment has cref attribute 'operator >>>' that could not be resolved // /// See <see cref="operator >>>"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "operator >>>").WithArguments("operator >>>").WithLocation(3, 20) }; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(expected); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation, expected); Assert.Null(actualSymbol); } [Fact] public void CRef_NoParameters_03() { var source = @" /// <summary> /// See <see cref=""operator >>""/>. /// </summary> class C { public static C operator >>>(C c, int y) { return null; } } "; var expected = new[] { // (3,20): warning CS1574: XML comment has cref attribute 'operator >>' that could not be resolved // /// See <see cref="operator >>"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "operator >>").WithArguments("operator >>").WithLocation(3, 20) }; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(expected); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation, expected); Assert.Null(actualSymbol); } [Fact] public void CRef_NoParameters_04() { var source = @" /// <summary> /// See <see cref=""operator >>>=""/>. /// </summary> class C { public static C operator >>>(C c, int y) { return null; } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics( // (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute 'operator >>>=' // /// See <see cref="operator >>>="/>. Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "operator").WithArguments("operator >>>=").WithLocation(3, 20), // (3,28): warning CS1658: Overloadable operator expected. See also error CS1037. // /// See <see cref="operator >>>="/>. Diagnostic(ErrorCode.WRN_ErrorOverride, " >>>").WithArguments("Overloadable operator expected", "1037").WithLocation(3, 28) ); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation, // (3,20): warning CS1574: XML comment has cref attribute 'operator' that could not be resolved // /// See <see cref="operator >>>="/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "operator").WithArguments("operator").WithLocation(3, 20) ); Assert.Null(actualSymbol); } [Fact] public void CRef_OneParameter_01() { var source = @" /// <summary> /// See <see cref=""operator >>>(C)""/>. /// </summary> class C { public static C operator >>>(C c, int y) { return null; } } "; var expected = new[] { // (3,20): warning CS1574: XML comment has cref attribute 'operator >>>(C)' that could not be resolved // /// See <see cref="operator >>>(C)"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "operator >>>(C)").WithArguments("operator >>>(C)").WithLocation(3, 20) }; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(expected); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation, expected); Assert.Null(actualSymbol); } [Fact] public void CRef_TwoParameters_01() { var source = @" /// <summary> /// See <see cref=""operator >>>(C, int)""/>. /// </summary> class C { public static C operator >>>(C c, int y) { return null; } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var expectedSymbol = compilation.SourceModule.GlobalNamespace.GetTypeMember("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind != MethodKind.Constructor).First(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation); Assert.Equal(expectedSymbol, actualSymbol); compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.Regular10.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics( // (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute 'operator >>>(C, int)' // /// See <see cref="operator >>>(C, int)"/>. Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "operator >>>(C, int)").WithArguments("operator >>>(C, int)").WithLocation(3, 20), // (3,29): warning CS1658: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.. See also error CS8652. // /// See <see cref="operator >>>(C, int)"/>. Diagnostic(ErrorCode.WRN_ErrorOverride, ">>>").WithArguments("The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.", "8652").WithLocation(3, 29), // (7,30): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public static C operator >>>(C c, int y) Diagnostic(ErrorCode.ERR_FeatureInPreview, ">>>").WithArguments("unsigned right shift").WithLocation(7, 30) ); crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); expectedSymbol = compilation.SourceModule.GlobalNamespace.GetTypeMember("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind != MethodKind.Constructor).First(); actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation); Assert.Equal(expectedSymbol, actualSymbol); compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularNext.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(); crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); expectedSymbol = compilation.SourceModule.GlobalNamespace.GetTypeMember("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind != MethodKind.Constructor).First(); actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation); Assert.Equal(expectedSymbol, actualSymbol); } [Fact] public void CRef_TwoParameters_02() { var source = @" /// <summary> /// See <see cref=""operator >>>(C, int)""/>. /// </summary> class C { public static C operator >>(C c, int y) { return null; } } "; var expected = new[] { // (3,20): warning CS1574: XML comment has cref attribute 'operator >>>(C, int)' that could not be resolved // /// See <see cref="operator >>>(C, int)"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "operator >>>(C, int)").WithArguments("operator >>>(C, int)").WithLocation(3, 20) }; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(expected); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation, expected); Assert.Null(actualSymbol); } [Fact] public void CRef_TwoParameters_03() { var source = @" /// <summary> /// See <see cref=""operator >>(C, int)""/>. /// </summary> class C { public static C operator >>>(C c, int y) { return null; } } "; var expected = new[] { // (3,20): warning CS1574: XML comment has cref attribute 'operator >>(C, int)' that could not be resolved // /// See <see cref="operator >>(C, int)"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "operator >>(C, int)").WithArguments("operator >>(C, int)").WithLocation(3, 20) }; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(expected); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation, expected); Assert.Null(actualSymbol); } [Fact] public void CRef_TwoParameters_04() { var source = @" /// <summary> /// See <see cref=""operator >>>=(C, int)""/>. /// </summary> class C { public static C operator >>>(C c, int y) { return null; } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics( // (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute 'operator >>>=(C, int)' // /// See <see cref="operator >>>=(C, int)"/>. Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "operator >>>=(C, int)").WithArguments("operator >>>=(C, int)").WithLocation(3, 20), // (3,28): warning CS1658: Overloadable operator expected. See also error CS1037. // /// See <see cref="operator >>>=(C, int)"/>. Diagnostic(ErrorCode.WRN_ErrorOverride, " >>>").WithArguments("Overloadable operator expected", "1037").WithLocation(3, 28) ); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation, // (3,20): warning CS1574: XML comment has cref attribute 'operator >>>=(C, int)' that could not be resolved // /// See <see cref="operator >>>=(C, int)"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "operator >>>=(C, int)").WithArguments("operator >>>=(C, int)").WithLocation(3, 20) ); Assert.Null(actualSymbol); } [Fact] public void CRef_ThreeParameter_01() { var source = @" /// <summary> /// See <see cref=""operator >>>(C, int, object)""/>. /// </summary> class C { public static C operator >>>(C c, int y) { return null; } } "; var expected = new[] { // (3,20): warning CS1574: XML comment has cref attribute 'operator >>>(C, int, object)' that could not be resolved // /// See <see cref="operator >>>(C, int, object)"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "operator >>>(C, int, object)").WithArguments("operator >>>(C, int, object)").WithLocation(3, 20) }; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(expected); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation, expected); Assert.Null(actualSymbol); } [Theory] [InlineData("char", "char")] [InlineData("char", "sbyte")] [InlineData("char", "short")] [InlineData("char", "int")] [InlineData("char", "byte")] [InlineData("char", "ushort")] [InlineData("sbyte", "char")] [InlineData("sbyte", "sbyte")] [InlineData("sbyte", "short")] [InlineData("sbyte", "int")] [InlineData("sbyte", "byte")] [InlineData("sbyte", "ushort")] [InlineData("short", "char")] [InlineData("short", "sbyte")] [InlineData("short", "short")] [InlineData("short", "int")] [InlineData("short", "byte")] [InlineData("short", "ushort")] [InlineData("int", "char")] [InlineData("int", "sbyte")] [InlineData("int", "short")] [InlineData("int", "int")] [InlineData("int", "byte")] [InlineData("int", "ushort")] [InlineData("long", "char")] [InlineData("long", "sbyte")] [InlineData("long", "short")] [InlineData("long", "int")] [InlineData("long", "byte")] [InlineData("long", "ushort")] [InlineData("byte", "char")] [InlineData("byte", "sbyte")] [InlineData("byte", "short")] [InlineData("byte", "int")] [InlineData("byte", "byte")] [InlineData("byte", "ushort")] [InlineData("ushort", "char")] [InlineData("ushort", "sbyte")] [InlineData("ushort", "short")] [InlineData("ushort", "int")] [InlineData("ushort", "byte")] [InlineData("ushort", "ushort")] [InlineData("uint", "char")] [InlineData("uint", "sbyte")] [InlineData("uint", "short")] [InlineData("uint", "int")] [InlineData("uint", "byte")] [InlineData("uint", "ushort")] [InlineData("ulong", "char")] [InlineData("ulong", "sbyte")] [InlineData("ulong", "short")] [InlineData("ulong", "int")] [InlineData("ulong", "byte")] [InlineData("ulong", "ushort")] [InlineData("nint", "char")] [InlineData("nint", "sbyte")] [InlineData("nint", "short")] [InlineData("nint", "int")] [InlineData("nint", "byte")] [InlineData("nint", "ushort")] [InlineData("nuint", "char")] [InlineData("nuint", "sbyte")] [InlineData("nuint", "short")] [InlineData("nuint", "int")] [InlineData("nuint", "byte")] [InlineData("nuint", "ushort")] public void BuiltIn_LangVersion_01(string left, string right) { var source1 = @" class C { static void Main() { " + left + @" x = default; " + right + @" y = default; _ = x >>> y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10); compilation1.VerifyDiagnostics( // (8,13): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x >>> y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x >>> y").WithArguments("unsigned right shift").WithLocation(8, 13) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); compilation2.VerifyDiagnostics(); } [Theory] [InlineData("char", "char")] [InlineData("char", "sbyte")] [InlineData("char", "short")] [InlineData("char", "int")] [InlineData("char", "byte")] [InlineData("char", "ushort")] [InlineData("sbyte", "char")] [InlineData("sbyte", "sbyte")] [InlineData("sbyte", "short")] [InlineData("sbyte", "int")] [InlineData("sbyte", "byte")] [InlineData("sbyte", "ushort")] [InlineData("short", "char")] [InlineData("short", "sbyte")] [InlineData("short", "short")] [InlineData("short", "int")] [InlineData("short", "byte")] [InlineData("short", "ushort")] [InlineData("int", "char")] [InlineData("int", "sbyte")] [InlineData("int", "short")] [InlineData("int", "int")] [InlineData("int", "byte")] [InlineData("int", "ushort")] [InlineData("long", "char")] [InlineData("long", "sbyte")] [InlineData("long", "short")] [InlineData("long", "int")] [InlineData("long", "byte")] [InlineData("long", "ushort")] [InlineData("byte", "char")] [InlineData("byte", "sbyte")] [InlineData("byte", "short")] [InlineData("byte", "int")] [InlineData("byte", "byte")] [InlineData("byte", "ushort")] [InlineData("ushort", "char")] [InlineData("ushort", "sbyte")] [InlineData("ushort", "short")] [InlineData("ushort", "int")] [InlineData("ushort", "byte")] [InlineData("ushort", "ushort")] [InlineData("uint", "char")] [InlineData("uint", "sbyte")] [InlineData("uint", "short")] [InlineData("uint", "int")] [InlineData("uint", "byte")] [InlineData("uint", "ushort")] [InlineData("ulong", "char")] [InlineData("ulong", "sbyte")] [InlineData("ulong", "short")] [InlineData("ulong", "int")] [InlineData("ulong", "byte")] [InlineData("ulong", "ushort")] [InlineData("nint", "char")] [InlineData("nint", "sbyte")] [InlineData("nint", "short")] [InlineData("nint", "int")] [InlineData("nint", "byte")] [InlineData("nint", "ushort")] [InlineData("nuint", "char")] [InlineData("nuint", "sbyte")] [InlineData("nuint", "short")] [InlineData("nuint", "int")] [InlineData("nuint", "byte")] [InlineData("nuint", "ushort")] public void BuiltIn_CompoundAssignment_LangVersion_01(string left, string right) { var source1 = @" class C { static void Main() { " + left + @" x = default; " + right + @" y = default; x >>>= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10); compilation1.VerifyDiagnostics( // (8,9): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x >>>= y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x >>>= y").WithArguments("unsigned right shift").WithLocation(8, 9) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); compilation2.VerifyDiagnostics(); } [Theory] [InlineData("char", "char")] [InlineData("char", "sbyte")] [InlineData("char", "short")] [InlineData("char", "int")] [InlineData("char", "byte")] [InlineData("char", "ushort")] [InlineData("sbyte", "char")] [InlineData("sbyte", "sbyte")] [InlineData("sbyte", "short")] [InlineData("sbyte", "int")] [InlineData("sbyte", "byte")] [InlineData("sbyte", "ushort")] [InlineData("short", "char")] [InlineData("short", "sbyte")] [InlineData("short", "short")] [InlineData("short", "int")] [InlineData("short", "byte")] [InlineData("short", "ushort")] [InlineData("int", "char")] [InlineData("int", "sbyte")] [InlineData("int", "short")] [InlineData("int", "int")] [InlineData("int", "byte")] [InlineData("int", "ushort")] [InlineData("long", "char")] [InlineData("long", "sbyte")] [InlineData("long", "short")] [InlineData("long", "int")] [InlineData("long", "byte")] [InlineData("long", "ushort")] [InlineData("byte", "char")] [InlineData("byte", "sbyte")] [InlineData("byte", "short")] [InlineData("byte", "int")] [InlineData("byte", "byte")] [InlineData("byte", "ushort")] [InlineData("ushort", "char")] [InlineData("ushort", "sbyte")] [InlineData("ushort", "short")] [InlineData("ushort", "int")] [InlineData("ushort", "byte")] [InlineData("ushort", "ushort")] [InlineData("uint", "char")] [InlineData("uint", "sbyte")] [InlineData("uint", "short")] [InlineData("uint", "int")] [InlineData("uint", "byte")] [InlineData("uint", "ushort")] [InlineData("ulong", "char")] [InlineData("ulong", "sbyte")] [InlineData("ulong", "short")] [InlineData("ulong", "int")] [InlineData("ulong", "byte")] [InlineData("ulong", "ushort")] [InlineData("nint", "char")] [InlineData("nint", "sbyte")] [InlineData("nint", "short")] [InlineData("nint", "int")] [InlineData("nint", "byte")] [InlineData("nint", "ushort")] [InlineData("nuint", "char")] [InlineData("nuint", "sbyte")] [InlineData("nuint", "short")] [InlineData("nuint", "int")] [InlineData("nuint", "byte")] [InlineData("nuint", "ushort")] public void BuiltIn_Lifted_LangVersion_01(string left, string right) { var source1 = @" class C { static void Main() { " + left + @"? x = default; " + right + @"? y = default; _ = x >>> y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10); compilation1.VerifyDiagnostics( // (8,13): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x >>> y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x >>> y").WithArguments("unsigned right shift").WithLocation(8, 13) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); compilation2.VerifyDiagnostics(); } [Theory] [InlineData("char", "char")] [InlineData("char", "sbyte")] [InlineData("char", "short")] [InlineData("char", "int")] [InlineData("char", "byte")] [InlineData("char", "ushort")] [InlineData("sbyte", "char")] [InlineData("sbyte", "sbyte")] [InlineData("sbyte", "short")] [InlineData("sbyte", "int")] [InlineData("sbyte", "byte")] [InlineData("sbyte", "ushort")] [InlineData("short", "char")] [InlineData("short", "sbyte")] [InlineData("short", "short")] [InlineData("short", "int")] [InlineData("short", "byte")] [InlineData("short", "ushort")] [InlineData("int", "char")] [InlineData("int", "sbyte")] [InlineData("int", "short")] [InlineData("int", "int")] [InlineData("int", "byte")] [InlineData("int", "ushort")] [InlineData("long", "char")] [InlineData("long", "sbyte")] [InlineData("long", "short")] [InlineData("long", "int")] [InlineData("long", "byte")] [InlineData("long", "ushort")] [InlineData("byte", "char")] [InlineData("byte", "sbyte")] [InlineData("byte", "short")] [InlineData("byte", "int")] [InlineData("byte", "byte")] [InlineData("byte", "ushort")] [InlineData("ushort", "char")] [InlineData("ushort", "sbyte")] [InlineData("ushort", "short")] [InlineData("ushort", "int")] [InlineData("ushort", "byte")] [InlineData("ushort", "ushort")] [InlineData("uint", "char")] [InlineData("uint", "sbyte")] [InlineData("uint", "short")] [InlineData("uint", "int")] [InlineData("uint", "byte")] [InlineData("uint", "ushort")] [InlineData("ulong", "char")] [InlineData("ulong", "sbyte")] [InlineData("ulong", "short")] [InlineData("ulong", "int")] [InlineData("ulong", "byte")] [InlineData("ulong", "ushort")] [InlineData("nint", "char")] [InlineData("nint", "sbyte")] [InlineData("nint", "short")] [InlineData("nint", "int")] [InlineData("nint", "byte")] [InlineData("nint", "ushort")] [InlineData("nuint", "char")] [InlineData("nuint", "sbyte")] [InlineData("nuint", "short")] [InlineData("nuint", "int")] [InlineData("nuint", "byte")] [InlineData("nuint", "ushort")] public void BuiltIn_Lifted_CompoundAssignment_LangVersion_01(string left, string right) { var source1 = @" class C { static void Main() { " + left + @"? x = default; " + right + @"? y = default; x >>>= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10); compilation1.VerifyDiagnostics( // (8,9): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x >>>= y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x >>>= y").WithArguments("unsigned right shift").WithLocation(8, 9) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); compilation2.VerifyDiagnostics(); } [Fact] public void UserDefined_LangVersion_01() { var source0 = @" public class C1 { public static C1 operator >>>(C1 x, int y) { System.Console.WriteLine("">>>""); return x; } } "; var source1 = @" class C { static C1 Test1(C1 x, int y) => x >>> y; } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyDiagnostics( // (4,31): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public static C1 operator >>>(C1 x, int y) Diagnostic(ErrorCode.ERR_FeatureInPreview, ">>>").WithArguments("unsigned right shift").WithLocation(4, 31) ); compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyDiagnostics(); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); foreach (var reference in new[] { compilation0.ToMetadataReference(), compilation0.EmitToImageReference() }) { var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular10); compilation2.VerifyDiagnostics( // (4,37): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static C1 Test1(C1 x, int y) => x >>> y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x >>> y").WithArguments("unsigned right shift").WithLocation(4, 37) ); compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.RegularNext); compilation2.VerifyDiagnostics(); } } [Fact] public void UserDefined_CompountAssignment_LangVersion_01() { var source0 = @" public class C1 { public static C1 operator >>>(C1 x, int y) { System.Console.WriteLine("">>>""); return x; } } "; var source1 = @" class C { static C1 Test1(C1 x, int y) => x >>>= y; } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyDiagnostics( // (4,31): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public static C1 operator >>>(C1 x, int y) Diagnostic(ErrorCode.ERR_FeatureInPreview, ">>>").WithArguments("unsigned right shift").WithLocation(4, 31) ); compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyDiagnostics(); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); foreach (var reference in new[] { compilation0.ToMetadataReference(), compilation0.EmitToImageReference() }) { var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular10); compilation2.VerifyDiagnostics( // (4,37): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static C1 Test1(C1 x, int y) => x >>>= y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x >>>= y").WithArguments("unsigned right shift").WithLocation(4, 37) ); compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.RegularNext); compilation2.VerifyDiagnostics(); } } [Fact] public void UserDefined_Lifted_LangVersion_01() { var source0 = @" public struct C1 { public static C1 operator >>>(C1 x, int y) { System.Console.WriteLine("">>>""); return x; } } "; var source1 = @" class C { static C1? Test1(C1? x, int? y) => x >>> y; } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyDiagnostics( // (4,31): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public static C1 operator >>>(C1 x, int y) Diagnostic(ErrorCode.ERR_FeatureInPreview, ">>>").WithArguments("unsigned right shift").WithLocation(4, 31) ); compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyDiagnostics(); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); foreach (var reference in new[] { compilation0.ToMetadataReference(), compilation0.EmitToImageReference() }) { var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular10); compilation2.VerifyDiagnostics( // (4,40): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static C1? Test1(C1? x, int? y) => x >>> y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x >>> y").WithArguments("unsigned right shift").WithLocation(4, 40) ); compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.RegularNext); compilation2.VerifyDiagnostics(); } } [Fact] public void UserDefined_Lifted_CompountAssignment_LangVersion_01() { var source0 = @" public struct C1 { public static C1 operator >>>(C1 x, int y) { System.Console.WriteLine("">>>""); return x; } } "; var source1 = @" class C { static C1? Test1(C1? x, int? y) => x >>>= y; } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyDiagnostics( // (4,31): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public static C1 operator >>>(C1 x, int y) Diagnostic(ErrorCode.ERR_FeatureInPreview, ">>>").WithArguments("unsigned right shift").WithLocation(4, 31) ); compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyDiagnostics(); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); foreach (var reference in new[] { compilation0.ToMetadataReference(), compilation0.EmitToImageReference() }) { var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular10); compilation2.VerifyDiagnostics( // (4,40): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static C1? Test1(C1? x, int? y) => x >>>= y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x >>>= y").WithArguments("unsigned right shift").WithLocation(4, 40) ); compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.RegularNext); compilation2.VerifyDiagnostics(); } } [Fact] public void TestGenericArgWithGreaterThan_05() { var source1 = @" class C { void M() { var added = ImmutableDictionary<T<(S a, U b)>>> ProjectChange = projectChange; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyDiagnostics( // (6,21): error CS0103: The name 'ImmutableDictionary' does not exist in the current context // var added = ImmutableDictionary<T<(S a, U b)>>> Diagnostic(ErrorCode.ERR_NameNotInContext, "ImmutableDictionary").WithArguments("ImmutableDictionary").WithLocation(6, 21), // (6,41): error CS0103: The name 'T' does not exist in the current context // var added = ImmutableDictionary<T<(S a, U b)>>> Diagnostic(ErrorCode.ERR_NameNotInContext, "T").WithArguments("T").WithLocation(6, 41), // (6,44): error CS0246: The type or namespace name 'S' could not be found (are you missing a using directive or an assembly reference?) // var added = ImmutableDictionary<T<(S a, U b)>>> Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "S").WithArguments("S").WithLocation(6, 44), // (6,44): error CS8185: A declaration is not allowed in this context. // var added = ImmutableDictionary<T<(S a, U b)>>> Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "S a").WithLocation(6, 44), // (6,49): error CS0246: The type or namespace name 'U' could not be found (are you missing a using directive or an assembly reference?) // var added = ImmutableDictionary<T<(S a, U b)>>> Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "U").WithArguments("U").WithLocation(6, 49), // (6,49): error CS8185: A declaration is not allowed in this context. // var added = ImmutableDictionary<T<(S a, U b)>>> Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "U b").WithLocation(6, 49), // (8,9): error CS0103: The name 'ProjectChange' does not exist in the current context // ProjectChange = projectChange; Diagnostic(ErrorCode.ERR_NameNotInContext, "ProjectChange").WithArguments("ProjectChange").WithLocation(8, 9), // (8,25): error CS0103: The name 'projectChange' does not exist in the current context // ProjectChange = projectChange; Diagnostic(ErrorCode.ERR_NameNotInContext, "projectChange").WithArguments("projectChange").WithLocation(8, 25) ); } [Fact] public void CanBeValidAttributeArgument() { string source = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; public class Parent { public void TestRightShift([Optional][DefaultParameterValue(300 >> 1)] int i) { Console.Write(i); } public void TestUnsignedRightShift([Optional][DefaultParameterValue(300 >>> 1)] int i) { Console.Write(i); } } class Test { public static void Main() { var p = new Parent(); p.TestRightShift(); p.TestUnsignedRightShift(); } } "; CompileAndVerify(source, expectedOutput: @"150150", parseOptions: TestOptions.RegularNext); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class UnsignedRightShiftTests : CSharpTestBase { [Theory] [InlineData("char", "char", "ushort.MaxValue", "int", "uint")] [InlineData("char", "sbyte", "ushort.MaxValue", "int", "uint")] [InlineData("char", "short", "ushort.MaxValue", "int", "uint")] [InlineData("char", "int", "ushort.MaxValue", "int", "uint")] [InlineData("char", "byte", "ushort.MaxValue", "int", "uint")] [InlineData("char", "ushort", "ushort.MaxValue", "int", "uint")] [InlineData("sbyte", "char", "sbyte.MinValue", "int", "uint")] [InlineData("sbyte", "sbyte", "sbyte.MinValue", "int", "uint")] [InlineData("sbyte", "short", "sbyte.MinValue", "int", "uint")] [InlineData("sbyte", "int", "sbyte.MinValue", "int", "uint")] [InlineData("sbyte", "byte", "sbyte.MinValue", "int", "uint")] [InlineData("sbyte", "ushort", "sbyte.MinValue", "int", "uint")] [InlineData("short", "char", "short.MinValue", "int", "uint")] [InlineData("short", "sbyte", "short.MinValue", "int", "uint")] [InlineData("short", "short", "short.MinValue", "int", "uint")] [InlineData("short", "int", "short.MinValue", "int", "uint")] [InlineData("short", "byte", "short.MinValue", "int", "uint")] [InlineData("short", "ushort", "short.MinValue", "int", "uint")] [InlineData("int", "char", "int.MinValue", "int", "uint")] [InlineData("int", "sbyte", "int.MinValue", "int", "uint")] [InlineData("int", "short", "int.MinValue", "int", "uint")] [InlineData("int", "int", "int.MinValue", "int", "uint")] [InlineData("int", "byte", "int.MinValue", "int", "uint")] [InlineData("int", "ushort", "int.MinValue", "int", "uint")] [InlineData("long", "char", "long.MinValue", "long", "ulong")] [InlineData("long", "sbyte", "long.MinValue", "long", "ulong")] [InlineData("long", "short", "long.MinValue", "long", "ulong")] [InlineData("long", "int", "long.MinValue", "long", "ulong")] [InlineData("long", "byte", "long.MinValue", "long", "ulong")] [InlineData("long", "ushort", "long.MinValue", "long", "ulong")] [InlineData("byte", "char", "byte.MaxValue", "int", "uint")] [InlineData("byte", "sbyte", "byte.MaxValue", "int", "uint")] [InlineData("byte", "short", "byte.MaxValue", "int", "uint")] [InlineData("byte", "int", "byte.MaxValue", "int", "uint")] [InlineData("byte", "byte", "byte.MaxValue", "int", "uint")] [InlineData("byte", "ushort", "byte.MaxValue", "int", "uint")] [InlineData("ushort", "char", "ushort.MaxValue", "int", "uint")] [InlineData("ushort", "sbyte", "ushort.MaxValue", "int", "uint")] [InlineData("ushort", "short", "ushort.MaxValue", "int", "uint")] [InlineData("ushort", "int", "ushort.MaxValue", "int", "uint")] [InlineData("ushort", "byte", "ushort.MaxValue", "int", "uint")] [InlineData("ushort", "ushort", "ushort.MaxValue", "int", "uint")] [InlineData("uint", "char", "uint.MaxValue", "uint", "uint")] [InlineData("uint", "sbyte", "uint.MaxValue", "uint", "uint")] [InlineData("uint", "short", "uint.MaxValue", "uint", "uint")] [InlineData("uint", "int", "uint.MaxValue", "uint", "uint")] [InlineData("uint", "byte", "uint.MaxValue", "uint", "uint")] [InlineData("uint", "ushort", "uint.MaxValue", "uint", "uint")] [InlineData("ulong", "char", "ulong.MaxValue", "ulong", "ulong")] [InlineData("ulong", "sbyte", "ulong.MaxValue", "ulong", "ulong")] [InlineData("ulong", "short", "ulong.MaxValue", "ulong", "ulong")] [InlineData("ulong", "int", "ulong.MaxValue", "ulong", "ulong")] [InlineData("ulong", "byte", "ulong.MaxValue", "ulong", "ulong")] [InlineData("ulong", "ushort", "ulong.MaxValue", "ulong", "ulong")] [InlineData("nint", "char", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint", "nuint")] [InlineData("nint", "sbyte", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint", "nuint")] [InlineData("nint", "short", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint", "nuint")] [InlineData("nint", "int", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint", "nuint")] [InlineData("nint", "byte", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint", "nuint")] [InlineData("nint", "ushort", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint", "nuint")] [InlineData("nuint", "char", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint", "nuint")] [InlineData("nuint", "sbyte", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint", "nuint")] [InlineData("nuint", "short", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint", "nuint")] [InlineData("nuint", "int", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint", "nuint")] [InlineData("nuint", "byte", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint", "nuint")] [InlineData("nuint", "ushort", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint", "nuint")] public void BuiltIn_01(string left, string right, string leftValue, string result, string unsignedResult) { var source1 = @" class C { static void Main() { var x = (" + left + @")" + leftValue + @"; var y = (" + right + @")1; var z1 = x >>> y; var z2 = x >> y; if (z1 == unchecked((" + result + @")(((" + unsignedResult + @")(" + result + @")x) >> y))) System.Console.WriteLine(""Passed 1""); if (x > 0 ? z1 == z2 : z1 != z2) System.Console.WriteLine(""Passed 2""); if (z1.GetType() == z2.GetType() && z1.GetType() == typeof(" + result + @")) System.Console.WriteLine(""Passed 3""); } " + result + @" Test1(" + left + @" x, " + right + @" y) => x >>> y; " + result + @" Test2(" + left + @" x, " + right + @" y) => x >> y; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(compilation1, expectedOutput: @" Passed 1 Passed 2 Passed 3 ").VerifyDiagnostics(); string actualIL = verifier.VisualizeIL("C.Test2"); verifier.VerifyIL("C.Test1", actualIL.Replace("shr.un", "shr").Replace("shr", "shr.un")); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftExpression).First(); var shift = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.RightShiftExpression).First(); Assert.Equal("x >>> y", unsignedShift.ToString()); Assert.Equal("x >> y", shift.ToString()); var unsignedShiftSymbol = (IMethodSymbol)model.GetSymbolInfo(unsignedShift).Symbol; var shiftSymbol = (IMethodSymbol)model.GetSymbolInfo(shift).Symbol; Assert.Equal("op_UnsignedRightShift", unsignedShiftSymbol.Name); Assert.Equal("op_RightShift", shiftSymbol.Name); Assert.Same(shiftSymbol.ReturnType, unsignedShiftSymbol.ReturnType); Assert.Same(shiftSymbol.Parameters[0].Type, unsignedShiftSymbol.Parameters[0].Type); Assert.Same(shiftSymbol.Parameters[1].Type, unsignedShiftSymbol.Parameters[1].Type); Assert.Same(shiftSymbol.ContainingSymbol, unsignedShiftSymbol.ContainingSymbol); } [Theory] [InlineData("object", "object")] [InlineData("object", "string")] [InlineData("object", "bool")] [InlineData("object", "char")] [InlineData("object", "sbyte")] [InlineData("object", "short")] [InlineData("object", "int")] [InlineData("object", "long")] [InlineData("object", "byte")] [InlineData("object", "ushort")] [InlineData("object", "uint")] [InlineData("object", "ulong")] [InlineData("object", "nint")] [InlineData("object", "nuint")] [InlineData("object", "float")] [InlineData("object", "double")] [InlineData("object", "decimal")] [InlineData("string", "object")] [InlineData("string", "string")] [InlineData("string", "bool")] [InlineData("string", "char")] [InlineData("string", "sbyte")] [InlineData("string", "short")] [InlineData("string", "int")] [InlineData("string", "long")] [InlineData("string", "byte")] [InlineData("string", "ushort")] [InlineData("string", "uint")] [InlineData("string", "ulong")] [InlineData("string", "nint")] [InlineData("string", "nuint")] [InlineData("string", "float")] [InlineData("string", "double")] [InlineData("string", "decimal")] [InlineData("bool", "object")] [InlineData("bool", "string")] [InlineData("bool", "bool")] [InlineData("bool", "char")] [InlineData("bool", "sbyte")] [InlineData("bool", "short")] [InlineData("bool", "int")] [InlineData("bool", "long")] [InlineData("bool", "byte")] [InlineData("bool", "ushort")] [InlineData("bool", "uint")] [InlineData("bool", "ulong")] [InlineData("bool", "nint")] [InlineData("bool", "nuint")] [InlineData("bool", "float")] [InlineData("bool", "double")] [InlineData("bool", "decimal")] [InlineData("char", "object")] [InlineData("char", "string")] [InlineData("char", "bool")] [InlineData("char", "long")] [InlineData("char", "uint")] [InlineData("char", "ulong")] [InlineData("char", "nint")] [InlineData("char", "nuint")] [InlineData("char", "float")] [InlineData("char", "double")] [InlineData("char", "decimal")] [InlineData("sbyte", "object")] [InlineData("sbyte", "string")] [InlineData("sbyte", "bool")] [InlineData("sbyte", "long")] [InlineData("sbyte", "uint")] [InlineData("sbyte", "ulong")] [InlineData("sbyte", "nint")] [InlineData("sbyte", "nuint")] [InlineData("sbyte", "float")] [InlineData("sbyte", "double")] [InlineData("sbyte", "decimal")] [InlineData("short", "object")] [InlineData("short", "string")] [InlineData("short", "bool")] [InlineData("short", "long")] [InlineData("short", "uint")] [InlineData("short", "ulong")] [InlineData("short", "nint")] [InlineData("short", "nuint")] [InlineData("short", "float")] [InlineData("short", "double")] [InlineData("short", "decimal")] [InlineData("int", "object")] [InlineData("int", "string")] [InlineData("int", "bool")] [InlineData("int", "long")] [InlineData("int", "uint")] [InlineData("int", "ulong")] [InlineData("int", "nint")] [InlineData("int", "nuint")] [InlineData("int", "float")] [InlineData("int", "double")] [InlineData("int", "decimal")] [InlineData("long", "object")] [InlineData("long", "string")] [InlineData("long", "bool")] [InlineData("long", "long")] [InlineData("long", "uint")] [InlineData("long", "ulong")] [InlineData("long", "nint")] [InlineData("long", "nuint")] [InlineData("long", "float")] [InlineData("long", "double")] [InlineData("long", "decimal")] [InlineData("byte", "object")] [InlineData("byte", "string")] [InlineData("byte", "bool")] [InlineData("byte", "long")] [InlineData("byte", "uint")] [InlineData("byte", "ulong")] [InlineData("byte", "nint")] [InlineData("byte", "nuint")] [InlineData("byte", "float")] [InlineData("byte", "double")] [InlineData("byte", "decimal")] [InlineData("ushort", "object")] [InlineData("ushort", "string")] [InlineData("ushort", "bool")] [InlineData("ushort", "long")] [InlineData("ushort", "uint")] [InlineData("ushort", "ulong")] [InlineData("ushort", "nint")] [InlineData("ushort", "nuint")] [InlineData("ushort", "float")] [InlineData("ushort", "double")] [InlineData("ushort", "decimal")] [InlineData("uint", "object")] [InlineData("uint", "string")] [InlineData("uint", "bool")] [InlineData("uint", "long")] [InlineData("uint", "uint")] [InlineData("uint", "ulong")] [InlineData("uint", "nint")] [InlineData("uint", "nuint")] [InlineData("uint", "float")] [InlineData("uint", "double")] [InlineData("uint", "decimal")] [InlineData("ulong", "object")] [InlineData("ulong", "string")] [InlineData("ulong", "bool")] [InlineData("ulong", "long")] [InlineData("ulong", "uint")] [InlineData("ulong", "ulong")] [InlineData("ulong", "nint")] [InlineData("ulong", "nuint")] [InlineData("ulong", "float")] [InlineData("ulong", "double")] [InlineData("ulong", "decimal")] [InlineData("nint", "object")] [InlineData("nint", "string")] [InlineData("nint", "bool")] [InlineData("nint", "long")] [InlineData("nint", "uint")] [InlineData("nint", "ulong")] [InlineData("nint", "nint")] [InlineData("nint", "nuint")] [InlineData("nint", "float")] [InlineData("nint", "double")] [InlineData("nint", "decimal")] [InlineData("nuint", "object")] [InlineData("nuint", "string")] [InlineData("nuint", "bool")] [InlineData("nuint", "long")] [InlineData("nuint", "uint")] [InlineData("nuint", "ulong")] [InlineData("nuint", "nint")] [InlineData("nuint", "nuint")] [InlineData("nuint", "float")] [InlineData("nuint", "double")] [InlineData("nuint", "decimal")] [InlineData("float", "object")] [InlineData("float", "string")] [InlineData("float", "bool")] [InlineData("float", "char")] [InlineData("float", "sbyte")] [InlineData("float", "short")] [InlineData("float", "int")] [InlineData("float", "long")] [InlineData("float", "byte")] [InlineData("float", "ushort")] [InlineData("float", "uint")] [InlineData("float", "ulong")] [InlineData("float", "nint")] [InlineData("float", "nuint")] [InlineData("float", "float")] [InlineData("float", "double")] [InlineData("float", "decimal")] [InlineData("double", "object")] [InlineData("double", "string")] [InlineData("double", "bool")] [InlineData("double", "char")] [InlineData("double", "sbyte")] [InlineData("double", "short")] [InlineData("double", "int")] [InlineData("double", "long")] [InlineData("double", "byte")] [InlineData("double", "ushort")] [InlineData("double", "uint")] [InlineData("double", "ulong")] [InlineData("double", "nint")] [InlineData("double", "nuint")] [InlineData("double", "float")] [InlineData("double", "double")] [InlineData("double", "decimal")] [InlineData("decimal", "object")] [InlineData("decimal", "string")] [InlineData("decimal", "bool")] [InlineData("decimal", "char")] [InlineData("decimal", "sbyte")] [InlineData("decimal", "short")] [InlineData("decimal", "int")] [InlineData("decimal", "long")] [InlineData("decimal", "byte")] [InlineData("decimal", "ushort")] [InlineData("decimal", "uint")] [InlineData("decimal", "ulong")] [InlineData("decimal", "nint")] [InlineData("decimal", "nuint")] [InlineData("decimal", "float")] [InlineData("decimal", "double")] [InlineData("decimal", "decimal")] public void BuiltIn_02(string left, string right) { var source1 = @" class C { static void Main() { " + left + @" x = default; " + right + @" y = default; var z1 = x >> y; var z2 = x >>> y; } } "; var expected = new[] { // (8,18): error CS0019: Operator '>>' cannot be applied to operands of type 'object' and 'object' // var z1 = x >> y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >> y").WithArguments(">>", left, right).WithLocation(8, 18), // (9,18): error CS0019: Operator '>>>' cannot be applied to operands of type 'object' and 'object' // var z2 = x >>> y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>> y").WithArguments(">>>", left, right).WithLocation(9, 18) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyEmitDiagnostics(expected); } [Theory] [InlineData("char", "char", "ushort.MaxValue", "int")] [InlineData("char", "sbyte", "ushort.MaxValue", "int")] [InlineData("char", "short", "ushort.MaxValue", "int")] [InlineData("char", "int", "ushort.MaxValue", "int")] [InlineData("char", "byte", "ushort.MaxValue", "int")] [InlineData("char", "ushort", "ushort.MaxValue", "int")] [InlineData("sbyte", "char", "sbyte.MinValue", "int")] [InlineData("sbyte", "sbyte", "sbyte.MinValue", "int")] [InlineData("sbyte", "short", "sbyte.MinValue", "int")] [InlineData("sbyte", "int", "sbyte.MinValue", "int")] [InlineData("sbyte", "byte", "sbyte.MinValue", "int")] [InlineData("sbyte", "ushort", "sbyte.MinValue", "int")] [InlineData("short", "char", "short.MinValue", "int")] [InlineData("short", "sbyte", "short.MinValue", "int")] [InlineData("short", "short", "short.MinValue", "int")] [InlineData("short", "int", "short.MinValue", "int")] [InlineData("short", "byte", "short.MinValue", "int")] [InlineData("short", "ushort", "short.MinValue", "int")] [InlineData("int", "char", "int.MinValue", "int")] [InlineData("int", "sbyte", "int.MinValue", "int")] [InlineData("int", "short", "int.MinValue", "int")] [InlineData("int", "int", "int.MinValue", "int")] [InlineData("int", "byte", "int.MinValue", "int")] [InlineData("int", "ushort", "int.MinValue", "int")] [InlineData("long", "char", "long.MinValue", "long")] [InlineData("long", "sbyte", "long.MinValue", "long")] [InlineData("long", "short", "long.MinValue", "long")] [InlineData("long", "int", "long.MinValue", "long")] [InlineData("long", "byte", "long.MinValue", "long")] [InlineData("long", "ushort", "long.MinValue", "long")] [InlineData("byte", "char", "byte.MaxValue", "int")] [InlineData("byte", "sbyte", "byte.MaxValue", "int")] [InlineData("byte", "short", "byte.MaxValue", "int")] [InlineData("byte", "int", "byte.MaxValue", "int")] [InlineData("byte", "byte", "byte.MaxValue", "int")] [InlineData("byte", "ushort", "byte.MaxValue", "int")] [InlineData("ushort", "char", "ushort.MaxValue", "int")] [InlineData("ushort", "sbyte", "ushort.MaxValue", "int")] [InlineData("ushort", "short", "ushort.MaxValue", "int")] [InlineData("ushort", "int", "ushort.MaxValue", "int")] [InlineData("ushort", "byte", "ushort.MaxValue", "int")] [InlineData("ushort", "ushort", "ushort.MaxValue", "int")] [InlineData("uint", "char", "uint.MaxValue", "uint")] [InlineData("uint", "sbyte", "uint.MaxValue", "uint")] [InlineData("uint", "short", "uint.MaxValue", "uint")] [InlineData("uint", "int", "uint.MaxValue", "uint")] [InlineData("uint", "byte", "uint.MaxValue", "uint")] [InlineData("uint", "ushort", "uint.MaxValue", "uint")] [InlineData("ulong", "char", "ulong.MaxValue", "ulong")] [InlineData("ulong", "sbyte", "ulong.MaxValue", "ulong")] [InlineData("ulong", "short", "ulong.MaxValue", "ulong")] [InlineData("ulong", "int", "ulong.MaxValue", "ulong")] [InlineData("ulong", "byte", "ulong.MaxValue", "ulong")] [InlineData("ulong", "ushort", "ulong.MaxValue", "ulong")] [InlineData("nint", "char", "int.MaxValue", "nint")] [InlineData("nint", "sbyte", "int.MaxValue", "nint")] [InlineData("nint", "short", "int.MaxValue", "nint")] [InlineData("nint", "int", "int.MaxValue", "nint")] [InlineData("nint", "byte", "int.MaxValue", "nint")] [InlineData("nint", "ushort", "int.MaxValue", "nint")] [InlineData("nuint", "char", "uint.MaxValue", "nuint")] [InlineData("nuint", "sbyte", "uint.MaxValue", "nuint")] [InlineData("nuint", "short", "uint.MaxValue", "nuint")] [InlineData("nuint", "int", "uint.MaxValue", "nuint")] [InlineData("nuint", "byte", "uint.MaxValue", "nuint")] [InlineData("nuint", "ushort", "uint.MaxValue", "nuint")] [InlineData("nint", "char", "0", "nint")] [InlineData("nint", "sbyte", "0", "nint")] [InlineData("nint", "short", "0", "nint")] [InlineData("nint", "int", "0", "nint")] [InlineData("nint", "byte", "0", "nint")] [InlineData("nint", "ushort", "0", "nint")] public void BuiltIn_ConstantFolding_01(string left, string right, string leftValue, string result) { var source1 = @" class C { static void Main() { const " + left + @" x = (" + left + @")(" + leftValue + @"); const " + result + @" y = x >>> (" + right + @")1; var z1 = x; var z2 = z1 >>> (" + right + @")1; if (y == z2) System.Console.WriteLine(""Passed 1""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation1, expectedOutput: @" Passed 1 ").VerifyDiagnostics(); } [Theory] [InlineData("int.MinValue")] [InlineData("-1")] [InlineData("-100")] public void BuiltIn_ConstantFolding_02(string leftValue) { var source1 = @" #pragma warning disable CS0219 // The variable 'y' is assigned but its value is never used class C { static void Main() { const nint x = (nint)(" + leftValue + @"); const nint y = x >>> 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); compilation1.VerifyDiagnostics( // (9,24): error CS0133: The expression being assigned to 'y' must be constant // const nint y = x >>> 1; Diagnostic(ErrorCode.ERR_NotConstantExpression, "x >>> 1").WithArguments("y").WithLocation(9, 24) ); } [Theory] [InlineData("char", "char", "ushort.MaxValue")] [InlineData("char", "sbyte", "ushort.MaxValue")] [InlineData("char", "short", "ushort.MaxValue")] [InlineData("char", "int", "ushort.MaxValue")] [InlineData("char", "byte", "ushort.MaxValue")] [InlineData("char", "ushort", "ushort.MaxValue")] [InlineData("sbyte", "char", "sbyte.MinValue")] [InlineData("sbyte", "sbyte", "sbyte.MinValue")] [InlineData("sbyte", "short", "sbyte.MinValue")] [InlineData("sbyte", "int", "sbyte.MinValue")] [InlineData("sbyte", "byte", "sbyte.MinValue")] [InlineData("sbyte", "ushort", "sbyte.MinValue")] [InlineData("short", "char", "short.MinValue")] [InlineData("short", "sbyte", "short.MinValue")] [InlineData("short", "short", "short.MinValue")] [InlineData("short", "int", "short.MinValue")] [InlineData("short", "byte", "short.MinValue")] [InlineData("short", "ushort", "short.MinValue")] [InlineData("int", "char", "int.MinValue")] [InlineData("int", "sbyte", "int.MinValue")] [InlineData("int", "short", "int.MinValue")] [InlineData("int", "int", "int.MinValue")] [InlineData("int", "byte", "int.MinValue")] [InlineData("int", "ushort", "int.MinValue")] [InlineData("long", "char", "long.MinValue")] [InlineData("long", "sbyte", "long.MinValue")] [InlineData("long", "short", "long.MinValue")] [InlineData("long", "int", "long.MinValue")] [InlineData("long", "byte", "long.MinValue")] [InlineData("long", "ushort", "long.MinValue")] [InlineData("byte", "char", "byte.MaxValue")] [InlineData("byte", "sbyte", "byte.MaxValue")] [InlineData("byte", "short", "byte.MaxValue")] [InlineData("byte", "int", "byte.MaxValue")] [InlineData("byte", "byte", "byte.MaxValue")] [InlineData("byte", "ushort", "byte.MaxValue")] [InlineData("ushort", "char", "ushort.MaxValue")] [InlineData("ushort", "sbyte", "ushort.MaxValue")] [InlineData("ushort", "short", "ushort.MaxValue")] [InlineData("ushort", "int", "ushort.MaxValue")] [InlineData("ushort", "byte", "ushort.MaxValue")] [InlineData("ushort", "ushort", "ushort.MaxValue")] [InlineData("uint", "char", "uint.MaxValue")] [InlineData("uint", "sbyte", "uint.MaxValue")] [InlineData("uint", "short", "uint.MaxValue")] [InlineData("uint", "int", "uint.MaxValue")] [InlineData("uint", "byte", "uint.MaxValue")] [InlineData("uint", "ushort", "uint.MaxValue")] [InlineData("ulong", "char", "ulong.MaxValue")] [InlineData("ulong", "sbyte", "ulong.MaxValue")] [InlineData("ulong", "short", "ulong.MaxValue")] [InlineData("ulong", "int", "ulong.MaxValue")] [InlineData("ulong", "byte", "ulong.MaxValue")] [InlineData("ulong", "ushort", "ulong.MaxValue")] [InlineData("nint", "char", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "sbyte", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "short", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "int", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "byte", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "ushort", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nuint", "char", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "sbyte", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "short", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "int", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "byte", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "ushort", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] public void BuiltIn_CompoundAssignment_01(string left, string right, string leftValue) { var source1 = @" class C { static void Main() { var x = (" + left + @")" + leftValue + @"; var y = (" + right + @")1; var z1 = x; z1 >>>= y; if (z1 == (" + left + @")(x >>> y)) System.Console.WriteLine(""Passed 1""); z1 >>= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation1, expectedOutput: @" Passed 1 ").VerifyDiagnostics(); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftAssignmentExpression).First(); var shift = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.RightShiftAssignmentExpression).First(); Assert.Equal("z1 >>>= y", unsignedShift.ToString()); Assert.Equal("z1 >>= y", shift.ToString()); var unsignedShiftSymbol = (IMethodSymbol)model.GetSymbolInfo(unsignedShift).Symbol; var shiftSymbol = (IMethodSymbol)model.GetSymbolInfo(shift).Symbol; Assert.Equal("op_UnsignedRightShift", unsignedShiftSymbol.Name); Assert.Equal("op_RightShift", shiftSymbol.Name); Assert.Same(shiftSymbol.ReturnType, unsignedShiftSymbol.ReturnType); Assert.Same(shiftSymbol.Parameters[0].Type, unsignedShiftSymbol.Parameters[0].Type); Assert.Same(shiftSymbol.Parameters[1].Type, unsignedShiftSymbol.Parameters[1].Type); Assert.Same(shiftSymbol.ContainingSymbol, unsignedShiftSymbol.ContainingSymbol); } [Theory] [InlineData("object", "object")] [InlineData("object", "string")] [InlineData("object", "bool")] [InlineData("object", "char")] [InlineData("object", "sbyte")] [InlineData("object", "short")] [InlineData("object", "int")] [InlineData("object", "long")] [InlineData("object", "byte")] [InlineData("object", "ushort")] [InlineData("object", "uint")] [InlineData("object", "ulong")] [InlineData("object", "nint")] [InlineData("object", "nuint")] [InlineData("object", "float")] [InlineData("object", "double")] [InlineData("object", "decimal")] [InlineData("string", "object")] [InlineData("string", "string")] [InlineData("string", "bool")] [InlineData("string", "char")] [InlineData("string", "sbyte")] [InlineData("string", "short")] [InlineData("string", "int")] [InlineData("string", "long")] [InlineData("string", "byte")] [InlineData("string", "ushort")] [InlineData("string", "uint")] [InlineData("string", "ulong")] [InlineData("string", "nint")] [InlineData("string", "nuint")] [InlineData("string", "float")] [InlineData("string", "double")] [InlineData("string", "decimal")] [InlineData("bool", "object")] [InlineData("bool", "string")] [InlineData("bool", "bool")] [InlineData("bool", "char")] [InlineData("bool", "sbyte")] [InlineData("bool", "short")] [InlineData("bool", "int")] [InlineData("bool", "long")] [InlineData("bool", "byte")] [InlineData("bool", "ushort")] [InlineData("bool", "uint")] [InlineData("bool", "ulong")] [InlineData("bool", "nint")] [InlineData("bool", "nuint")] [InlineData("bool", "float")] [InlineData("bool", "double")] [InlineData("bool", "decimal")] [InlineData("char", "object")] [InlineData("char", "string")] [InlineData("char", "bool")] [InlineData("char", "long")] [InlineData("char", "uint")] [InlineData("char", "ulong")] [InlineData("char", "nint")] [InlineData("char", "nuint")] [InlineData("char", "float")] [InlineData("char", "double")] [InlineData("char", "decimal")] [InlineData("sbyte", "object")] [InlineData("sbyte", "string")] [InlineData("sbyte", "bool")] [InlineData("sbyte", "long")] [InlineData("sbyte", "uint")] [InlineData("sbyte", "ulong")] [InlineData("sbyte", "nint")] [InlineData("sbyte", "nuint")] [InlineData("sbyte", "float")] [InlineData("sbyte", "double")] [InlineData("sbyte", "decimal")] [InlineData("short", "object")] [InlineData("short", "string")] [InlineData("short", "bool")] [InlineData("short", "long")] [InlineData("short", "uint")] [InlineData("short", "ulong")] [InlineData("short", "nint")] [InlineData("short", "nuint")] [InlineData("short", "float")] [InlineData("short", "double")] [InlineData("short", "decimal")] [InlineData("int", "object")] [InlineData("int", "string")] [InlineData("int", "bool")] [InlineData("int", "long")] [InlineData("int", "uint")] [InlineData("int", "ulong")] [InlineData("int", "nint")] [InlineData("int", "nuint")] [InlineData("int", "float")] [InlineData("int", "double")] [InlineData("int", "decimal")] [InlineData("long", "object")] [InlineData("long", "string")] [InlineData("long", "bool")] [InlineData("long", "long")] [InlineData("long", "uint")] [InlineData("long", "ulong")] [InlineData("long", "nint")] [InlineData("long", "nuint")] [InlineData("long", "float")] [InlineData("long", "double")] [InlineData("long", "decimal")] [InlineData("byte", "object")] [InlineData("byte", "string")] [InlineData("byte", "bool")] [InlineData("byte", "long")] [InlineData("byte", "uint")] [InlineData("byte", "ulong")] [InlineData("byte", "nint")] [InlineData("byte", "nuint")] [InlineData("byte", "float")] [InlineData("byte", "double")] [InlineData("byte", "decimal")] [InlineData("ushort", "object")] [InlineData("ushort", "string")] [InlineData("ushort", "bool")] [InlineData("ushort", "long")] [InlineData("ushort", "uint")] [InlineData("ushort", "ulong")] [InlineData("ushort", "nint")] [InlineData("ushort", "nuint")] [InlineData("ushort", "float")] [InlineData("ushort", "double")] [InlineData("ushort", "decimal")] [InlineData("uint", "object")] [InlineData("uint", "string")] [InlineData("uint", "bool")] [InlineData("uint", "long")] [InlineData("uint", "uint")] [InlineData("uint", "ulong")] [InlineData("uint", "nint")] [InlineData("uint", "nuint")] [InlineData("uint", "float")] [InlineData("uint", "double")] [InlineData("uint", "decimal")] [InlineData("ulong", "object")] [InlineData("ulong", "string")] [InlineData("ulong", "bool")] [InlineData("ulong", "long")] [InlineData("ulong", "uint")] [InlineData("ulong", "ulong")] [InlineData("ulong", "nint")] [InlineData("ulong", "nuint")] [InlineData("ulong", "float")] [InlineData("ulong", "double")] [InlineData("ulong", "decimal")] [InlineData("nint", "object")] [InlineData("nint", "string")] [InlineData("nint", "bool")] [InlineData("nint", "long")] [InlineData("nint", "uint")] [InlineData("nint", "ulong")] [InlineData("nint", "nint")] [InlineData("nint", "nuint")] [InlineData("nint", "float")] [InlineData("nint", "double")] [InlineData("nint", "decimal")] [InlineData("nuint", "object")] [InlineData("nuint", "string")] [InlineData("nuint", "bool")] [InlineData("nuint", "long")] [InlineData("nuint", "uint")] [InlineData("nuint", "ulong")] [InlineData("nuint", "nint")] [InlineData("nuint", "nuint")] [InlineData("nuint", "float")] [InlineData("nuint", "double")] [InlineData("nuint", "decimal")] [InlineData("float", "object")] [InlineData("float", "string")] [InlineData("float", "bool")] [InlineData("float", "char")] [InlineData("float", "sbyte")] [InlineData("float", "short")] [InlineData("float", "int")] [InlineData("float", "long")] [InlineData("float", "byte")] [InlineData("float", "ushort")] [InlineData("float", "uint")] [InlineData("float", "ulong")] [InlineData("float", "nint")] [InlineData("float", "nuint")] [InlineData("float", "float")] [InlineData("float", "double")] [InlineData("float", "decimal")] [InlineData("double", "object")] [InlineData("double", "string")] [InlineData("double", "bool")] [InlineData("double", "char")] [InlineData("double", "sbyte")] [InlineData("double", "short")] [InlineData("double", "int")] [InlineData("double", "long")] [InlineData("double", "byte")] [InlineData("double", "ushort")] [InlineData("double", "uint")] [InlineData("double", "ulong")] [InlineData("double", "nint")] [InlineData("double", "nuint")] [InlineData("double", "float")] [InlineData("double", "double")] [InlineData("double", "decimal")] [InlineData("decimal", "object")] [InlineData("decimal", "string")] [InlineData("decimal", "bool")] [InlineData("decimal", "char")] [InlineData("decimal", "sbyte")] [InlineData("decimal", "short")] [InlineData("decimal", "int")] [InlineData("decimal", "long")] [InlineData("decimal", "byte")] [InlineData("decimal", "ushort")] [InlineData("decimal", "uint")] [InlineData("decimal", "ulong")] [InlineData("decimal", "nint")] [InlineData("decimal", "nuint")] [InlineData("decimal", "float")] [InlineData("decimal", "double")] [InlineData("decimal", "decimal")] public void BuiltIn_CompoundAssignment_02(string left, string right) { var source1 = @" class C { static void Main() { " + left + @" x = default; " + right + @" y = default; x >>= y; x >>>= y; } } "; var expected = new[] { // (8,9): error CS0019: Operator '>>=' cannot be applied to operands of type 'double' and 'char' // x >>= y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>= y").WithArguments(">>=", left, right).WithLocation(8, 9), // (9,9): error CS0019: Operator '>>>=' cannot be applied to operands of type 'double' and 'char' // x >>>= y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>>= y").WithArguments(">>>=", left, right).WithLocation(9, 9) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyEmitDiagnostics(expected); } [Fact] public void BuiltIn_CompoundAssignment_CollectionInitializerElement() { var source1 = @" class C { static void Main() { var x = int.MinValue; var y = new System.Collections.Generic.List<int>() { x >>= 1, x >>>= 1 }; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (8,13): error CS0747: Invalid initializer member declarator // x >>= 1, Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "x >>= 1").WithLocation(8, 13), // (9,13): error CS0747: Invalid initializer member declarator // x >>>= 1 Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "x >>>= 1").WithLocation(9, 13) ); } [Fact] public void BuiltIn_ExpressionTree_01() { var source1 = @" class C { static void Main() { System.Linq.Expressions.Expression<System.Func<int, int, int>> e = (x, y) => x >>> y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (6,86): error CS7053: An expression tree may not contain '>>>' // System.Linq.Expressions.Expression<System.Func<int, int, int>> e = (x, y) => x >>> y; Diagnostic(ErrorCode.ERR_FeatureNotValidInExpressionTree, "x >>> y").WithArguments(">>>").WithLocation(6, 86) ); } [Fact] public void BuiltIn_CompoundAssignment_ExpressionTree_01() { var source1 = @" class C { static void Main() { System.Linq.Expressions.Expression<System.Func<int, int, int>> e = (x, y) => x >>>= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (6,86): error CS0832: An expression tree may not contain an assignment operator // System.Linq.Expressions.Expression<System.Func<int, int, int>> e = (x, y) => x >>>= y; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "x >>>= y").WithLocation(6, 86) ); } [Fact] public void BuiltIn_Dynamic_01() { var source1 = @" class C { static void Main(dynamic x, int y) { _ = x >>> y; _ = y >>> x; _ = x >>> x; } } "; var expected = new[] { // (6,13): error CS0019: Operator '>>>' cannot be applied to operands of type 'dynamic' and 'int' // _ = x >>> y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>> y").WithArguments(">>>", "dynamic", "int").WithLocation(6, 13), // (7,13): error CS0019: Operator '>>>' cannot be applied to operands of type 'int' and 'dynamic' // _ = y >>> x; Diagnostic(ErrorCode.ERR_BadBinaryOps, "y >>> x").WithArguments(">>>", "int", "dynamic").WithLocation(7, 13), // (8,13): error CS0019: Operator '>>>' cannot be applied to operands of type 'dynamic' and 'dynamic' // _ = x >>> x; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>> x").WithArguments(">>>", "dynamic", "dynamic").WithLocation(8, 13) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyEmitDiagnostics(expected); } [Fact] public void BuiltIn_CompoundAssignment_Dynamic_01() { var source1 = @" class C { static void Main(dynamic x, int y) { x >>>= y; y >>>= x; x >>>= x; } } "; var expected = new[] { // (6,9): error CS0019: Operator '>>>=' cannot be applied to operands of type 'dynamic' and 'int' // x >>>= y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>>= y").WithArguments(">>>=", "dynamic", "int").WithLocation(6, 9), // (7,9): error CS0019: Operator '>>>=' cannot be applied to operands of type 'int' and 'dynamic' // y >>>= x; Diagnostic(ErrorCode.ERR_BadBinaryOps, "y >>>= x").WithArguments(">>>=", "int", "dynamic").WithLocation(7, 9), // (8,9): error CS0019: Operator '>>>=' cannot be applied to operands of type 'dynamic' and 'dynamic' // x >>>= x; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>>= x").WithArguments(">>>=", "dynamic", "dynamic").WithLocation(8, 9) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyEmitDiagnostics(expected); } [Theory] [InlineData("char", "char", "ushort.MaxValue", "int")] [InlineData("char", "sbyte", "ushort.MaxValue", "int")] [InlineData("char", "short", "ushort.MaxValue", "int")] [InlineData("char", "int", "ushort.MaxValue", "int")] [InlineData("char", "byte", "ushort.MaxValue", "int")] [InlineData("char", "ushort", "ushort.MaxValue", "int")] [InlineData("sbyte", "char", "sbyte.MinValue", "int")] [InlineData("sbyte", "sbyte", "sbyte.MinValue", "int")] [InlineData("sbyte", "short", "sbyte.MinValue", "int")] [InlineData("sbyte", "int", "sbyte.MinValue", "int")] [InlineData("sbyte", "byte", "sbyte.MinValue", "int")] [InlineData("sbyte", "ushort", "sbyte.MinValue", "int")] [InlineData("short", "char", "short.MinValue", "int")] [InlineData("short", "sbyte", "short.MinValue", "int")] [InlineData("short", "short", "short.MinValue", "int")] [InlineData("short", "int", "short.MinValue", "int")] [InlineData("short", "byte", "short.MinValue", "int")] [InlineData("short", "ushort", "short.MinValue", "int")] [InlineData("int", "char", "int.MinValue", "int")] [InlineData("int", "sbyte", "int.MinValue", "int")] [InlineData("int", "short", "int.MinValue", "int")] [InlineData("int", "int", "int.MinValue", "int")] [InlineData("int", "byte", "int.MinValue", "int")] [InlineData("int", "ushort", "int.MinValue", "int")] [InlineData("long", "char", "long.MinValue", "long")] [InlineData("long", "sbyte", "long.MinValue", "long")] [InlineData("long", "short", "long.MinValue", "long")] [InlineData("long", "int", "long.MinValue", "long")] [InlineData("long", "byte", "long.MinValue", "long")] [InlineData("long", "ushort", "long.MinValue", "long")] [InlineData("byte", "char", "byte.MaxValue", "int")] [InlineData("byte", "sbyte", "byte.MaxValue", "int")] [InlineData("byte", "short", "byte.MaxValue", "int")] [InlineData("byte", "int", "byte.MaxValue", "int")] [InlineData("byte", "byte", "byte.MaxValue", "int")] [InlineData("byte", "ushort", "byte.MaxValue", "int")] [InlineData("ushort", "char", "ushort.MaxValue", "int")] [InlineData("ushort", "sbyte", "ushort.MaxValue", "int")] [InlineData("ushort", "short", "ushort.MaxValue", "int")] [InlineData("ushort", "int", "ushort.MaxValue", "int")] [InlineData("ushort", "byte", "ushort.MaxValue", "int")] [InlineData("ushort", "ushort", "ushort.MaxValue", "int")] [InlineData("uint", "char", "uint.MaxValue", "uint")] [InlineData("uint", "sbyte", "uint.MaxValue", "uint")] [InlineData("uint", "short", "uint.MaxValue", "uint")] [InlineData("uint", "int", "uint.MaxValue", "uint")] [InlineData("uint", "byte", "uint.MaxValue", "uint")] [InlineData("uint", "ushort", "uint.MaxValue", "uint")] [InlineData("ulong", "char", "ulong.MaxValue", "ulong")] [InlineData("ulong", "sbyte", "ulong.MaxValue", "ulong")] [InlineData("ulong", "short", "ulong.MaxValue", "ulong")] [InlineData("ulong", "int", "ulong.MaxValue", "ulong")] [InlineData("ulong", "byte", "ulong.MaxValue", "ulong")] [InlineData("ulong", "ushort", "ulong.MaxValue", "ulong")] [InlineData("nint", "char", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint")] [InlineData("nint", "sbyte", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint")] [InlineData("nint", "short", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint")] [InlineData("nint", "int", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint")] [InlineData("nint", "byte", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint")] [InlineData("nint", "ushort", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)", "nint")] [InlineData("nuint", "char", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint")] [InlineData("nuint", "sbyte", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint")] [InlineData("nuint", "short", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint")] [InlineData("nuint", "int", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint")] [InlineData("nuint", "byte", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint")] [InlineData("nuint", "ushort", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)", "nuint")] public void BuiltIn_Lifted_01(string left, string right, string leftValue, string result) { var nullableLeft = left + "?"; var nullableRight = right + "?"; var nullableResult = result + "?"; var source1 = @" class C { static void Main() { var x = (" + nullableLeft + @")" + leftValue + @"; var y = (" + nullableRight + @")1; var z1 = x >>> y; var z2 = x >> y; if (z1 == (x.Value >>> y.Value)) System.Console.WriteLine(""Passed 1""); if (GetType(z1) == GetType(z2) && GetType(z1) == typeof(" + nullableResult + @")) System.Console.WriteLine(""Passed 2""); if (Test1(x, null) == null) System.Console.WriteLine(""Passed 3""); if (Test1(null, y) == null) System.Console.WriteLine(""Passed 4""); if (Test1(null, null) == null) System.Console.WriteLine(""Passed 5""); } static " + nullableResult + @" Test1(" + nullableLeft + @" x, " + nullableRight + @" y) => x >>> y; static " + nullableResult + @" Test2(" + nullableLeft + @" x, " + nullableRight + @" y) => x >> y; static System.Type GetType<T>(T x) => typeof(T); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(compilation1, expectedOutput: @" Passed 1 Passed 2 Passed 3 Passed 4 Passed 5 ").VerifyDiagnostics(); string actualIL = verifier.VisualizeIL("C.Test2"); verifier.VerifyIL("C.Test1", actualIL.Replace("shr.un", "shr").Replace("shr", "shr.un")); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftExpression).First(); var shift = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.RightShiftExpression).First(); Assert.Equal("x >>> y", unsignedShift.ToString()); Assert.Equal("x >> y", shift.ToString()); var unsignedShiftSymbol = (IMethodSymbol)model.GetSymbolInfo(unsignedShift).Symbol; var shiftSymbol = (IMethodSymbol)model.GetSymbolInfo(shift).Symbol; Assert.Equal("op_UnsignedRightShift", unsignedShiftSymbol.Name); Assert.Equal("op_RightShift", shiftSymbol.Name); Assert.Same(shiftSymbol.ReturnType, unsignedShiftSymbol.ReturnType); Assert.Same(shiftSymbol.Parameters[0].Type, unsignedShiftSymbol.Parameters[0].Type); Assert.Same(shiftSymbol.Parameters[1].Type, unsignedShiftSymbol.Parameters[1].Type); Assert.Same(shiftSymbol.ContainingSymbol, unsignedShiftSymbol.ContainingSymbol); } [Theory] [InlineData("object", "object")] [InlineData("object", "string")] [InlineData("object", "bool")] [InlineData("object", "char")] [InlineData("object", "sbyte")] [InlineData("object", "short")] [InlineData("object", "int")] [InlineData("object", "long")] [InlineData("object", "byte")] [InlineData("object", "ushort")] [InlineData("object", "uint")] [InlineData("object", "ulong")] [InlineData("object", "nint")] [InlineData("object", "nuint")] [InlineData("object", "float")] [InlineData("object", "double")] [InlineData("object", "decimal")] [InlineData("string", "object")] [InlineData("string", "string")] [InlineData("string", "bool")] [InlineData("string", "char")] [InlineData("string", "sbyte")] [InlineData("string", "short")] [InlineData("string", "int")] [InlineData("string", "long")] [InlineData("string", "byte")] [InlineData("string", "ushort")] [InlineData("string", "uint")] [InlineData("string", "ulong")] [InlineData("string", "nint")] [InlineData("string", "nuint")] [InlineData("string", "float")] [InlineData("string", "double")] [InlineData("string", "decimal")] [InlineData("bool", "object")] [InlineData("bool", "string")] [InlineData("bool", "bool")] [InlineData("bool", "char")] [InlineData("bool", "sbyte")] [InlineData("bool", "short")] [InlineData("bool", "int")] [InlineData("bool", "long")] [InlineData("bool", "byte")] [InlineData("bool", "ushort")] [InlineData("bool", "uint")] [InlineData("bool", "ulong")] [InlineData("bool", "nint")] [InlineData("bool", "nuint")] [InlineData("bool", "float")] [InlineData("bool", "double")] [InlineData("bool", "decimal")] [InlineData("char", "object")] [InlineData("char", "string")] [InlineData("char", "bool")] [InlineData("char", "long")] [InlineData("char", "uint")] [InlineData("char", "ulong")] [InlineData("char", "nint")] [InlineData("char", "nuint")] [InlineData("char", "float")] [InlineData("char", "double")] [InlineData("char", "decimal")] [InlineData("sbyte", "object")] [InlineData("sbyte", "string")] [InlineData("sbyte", "bool")] [InlineData("sbyte", "long")] [InlineData("sbyte", "uint")] [InlineData("sbyte", "ulong")] [InlineData("sbyte", "nint")] [InlineData("sbyte", "nuint")] [InlineData("sbyte", "float")] [InlineData("sbyte", "double")] [InlineData("sbyte", "decimal")] [InlineData("short", "object")] [InlineData("short", "string")] [InlineData("short", "bool")] [InlineData("short", "long")] [InlineData("short", "uint")] [InlineData("short", "ulong")] [InlineData("short", "nint")] [InlineData("short", "nuint")] [InlineData("short", "float")] [InlineData("short", "double")] [InlineData("short", "decimal")] [InlineData("int", "object")] [InlineData("int", "string")] [InlineData("int", "bool")] [InlineData("int", "long")] [InlineData("int", "uint")] [InlineData("int", "ulong")] [InlineData("int", "nint")] [InlineData("int", "nuint")] [InlineData("int", "float")] [InlineData("int", "double")] [InlineData("int", "decimal")] [InlineData("long", "object")] [InlineData("long", "string")] [InlineData("long", "bool")] [InlineData("long", "long")] [InlineData("long", "uint")] [InlineData("long", "ulong")] [InlineData("long", "nint")] [InlineData("long", "nuint")] [InlineData("long", "float")] [InlineData("long", "double")] [InlineData("long", "decimal")] [InlineData("byte", "object")] [InlineData("byte", "string")] [InlineData("byte", "bool")] [InlineData("byte", "long")] [InlineData("byte", "uint")] [InlineData("byte", "ulong")] [InlineData("byte", "nint")] [InlineData("byte", "nuint")] [InlineData("byte", "float")] [InlineData("byte", "double")] [InlineData("byte", "decimal")] [InlineData("ushort", "object")] [InlineData("ushort", "string")] [InlineData("ushort", "bool")] [InlineData("ushort", "long")] [InlineData("ushort", "uint")] [InlineData("ushort", "ulong")] [InlineData("ushort", "nint")] [InlineData("ushort", "nuint")] [InlineData("ushort", "float")] [InlineData("ushort", "double")] [InlineData("ushort", "decimal")] [InlineData("uint", "object")] [InlineData("uint", "string")] [InlineData("uint", "bool")] [InlineData("uint", "long")] [InlineData("uint", "uint")] [InlineData("uint", "ulong")] [InlineData("uint", "nint")] [InlineData("uint", "nuint")] [InlineData("uint", "float")] [InlineData("uint", "double")] [InlineData("uint", "decimal")] [InlineData("ulong", "object")] [InlineData("ulong", "string")] [InlineData("ulong", "bool")] [InlineData("ulong", "long")] [InlineData("ulong", "uint")] [InlineData("ulong", "ulong")] [InlineData("ulong", "nint")] [InlineData("ulong", "nuint")] [InlineData("ulong", "float")] [InlineData("ulong", "double")] [InlineData("ulong", "decimal")] [InlineData("nint", "object")] [InlineData("nint", "string")] [InlineData("nint", "bool")] [InlineData("nint", "long")] [InlineData("nint", "uint")] [InlineData("nint", "ulong")] [InlineData("nint", "nint")] [InlineData("nint", "nuint")] [InlineData("nint", "float")] [InlineData("nint", "double")] [InlineData("nint", "decimal")] [InlineData("nuint", "object")] [InlineData("nuint", "string")] [InlineData("nuint", "bool")] [InlineData("nuint", "long")] [InlineData("nuint", "uint")] [InlineData("nuint", "ulong")] [InlineData("nuint", "nint")] [InlineData("nuint", "nuint")] [InlineData("nuint", "float")] [InlineData("nuint", "double")] [InlineData("nuint", "decimal")] [InlineData("float", "object")] [InlineData("float", "string")] [InlineData("float", "bool")] [InlineData("float", "char")] [InlineData("float", "sbyte")] [InlineData("float", "short")] [InlineData("float", "int")] [InlineData("float", "long")] [InlineData("float", "byte")] [InlineData("float", "ushort")] [InlineData("float", "uint")] [InlineData("float", "ulong")] [InlineData("float", "nint")] [InlineData("float", "nuint")] [InlineData("float", "float")] [InlineData("float", "double")] [InlineData("float", "decimal")] [InlineData("double", "object")] [InlineData("double", "string")] [InlineData("double", "bool")] [InlineData("double", "char")] [InlineData("double", "sbyte")] [InlineData("double", "short")] [InlineData("double", "int")] [InlineData("double", "long")] [InlineData("double", "byte")] [InlineData("double", "ushort")] [InlineData("double", "uint")] [InlineData("double", "ulong")] [InlineData("double", "nint")] [InlineData("double", "nuint")] [InlineData("double", "float")] [InlineData("double", "double")] [InlineData("double", "decimal")] [InlineData("decimal", "object")] [InlineData("decimal", "string")] [InlineData("decimal", "bool")] [InlineData("decimal", "char")] [InlineData("decimal", "sbyte")] [InlineData("decimal", "short")] [InlineData("decimal", "int")] [InlineData("decimal", "long")] [InlineData("decimal", "byte")] [InlineData("decimal", "ushort")] [InlineData("decimal", "uint")] [InlineData("decimal", "ulong")] [InlineData("decimal", "nint")] [InlineData("decimal", "nuint")] [InlineData("decimal", "float")] [InlineData("decimal", "double")] [InlineData("decimal", "decimal")] public void BuiltIn_Lifted_02(string left, string right) { var nullableLeft = NullableIfPossible(left); var nullableRight = NullableIfPossible(right); var source1 = @" class C { static void Main() { " + nullableLeft + @" x = default; " + nullableRight + @" y = default; var z1 = x >> y; var z2 = x >>> y; } } "; var expected = new[] { // (8,18): error CS0019: Operator '>>' cannot be applied to operands of type 'object' and 'object' // var z1 = x >> y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >> y").WithArguments(">>", nullableLeft, nullableRight).WithLocation(8, 18), // (9,18): error CS0019: Operator '>>>' cannot be applied to operands of type 'object' and 'object' // var z2 = x >>> y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>> y").WithArguments(">>>", nullableLeft, nullableRight).WithLocation(9, 18) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyEmitDiagnostics(expected); } private static string NullableIfPossible(string type) { switch (type) { case "object": case "string": return type; default: return type + "?"; } } [Theory] [InlineData("char", "char", "ushort.MaxValue")] [InlineData("char", "sbyte", "ushort.MaxValue")] [InlineData("char", "short", "ushort.MaxValue")] [InlineData("char", "int", "ushort.MaxValue")] [InlineData("char", "byte", "ushort.MaxValue")] [InlineData("char", "ushort", "ushort.MaxValue")] [InlineData("sbyte", "char", "sbyte.MinValue")] [InlineData("sbyte", "sbyte", "sbyte.MinValue")] [InlineData("sbyte", "short", "sbyte.MinValue")] [InlineData("sbyte", "int", "sbyte.MinValue")] [InlineData("sbyte", "byte", "sbyte.MinValue")] [InlineData("sbyte", "ushort", "sbyte.MinValue")] [InlineData("short", "char", "short.MinValue")] [InlineData("short", "sbyte", "short.MinValue")] [InlineData("short", "short", "short.MinValue")] [InlineData("short", "int", "short.MinValue")] [InlineData("short", "byte", "short.MinValue")] [InlineData("short", "ushort", "short.MinValue")] [InlineData("int", "char", "int.MinValue")] [InlineData("int", "sbyte", "int.MinValue")] [InlineData("int", "short", "int.MinValue")] [InlineData("int", "int", "int.MinValue")] [InlineData("int", "byte", "int.MinValue")] [InlineData("int", "ushort", "int.MinValue")] [InlineData("long", "char", "long.MinValue")] [InlineData("long", "sbyte", "long.MinValue")] [InlineData("long", "short", "long.MinValue")] [InlineData("long", "int", "long.MinValue")] [InlineData("long", "byte", "long.MinValue")] [InlineData("long", "ushort", "long.MinValue")] [InlineData("byte", "char", "byte.MaxValue")] [InlineData("byte", "sbyte", "byte.MaxValue")] [InlineData("byte", "short", "byte.MaxValue")] [InlineData("byte", "int", "byte.MaxValue")] [InlineData("byte", "byte", "byte.MaxValue")] [InlineData("byte", "ushort", "byte.MaxValue")] [InlineData("ushort", "char", "ushort.MaxValue")] [InlineData("ushort", "sbyte", "ushort.MaxValue")] [InlineData("ushort", "short", "ushort.MaxValue")] [InlineData("ushort", "int", "ushort.MaxValue")] [InlineData("ushort", "byte", "ushort.MaxValue")] [InlineData("ushort", "ushort", "ushort.MaxValue")] [InlineData("uint", "char", "uint.MaxValue")] [InlineData("uint", "sbyte", "uint.MaxValue")] [InlineData("uint", "short", "uint.MaxValue")] [InlineData("uint", "int", "uint.MaxValue")] [InlineData("uint", "byte", "uint.MaxValue")] [InlineData("uint", "ushort", "uint.MaxValue")] [InlineData("ulong", "char", "ulong.MaxValue")] [InlineData("ulong", "sbyte", "ulong.MaxValue")] [InlineData("ulong", "short", "ulong.MaxValue")] [InlineData("ulong", "int", "ulong.MaxValue")] [InlineData("ulong", "byte", "ulong.MaxValue")] [InlineData("ulong", "ushort", "ulong.MaxValue")] [InlineData("nint", "char", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "sbyte", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "short", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "int", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "byte", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nint", "ushort", "(System.IntPtr.Size == 4 ? int.MinValue : long.MinValue)")] [InlineData("nuint", "char", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "sbyte", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "short", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "int", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "byte", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] [InlineData("nuint", "ushort", "(System.IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue)")] public void BuiltIn_Lifted_CompoundAssignment_01(string left, string right, string leftValue) { var nullableLeft = left + "?"; var nullableRight = right + "?"; var source1 = @" class C { static void Main() { var x = (" + nullableLeft + @")" + leftValue + @"; var y = (" + nullableRight + @")1; var z1 = x; z1 >>>= y; if (z1 == (" + left + @")(x.Value >>> y.Value)) System.Console.WriteLine(""Passed 1""); z1 >>= y; z1 = null; z1 >>>= y; if (z1 == null) System.Console.WriteLine(""Passed 2""); y = null; z1 >>>= y; if (z1 == null) System.Console.WriteLine(""Passed 3""); z1 = x; z1 >>>= y; if (z1 == null) System.Console.WriteLine(""Passed 4""); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation1, expectedOutput: @" Passed 1 Passed 2 Passed 3 Passed 4 ").VerifyDiagnostics(); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftAssignmentExpression).First(); var shift = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.RightShiftAssignmentExpression).First(); Assert.Equal("z1 >>>= y", unsignedShift.ToString()); Assert.Equal("z1 >>= y", shift.ToString()); var unsignedShiftSymbol = (IMethodSymbol)model.GetSymbolInfo(unsignedShift).Symbol; var shiftSymbol = (IMethodSymbol)model.GetSymbolInfo(shift).Symbol; Assert.Equal("op_UnsignedRightShift", unsignedShiftSymbol.Name); Assert.Equal("op_RightShift", shiftSymbol.Name); Assert.Same(shiftSymbol.ReturnType, unsignedShiftSymbol.ReturnType); Assert.Same(shiftSymbol.Parameters[0].Type, unsignedShiftSymbol.Parameters[0].Type); Assert.Same(shiftSymbol.Parameters[1].Type, unsignedShiftSymbol.Parameters[1].Type); Assert.Same(shiftSymbol.ContainingSymbol, unsignedShiftSymbol.ContainingSymbol); } [Theory] [InlineData("object", "object")] [InlineData("object", "string")] [InlineData("object", "bool")] [InlineData("object", "char")] [InlineData("object", "sbyte")] [InlineData("object", "short")] [InlineData("object", "int")] [InlineData("object", "long")] [InlineData("object", "byte")] [InlineData("object", "ushort")] [InlineData("object", "uint")] [InlineData("object", "ulong")] [InlineData("object", "nint")] [InlineData("object", "nuint")] [InlineData("object", "float")] [InlineData("object", "double")] [InlineData("object", "decimal")] [InlineData("string", "object")] [InlineData("string", "string")] [InlineData("string", "bool")] [InlineData("string", "char")] [InlineData("string", "sbyte")] [InlineData("string", "short")] [InlineData("string", "int")] [InlineData("string", "long")] [InlineData("string", "byte")] [InlineData("string", "ushort")] [InlineData("string", "uint")] [InlineData("string", "ulong")] [InlineData("string", "nint")] [InlineData("string", "nuint")] [InlineData("string", "float")] [InlineData("string", "double")] [InlineData("string", "decimal")] [InlineData("bool", "object")] [InlineData("bool", "string")] [InlineData("bool", "bool")] [InlineData("bool", "char")] [InlineData("bool", "sbyte")] [InlineData("bool", "short")] [InlineData("bool", "int")] [InlineData("bool", "long")] [InlineData("bool", "byte")] [InlineData("bool", "ushort")] [InlineData("bool", "uint")] [InlineData("bool", "ulong")] [InlineData("bool", "nint")] [InlineData("bool", "nuint")] [InlineData("bool", "float")] [InlineData("bool", "double")] [InlineData("bool", "decimal")] [InlineData("char", "object")] [InlineData("char", "string")] [InlineData("char", "bool")] [InlineData("char", "long")] [InlineData("char", "uint")] [InlineData("char", "ulong")] [InlineData("char", "nint")] [InlineData("char", "nuint")] [InlineData("char", "float")] [InlineData("char", "double")] [InlineData("char", "decimal")] [InlineData("sbyte", "object")] [InlineData("sbyte", "string")] [InlineData("sbyte", "bool")] [InlineData("sbyte", "long")] [InlineData("sbyte", "uint")] [InlineData("sbyte", "ulong")] [InlineData("sbyte", "nint")] [InlineData("sbyte", "nuint")] [InlineData("sbyte", "float")] [InlineData("sbyte", "double")] [InlineData("sbyte", "decimal")] [InlineData("short", "object")] [InlineData("short", "string")] [InlineData("short", "bool")] [InlineData("short", "long")] [InlineData("short", "uint")] [InlineData("short", "ulong")] [InlineData("short", "nint")] [InlineData("short", "nuint")] [InlineData("short", "float")] [InlineData("short", "double")] [InlineData("short", "decimal")] [InlineData("int", "object")] [InlineData("int", "string")] [InlineData("int", "bool")] [InlineData("int", "long")] [InlineData("int", "uint")] [InlineData("int", "ulong")] [InlineData("int", "nint")] [InlineData("int", "nuint")] [InlineData("int", "float")] [InlineData("int", "double")] [InlineData("int", "decimal")] [InlineData("long", "object")] [InlineData("long", "string")] [InlineData("long", "bool")] [InlineData("long", "long")] [InlineData("long", "uint")] [InlineData("long", "ulong")] [InlineData("long", "nint")] [InlineData("long", "nuint")] [InlineData("long", "float")] [InlineData("long", "double")] [InlineData("long", "decimal")] [InlineData("byte", "object")] [InlineData("byte", "string")] [InlineData("byte", "bool")] [InlineData("byte", "long")] [InlineData("byte", "uint")] [InlineData("byte", "ulong")] [InlineData("byte", "nint")] [InlineData("byte", "nuint")] [InlineData("byte", "float")] [InlineData("byte", "double")] [InlineData("byte", "decimal")] [InlineData("ushort", "object")] [InlineData("ushort", "string")] [InlineData("ushort", "bool")] [InlineData("ushort", "long")] [InlineData("ushort", "uint")] [InlineData("ushort", "ulong")] [InlineData("ushort", "nint")] [InlineData("ushort", "nuint")] [InlineData("ushort", "float")] [InlineData("ushort", "double")] [InlineData("ushort", "decimal")] [InlineData("uint", "object")] [InlineData("uint", "string")] [InlineData("uint", "bool")] [InlineData("uint", "long")] [InlineData("uint", "uint")] [InlineData("uint", "ulong")] [InlineData("uint", "nint")] [InlineData("uint", "nuint")] [InlineData("uint", "float")] [InlineData("uint", "double")] [InlineData("uint", "decimal")] [InlineData("ulong", "object")] [InlineData("ulong", "string")] [InlineData("ulong", "bool")] [InlineData("ulong", "long")] [InlineData("ulong", "uint")] [InlineData("ulong", "ulong")] [InlineData("ulong", "nint")] [InlineData("ulong", "nuint")] [InlineData("ulong", "float")] [InlineData("ulong", "double")] [InlineData("ulong", "decimal")] [InlineData("nint", "object")] [InlineData("nint", "string")] [InlineData("nint", "bool")] [InlineData("nint", "long")] [InlineData("nint", "uint")] [InlineData("nint", "ulong")] [InlineData("nint", "nint")] [InlineData("nint", "nuint")] [InlineData("nint", "float")] [InlineData("nint", "double")] [InlineData("nint", "decimal")] [InlineData("nuint", "object")] [InlineData("nuint", "string")] [InlineData("nuint", "bool")] [InlineData("nuint", "long")] [InlineData("nuint", "uint")] [InlineData("nuint", "ulong")] [InlineData("nuint", "nint")] [InlineData("nuint", "nuint")] [InlineData("nuint", "float")] [InlineData("nuint", "double")] [InlineData("nuint", "decimal")] [InlineData("float", "object")] [InlineData("float", "string")] [InlineData("float", "bool")] [InlineData("float", "char")] [InlineData("float", "sbyte")] [InlineData("float", "short")] [InlineData("float", "int")] [InlineData("float", "long")] [InlineData("float", "byte")] [InlineData("float", "ushort")] [InlineData("float", "uint")] [InlineData("float", "ulong")] [InlineData("float", "nint")] [InlineData("float", "nuint")] [InlineData("float", "float")] [InlineData("float", "double")] [InlineData("float", "decimal")] [InlineData("double", "object")] [InlineData("double", "string")] [InlineData("double", "bool")] [InlineData("double", "char")] [InlineData("double", "sbyte")] [InlineData("double", "short")] [InlineData("double", "int")] [InlineData("double", "long")] [InlineData("double", "byte")] [InlineData("double", "ushort")] [InlineData("double", "uint")] [InlineData("double", "ulong")] [InlineData("double", "nint")] [InlineData("double", "nuint")] [InlineData("double", "float")] [InlineData("double", "double")] [InlineData("double", "decimal")] [InlineData("decimal", "object")] [InlineData("decimal", "string")] [InlineData("decimal", "bool")] [InlineData("decimal", "char")] [InlineData("decimal", "sbyte")] [InlineData("decimal", "short")] [InlineData("decimal", "int")] [InlineData("decimal", "long")] [InlineData("decimal", "byte")] [InlineData("decimal", "ushort")] [InlineData("decimal", "uint")] [InlineData("decimal", "ulong")] [InlineData("decimal", "nint")] [InlineData("decimal", "nuint")] [InlineData("decimal", "float")] [InlineData("decimal", "double")] [InlineData("decimal", "decimal")] public void BuiltIn_Lifted_CompoundAssignment_02(string left, string right) { var nullableLeft = NullableIfPossible(left); var nullableRight = NullableIfPossible(right); var source1 = @" class C { static void Main() { " + nullableLeft + @" x = default; " + nullableRight + @" y = default; x >>= y; x >>>= y; } } "; var expected = new[] { // (8,9): error CS0019: Operator '>>=' cannot be applied to operands of type 'double' and 'char' // x >>= y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>= y").WithArguments(">>=", nullableLeft, nullableRight).WithLocation(8, 9), // (9,9): error CS0019: Operator '>>>=' cannot be applied to operands of type 'double' and 'char' // x >>>= y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>>= y").WithArguments(">>>=", nullableLeft, nullableRight).WithLocation(9, 9) }; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyEmitDiagnostics(expected); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyEmitDiagnostics(expected); } [Fact] public void BuiltIn_CompoundAssignment_CollectionInitializerElement_Lifted() { var source1 = @" class C { static void Main() { int? x = int.MinValue; var y = new System.Collections.Generic.List<int?>() { x >>= 1, x >>>= 1 }; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (8,13): error CS0747: Invalid initializer member declarator // x >>= 1, Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "x >>= 1").WithLocation(8, 13), // (9,13): error CS0747: Invalid initializer member declarator // x >>>= 1 Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "x >>>= 1").WithLocation(9, 13) ); } [Fact] public void BuiltIn_Lifted_ExpressionTree_01() { var source1 = @" class C { static void Main() { System.Linq.Expressions.Expression<System.Func<int?, int?, int?>> e = (x, y) => x >>> y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (6,89): error CS7053: An expression tree may not contain '>>>' // System.Linq.Expressions.Expression<System.Func<int?, int?, int?>> e = (x, y) => x >>> y; Diagnostic(ErrorCode.ERR_FeatureNotValidInExpressionTree, "x >>> y").WithArguments(">>>").WithLocation(6, 89) ); } [Fact] public void BuiltIn_Lifted_CompoundAssignment_ExpressionTree_01() { var source1 = @" class C { static void Main() { System.Linq.Expressions.Expression<System.Func<int?, int?, int?>> e = (x, y) => x >>>= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (6,89): error CS0832: An expression tree may not contain an assignment operator // System.Linq.Expressions.Expression<System.Func<int?, int?, int?>> e = (x, y) => x >>>= y; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "x >>>= y").WithLocation(6, 89) ); } [Fact] public void UserDefined_01() { var source0 = @" public class C1 { public static C1 operator >>>(C1 x, int y) { System.Console.WriteLine("">>>""); return x; } public static C1 operator >>(C1 x, int y) { System.Console.WriteLine("">>""); return x; } } "; var source1 = @" class C { static void Main() { Test1(new C1(), 1); } static C1 Test1(C1 x, int y) => x >>> y; static C1 Test2(C1 x, int y) => x >> y; } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(compilation1, expectedOutput: @">>>").VerifyDiagnostics(); string actualIL = verifier.VisualizeIL("C.Test2"); verifier.VerifyIL("C.Test1", actualIL.Replace("op_RightShift", "op_UnsignedRightShift")); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftExpression).First(); Assert.Equal("x >>> y", unsignedShift.ToString()); Assert.Equal("C1 C1.op_UnsignedRightShift(C1 x, System.Int32 y)", model.GetSymbolInfo(unsignedShift).Symbol.ToTestDisplayString()); Assert.Equal(MethodKind.UserDefinedOperator, compilation1.GetMember<MethodSymbol>("C1.op_UnsignedRightShift").MethodKind); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { compilation0.ToMetadataReference() }, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation2, expectedOutput: @">>>").VerifyDiagnostics(); Assert.Equal(MethodKind.UserDefinedOperator, compilation2.GetMember<MethodSymbol>("C1.op_UnsignedRightShift").MethodKind); var compilation3 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { compilation0.EmitToImageReference() }, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation3, expectedOutput: @">>>").VerifyDiagnostics(); Assert.Equal(MethodKind.UserDefinedOperator, compilation3.GetMember<MethodSymbol>("C1.op_UnsignedRightShift").MethodKind); } [Fact] public void UserDefined_02() { // The IL is equivalent to: // public class C1 // { // public static C1 operator >>>(C1 x, int y) // { // System.Console.WriteLine("">>>""); // return x; // } // } var ilSource = @" .class public auto ansi beforefieldinit C1 extends [mscorlib]System.Object { .method public hidebysig specialname static class C1 op_UnsignedRightShift ( class C1 x, int32 y ) cil managed { .maxstack 8 IL_0000: ldstr "">>>"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldarg.0 IL_000b: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } } "; var source1 = @" class C { static void Main() { Test1(new C1(), 1); } static C1 Test1(C1 x, int y) => C1.op_UnsignedRightShift(x, y); } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); // This code was previously allowed. We are accepting this source breaking change. compilation1.VerifyDiagnostics( // (9,40): error CS0571: 'C1.operator >>>(C1, int)': cannot explicitly call operator or accessor // static C1 Test1(C1 x, int y) => C1.op_UnsignedRightShift(x, y); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_UnsignedRightShift").WithArguments("C1.operator >>>(C1, int)").WithLocation(9, 40) ); } [Fact] public void UserDefined_03() { var source1 = @" public class C1 { public static void operator >>>(C1 x, int y) { throw null; } public static void operator >>(C1 x, int y) { throw null; } } public class C2 { public static C2 operator >>>(C1 x, int y) { throw null; } public static C2 operator >>(C1 x, int y) { throw null; } } public class C3 { public static C3 operator >>>(C3 x, C2 y) { throw null; } public static C3 operator >>(C3 x, C2 y) { throw null; } } public class C4 { public static int operator >>>(C4 x, int y) { throw null; } public static int operator >>(C4 x, int y) { throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyDiagnostics( // (4,33): error CS0590: User-defined operators cannot return void // public static void operator >>>(C1 x, int y) Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, ">>>").WithLocation(4, 33), // (9,33): error CS0590: User-defined operators cannot return void // public static void operator >>(C1 x, int y) Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, ">>").WithLocation(9, 33), // (17,31): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type // public static C2 operator >>>(C1 x, int y) Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, ">>>").WithLocation(17, 31), // (22,31): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type // public static C2 operator >>(C1 x, int y) Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, ">>").WithLocation(22, 31) ); } [Fact] public void UserDefined_04() { var source1 = @" public class C1 { public static C1 operator >>>(C1 x, int y) { throw null; } public static C1 op_UnsignedRightShift(C1 x, int y) { throw null; } } public class C2 { public static C2 op_UnsignedRightShift(C2 x, int y) { throw null; } public static C2 operator >>>(C2 x, int y) { throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyDiagnostics( // (9,22): error CS0111: Type 'C1' already defines a member called 'op_UnsignedRightShift' with the same parameter types // public static C1 op_UnsignedRightShift(C1 x, int y) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_UnsignedRightShift").WithArguments("op_UnsignedRightShift", "C1").WithLocation(9, 22), // (22,31): error CS0111: Type 'C2' already defines a member called 'op_UnsignedRightShift' with the same parameter types // public static C2 operator >>>(C2 x, int y) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, ">>>").WithArguments("op_UnsignedRightShift", "C2").WithLocation(22, 31) ); } [Fact] public void UserDefined_05() { var source0 = @" public struct C1 { public static C1 operator >>>(C1? x, int? y) { System.Console.WriteLine("">>>""); return x.Value; } public static C1 operator >>(C1? x, int? y) { System.Console.WriteLine("">>""); return x.Value; } } "; var source1 = @" class C { static void Main() { Test1(new C1(), 1); } static C1 Test1(C1? x, int? y) => x >>> y; static C1 Test2(C1? x, int? y) => x >> y; } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(compilation1, expectedOutput: @">>>").VerifyDiagnostics(); string actualIL = verifier.VisualizeIL("C.Test2"); verifier.VerifyIL("C.Test1", actualIL.Replace("op_RightShift", "op_UnsignedRightShift")); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftExpression).First(); Assert.Equal("x >>> y", unsignedShift.ToString()); Assert.Equal("C1 C1.op_UnsignedRightShift(C1? x, System.Int32? y)", model.GetSymbolInfo(unsignedShift).Symbol.ToTestDisplayString()); Assert.Equal(MethodKind.UserDefinedOperator, compilation1.GetMember<MethodSymbol>("C1.op_UnsignedRightShift").MethodKind); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { compilation0.ToMetadataReference() }, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation2, expectedOutput: @">>>").VerifyDiagnostics(); Assert.Equal(MethodKind.UserDefinedOperator, compilation2.GetMember<MethodSymbol>("C1.op_UnsignedRightShift").MethodKind); var compilation3 = CreateCompilation(source1, options: TestOptions.DebugExe, references: new[] { compilation0.EmitToImageReference() }, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation3, expectedOutput: @">>>").VerifyDiagnostics(); Assert.Equal(MethodKind.UserDefinedOperator, compilation3.GetMember<MethodSymbol>("C1.op_UnsignedRightShift").MethodKind); } [Fact] public void UserDefined_06() { var source0 = @" public class C1 { public static C1 op_UnsignedRightShift(C1 x, int y) { return x; } } "; var source1 = @" class C { static C1 Test1(C1 x, int y) => x >>> y; } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { compilation0.ToMetadataReference() }, parseOptions: TestOptions.RegularPreview); compilation2.VerifyDiagnostics( // (4,37): error CS0019: Operator '>>>' cannot be applied to operands of type 'C1' and 'int' // static C1 Test1(C1 x, int y) => x >>> y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>> y").WithArguments(">>>", "C1", "int").WithLocation(4, 37) ); var compilation3 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { compilation0.EmitToImageReference() }, parseOptions: TestOptions.RegularPreview); compilation3.VerifyDiagnostics( // (4,37): error CS0019: Operator '>>>' cannot be applied to operands of type 'C1' and 'int' // static C1 Test1(C1 x, int y) => x >>> y; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x >>> y").WithArguments(">>>", "C1", "int").WithLocation(4, 37) ); } [Fact] public void UserDefined_ExpressionTree_01() { var source1 = @" public class C1 { public static C1 operator >>>(C1 x, int y) { return x; } } class C { static void Main() { System.Linq.Expressions.Expression<System.Func<C1, int, C1>> e = (x, y) => x >>> y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (14,84): error CS7053: An expression tree may not contain '>>>' // System.Linq.Expressions.Expression<System.Func<C1, int, C1>> e = (x, y) => x >>> y; Diagnostic(ErrorCode.ERR_FeatureNotValidInExpressionTree, "x >>> y").WithArguments(">>>").WithLocation(14, 84) ); } [Fact] public void UserDefined_CompountAssignment_01() { var source1 = @" public class C1 { public int F; public static C1 operator >>>(C1 x, int y) { return new C1() { F = x.F >>> y }; } public static C1 operator >>(C1 x, int y) { return x; } } class C { static void Main() { if (Test1(new C1() { F = int.MinValue }, 1).F == (int.MinValue >>> 1)) System.Console.WriteLine(""Passed 1""); } static C1 Test1(C1 x, int y) { x >>>= y; return x; } static C1 Test2(C1 x, int y) { x >>= y; return x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(compilation1, expectedOutput: @"Passed 1").VerifyDiagnostics(); string actualIL = verifier.VisualizeIL("C.Test2"); verifier.VerifyIL("C.Test1", actualIL.Replace("op_RightShift", "op_UnsignedRightShift")); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftAssignmentExpression).First(); Assert.Equal("x >>>= y", unsignedShift.ToString()); Assert.Equal("C1 C1.op_UnsignedRightShift(C1 x, System.Int32 y)", model.GetSymbolInfo(unsignedShift).Symbol.ToTestDisplayString()); } [Fact] public void UserDefined_CompoundAssignment_ExpressionTree_01() { var source1 = @" public class C1 { public static C1 operator >>>(C1 x, int y) { return x; } } class C { static void Main() { System.Linq.Expressions.Expression<System.Func<C1, int, C1>> e = (x, y) => x >>>= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (14,84): error CS0832: An expression tree may not contain an assignment operator // System.Linq.Expressions.Expression<System.Func<C1, int, C1>> e = (x, y) => x >>>= y; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "x >>>= y").WithLocation(14, 84) ); } [Fact] public void UserDefined_CompoundAssignment_CollectionInitializerElement() { var source1 = @" public class C1 { public static C1 operator >>>(C1 x, int y) { return x; } public static C1 operator >>(C1 x, int y) { return x; } } class C { static void Main() { var x = new C1(); var y = new System.Collections.Generic.List<C1>() { x >>= 1, x >>>= 1 }; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (21,13): error CS0747: Invalid initializer member declarator // x >>= 1, Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "x >>= 1").WithLocation(21, 13), // (22,13): error CS0747: Invalid initializer member declarator // x >>>= 1 Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "x >>>= 1").WithLocation(22, 13) ); } [Fact] public void UserDefined_Lifted_01() { var source0 = @" public struct C1 { public static C1 operator >>>(C1 x, int y) { System.Console.WriteLine("">>>""); return x; } public static C1 operator >>(C1 x, int y) { System.Console.WriteLine("">>""); return x; } } "; var source1 = @" class C { static void Main() { if (Test1(new C1(), 1) is not null) System.Console.WriteLine(""Passed 1""); if (Test1(null, 1) is null) System.Console.WriteLine(""Passed 2""); if (Test1(new C1(), null) is null) System.Console.WriteLine(""Passed 3""); if (Test1(null, null) is null) System.Console.WriteLine(""Passed 4""); } static C1? Test1(C1? x, int? y) => x >>> y; static C1? Test2(C1? x, int? y) => x >> y; } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(compilation1, expectedOutput: @" >>> Passed 1 Passed 2 Passed 3 Passed 4 ").VerifyDiagnostics(); string actualIL = verifier.VisualizeIL("C.Test2"); verifier.VerifyIL("C.Test1", actualIL.Replace("op_RightShift", "op_UnsignedRightShift")); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftExpression).First(); Assert.Equal("x >>> y", unsignedShift.ToString()); Assert.Equal("C1 C1.op_UnsignedRightShift(C1 x, System.Int32 y)", model.GetSymbolInfo(unsignedShift).Symbol.ToTestDisplayString()); } [Fact] public void UserDefined_Lifted_ExpressionTree_01() { var source1 = @" public struct C1 { public static C1 operator >>>(C1 x, int y) { return x; } } class C { static void Main() { System.Linq.Expressions.Expression<System.Func<C1?, int?, C1?>> e = (x, y) => x >>> y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (14,87): error CS7053: An expression tree may not contain '>>>' // System.Linq.Expressions.Expression<System.Func<C1?, int?, C1?>> e = (x, y) => x >>> y; Diagnostic(ErrorCode.ERR_FeatureNotValidInExpressionTree, "x >>> y").WithArguments(">>>").WithLocation(14, 87) ); } [Fact] public void UserDefined_Lifted_CompountAssignment_01() { var source1 = @" public struct C1 { public int F; public static C1 operator >>>(C1 x, int y) { return new C1() { F = x.F >>> y }; } public static C1 operator >>(C1 x, int y) { return x; } } class C { static void Main() { if (Test1(new C1() { F = int.MinValue }, 1).Value.F == (int.MinValue >>> 1)) System.Console.WriteLine(""Passed 1""); if (Test1(null, 1) is null) System.Console.WriteLine(""Passed 2""); if (Test1(new C1(), null) is null) System.Console.WriteLine(""Passed 3""); if (Test1(null, null) is null) System.Console.WriteLine(""Passed 4""); } static C1? Test1(C1? x, int? y) { x >>>= y; return x; } static C1? Test2(C1? x, int? y) { x >>= y; return x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(compilation1, expectedOutput: @" Passed 1 Passed 2 Passed 3 Passed 4 ").VerifyDiagnostics(); string actualIL = verifier.VisualizeIL("C.Test2"); verifier.VerifyIL("C.Test1", actualIL.Replace("op_RightShift", "op_UnsignedRightShift")); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var unsignedShift = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(e => e.Kind() == SyntaxKind.UnsignedRightShiftAssignmentExpression).First(); Assert.Equal("x >>>= y", unsignedShift.ToString()); Assert.Equal("C1 C1.op_UnsignedRightShift(C1 x, System.Int32 y)", model.GetSymbolInfo(unsignedShift).Symbol.ToTestDisplayString()); } [Fact] public void UserDefined_Lifted_CompoundAssignment_ExpressionTree_01() { var source1 = @" public struct C1 { public static C1 operator >>>(C1 x, int y) { return x; } } class C { static void Main() { System.Linq.Expressions.Expression<System.Func<C1?, int?, C1?>> e = (x, y) => x >>>= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (14,87): error CS0832: An expression tree may not contain an assignment operator // System.Linq.Expressions.Expression<System.Func<C1?, int?, C1?>> e = (x, y) => x >>>= y; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "x >>>= y").WithLocation(14, 87) ); } [Fact] public void UserDefined_Lifted_CompoundAssignment_CollectionInitializerElement() { var source1 = @" public struct C1 { public static C1 operator >>>(C1 x, int y) { return x; } public static C1 operator >>(C1 x, int y) { return x; } } class C { static void Main() { C1? x = new C1(); var y = new System.Collections.Generic.List<C1?>() { x >>= 1, x >>>= 1 }; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyEmitDiagnostics( // (21,13): error CS0747: Invalid initializer member declarator // x >>= 1, Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "x >>= 1").WithLocation(21, 13), // (22,13): error CS0747: Invalid initializer member declarator // x >>>= 1 Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "x >>>= 1").WithLocation(22, 13) ); } [Fact] public void CRef_NoParameters_01() { var source = @" /// <summary> /// See <see cref=""operator >>>""/>. /// </summary> class C { public static C operator >>>(C c, int y) { return null; } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var expectedSymbol = compilation.SourceModule.GlobalNamespace.GetTypeMember("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind != MethodKind.Constructor).First(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation); Assert.Equal(expectedSymbol, actualSymbol); compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.Regular10.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics( // (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute 'operator >>>' // /// See <see cref="operator >>>"/>. Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "operator >>>").WithArguments("operator >>>").WithLocation(3, 20), // (3,29): warning CS1658: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.. See also error CS8652. // /// See <see cref="operator >>>"/>. Diagnostic(ErrorCode.WRN_ErrorOverride, ">>>").WithArguments("The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.", "8652").WithLocation(3, 29), // (7,30): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public static C operator >>>(C c, int y) Diagnostic(ErrorCode.ERR_FeatureInPreview, ">>>").WithArguments("unsigned right shift").WithLocation(7, 30) ); crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); expectedSymbol = compilation.SourceModule.GlobalNamespace.GetTypeMember("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind != MethodKind.Constructor).First(); actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation); Assert.Equal(expectedSymbol, actualSymbol); compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularNext.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(); crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); expectedSymbol = compilation.SourceModule.GlobalNamespace.GetTypeMember("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind != MethodKind.Constructor).First(); actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation); Assert.Equal(expectedSymbol, actualSymbol); } [Fact] public void CRef_NoParameters_02() { var source = @" /// <summary> /// See <see cref=""operator >>>""/>. /// </summary> class C { public static C operator >>(C c, int y) { return null; } } "; var expected = new[] { // (3,20): warning CS1574: XML comment has cref attribute 'operator >>>' that could not be resolved // /// See <see cref="operator >>>"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "operator >>>").WithArguments("operator >>>").WithLocation(3, 20) }; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(expected); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation, expected); Assert.Null(actualSymbol); } [Fact] public void CRef_NoParameters_03() { var source = @" /// <summary> /// See <see cref=""operator >>""/>. /// </summary> class C { public static C operator >>>(C c, int y) { return null; } } "; var expected = new[] { // (3,20): warning CS1574: XML comment has cref attribute 'operator >>' that could not be resolved // /// See <see cref="operator >>"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "operator >>").WithArguments("operator >>").WithLocation(3, 20) }; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(expected); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation, expected); Assert.Null(actualSymbol); } [Fact] public void CRef_NoParameters_04() { var source = @" /// <summary> /// See <see cref=""operator >>>=""/>. /// </summary> class C { public static C operator >>>(C c, int y) { return null; } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics( // (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute 'operator >>>=' // /// See <see cref="operator >>>="/>. Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "operator").WithArguments("operator >>>=").WithLocation(3, 20), // (3,28): warning CS1658: Overloadable operator expected. See also error CS1037. // /// See <see cref="operator >>>="/>. Diagnostic(ErrorCode.WRN_ErrorOverride, " >>>").WithArguments("Overloadable operator expected", "1037").WithLocation(3, 28) ); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation, // (3,20): warning CS1574: XML comment has cref attribute 'operator' that could not be resolved // /// See <see cref="operator >>>="/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "operator").WithArguments("operator").WithLocation(3, 20) ); Assert.Null(actualSymbol); } [Fact] public void CRef_OneParameter_01() { var source = @" /// <summary> /// See <see cref=""operator >>>(C)""/>. /// </summary> class C { public static C operator >>>(C c, int y) { return null; } } "; var expected = new[] { // (3,20): warning CS1574: XML comment has cref attribute 'operator >>>(C)' that could not be resolved // /// See <see cref="operator >>>(C)"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "operator >>>(C)").WithArguments("operator >>>(C)").WithLocation(3, 20) }; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(expected); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation, expected); Assert.Null(actualSymbol); } [Fact] public void CRef_TwoParameters_01() { var source = @" /// <summary> /// See <see cref=""operator >>>(C, int)""/>. /// </summary> class C { public static C operator >>>(C c, int y) { return null; } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var expectedSymbol = compilation.SourceModule.GlobalNamespace.GetTypeMember("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind != MethodKind.Constructor).First(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation); Assert.Equal(expectedSymbol, actualSymbol); compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.Regular10.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics( // (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute 'operator >>>(C, int)' // /// See <see cref="operator >>>(C, int)"/>. Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "operator >>>(C, int)").WithArguments("operator >>>(C, int)").WithLocation(3, 20), // (3,29): warning CS1658: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.. See also error CS8652. // /// See <see cref="operator >>>(C, int)"/>. Diagnostic(ErrorCode.WRN_ErrorOverride, ">>>").WithArguments("The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.", "8652").WithLocation(3, 29), // (7,30): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public static C operator >>>(C c, int y) Diagnostic(ErrorCode.ERR_FeatureInPreview, ">>>").WithArguments("unsigned right shift").WithLocation(7, 30) ); crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); expectedSymbol = compilation.SourceModule.GlobalNamespace.GetTypeMember("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind != MethodKind.Constructor).First(); actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation); Assert.Equal(expectedSymbol, actualSymbol); compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularNext.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(); crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); expectedSymbol = compilation.SourceModule.GlobalNamespace.GetTypeMember("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind != MethodKind.Constructor).First(); actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation); Assert.Equal(expectedSymbol, actualSymbol); } [Fact] public void CRef_TwoParameters_02() { var source = @" /// <summary> /// See <see cref=""operator >>>(C, int)""/>. /// </summary> class C { public static C operator >>(C c, int y) { return null; } } "; var expected = new[] { // (3,20): warning CS1574: XML comment has cref attribute 'operator >>>(C, int)' that could not be resolved // /// See <see cref="operator >>>(C, int)"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "operator >>>(C, int)").WithArguments("operator >>>(C, int)").WithLocation(3, 20) }; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(expected); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation, expected); Assert.Null(actualSymbol); } [Fact] public void CRef_TwoParameters_03() { var source = @" /// <summary> /// See <see cref=""operator >>(C, int)""/>. /// </summary> class C { public static C operator >>>(C c, int y) { return null; } } "; var expected = new[] { // (3,20): warning CS1574: XML comment has cref attribute 'operator >>(C, int)' that could not be resolved // /// See <see cref="operator >>(C, int)"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "operator >>(C, int)").WithArguments("operator >>(C, int)").WithLocation(3, 20) }; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(expected); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation, expected); Assert.Null(actualSymbol); } [Fact] public void CRef_TwoParameters_04() { var source = @" /// <summary> /// See <see cref=""operator >>>=(C, int)""/>. /// </summary> class C { public static C operator >>>(C c, int y) { return null; } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics( // (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute 'operator >>>=(C, int)' // /// See <see cref="operator >>>=(C, int)"/>. Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "operator >>>=(C, int)").WithArguments("operator >>>=(C, int)").WithLocation(3, 20), // (3,28): warning CS1658: Overloadable operator expected. See also error CS1037. // /// See <see cref="operator >>>=(C, int)"/>. Diagnostic(ErrorCode.WRN_ErrorOverride, " >>>").WithArguments("Overloadable operator expected", "1037").WithLocation(3, 28) ); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation, // (3,20): warning CS1574: XML comment has cref attribute 'operator >>>=(C, int)' that could not be resolved // /// See <see cref="operator >>>=(C, int)"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "operator >>>=(C, int)").WithArguments("operator >>>=(C, int)").WithLocation(3, 20) ); Assert.Null(actualSymbol); } [Fact] public void CRef_ThreeParameter_01() { var source = @" /// <summary> /// See <see cref=""operator >>>(C, int, object)""/>. /// </summary> class C { public static C operator >>>(C c, int y) { return null; } } "; var expected = new[] { // (3,20): warning CS1574: XML comment has cref attribute 'operator >>>(C, int, object)' that could not be resolved // /// See <see cref="operator >>>(C, int, object)"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "operator >>>(C, int, object)").WithArguments("operator >>>(C, int, object)").WithLocation(3, 20) }; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, parseOptions: TestOptions.RegularPreview.WithDocumentationMode(DocumentationMode.Diagnose)); compilation.VerifyDiagnostics(expected); var crefSyntax = CrefTests.GetCrefSyntaxes(compilation).Single(); var actualSymbol = CrefTests.GetReferencedSymbol(crefSyntax, compilation, expected); Assert.Null(actualSymbol); } [Theory] [InlineData("char", "char")] [InlineData("char", "sbyte")] [InlineData("char", "short")] [InlineData("char", "int")] [InlineData("char", "byte")] [InlineData("char", "ushort")] [InlineData("sbyte", "char")] [InlineData("sbyte", "sbyte")] [InlineData("sbyte", "short")] [InlineData("sbyte", "int")] [InlineData("sbyte", "byte")] [InlineData("sbyte", "ushort")] [InlineData("short", "char")] [InlineData("short", "sbyte")] [InlineData("short", "short")] [InlineData("short", "int")] [InlineData("short", "byte")] [InlineData("short", "ushort")] [InlineData("int", "char")] [InlineData("int", "sbyte")] [InlineData("int", "short")] [InlineData("int", "int")] [InlineData("int", "byte")] [InlineData("int", "ushort")] [InlineData("long", "char")] [InlineData("long", "sbyte")] [InlineData("long", "short")] [InlineData("long", "int")] [InlineData("long", "byte")] [InlineData("long", "ushort")] [InlineData("byte", "char")] [InlineData("byte", "sbyte")] [InlineData("byte", "short")] [InlineData("byte", "int")] [InlineData("byte", "byte")] [InlineData("byte", "ushort")] [InlineData("ushort", "char")] [InlineData("ushort", "sbyte")] [InlineData("ushort", "short")] [InlineData("ushort", "int")] [InlineData("ushort", "byte")] [InlineData("ushort", "ushort")] [InlineData("uint", "char")] [InlineData("uint", "sbyte")] [InlineData("uint", "short")] [InlineData("uint", "int")] [InlineData("uint", "byte")] [InlineData("uint", "ushort")] [InlineData("ulong", "char")] [InlineData("ulong", "sbyte")] [InlineData("ulong", "short")] [InlineData("ulong", "int")] [InlineData("ulong", "byte")] [InlineData("ulong", "ushort")] [InlineData("nint", "char")] [InlineData("nint", "sbyte")] [InlineData("nint", "short")] [InlineData("nint", "int")] [InlineData("nint", "byte")] [InlineData("nint", "ushort")] [InlineData("nuint", "char")] [InlineData("nuint", "sbyte")] [InlineData("nuint", "short")] [InlineData("nuint", "int")] [InlineData("nuint", "byte")] [InlineData("nuint", "ushort")] public void BuiltIn_LangVersion_01(string left, string right) { var source1 = @" class C { static void Main() { " + left + @" x = default; " + right + @" y = default; _ = x >>> y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10); compilation1.VerifyDiagnostics( // (8,13): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x >>> y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x >>> y").WithArguments("unsigned right shift").WithLocation(8, 13) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); compilation2.VerifyDiagnostics(); } [Theory] [InlineData("char", "char")] [InlineData("char", "sbyte")] [InlineData("char", "short")] [InlineData("char", "int")] [InlineData("char", "byte")] [InlineData("char", "ushort")] [InlineData("sbyte", "char")] [InlineData("sbyte", "sbyte")] [InlineData("sbyte", "short")] [InlineData("sbyte", "int")] [InlineData("sbyte", "byte")] [InlineData("sbyte", "ushort")] [InlineData("short", "char")] [InlineData("short", "sbyte")] [InlineData("short", "short")] [InlineData("short", "int")] [InlineData("short", "byte")] [InlineData("short", "ushort")] [InlineData("int", "char")] [InlineData("int", "sbyte")] [InlineData("int", "short")] [InlineData("int", "int")] [InlineData("int", "byte")] [InlineData("int", "ushort")] [InlineData("long", "char")] [InlineData("long", "sbyte")] [InlineData("long", "short")] [InlineData("long", "int")] [InlineData("long", "byte")] [InlineData("long", "ushort")] [InlineData("byte", "char")] [InlineData("byte", "sbyte")] [InlineData("byte", "short")] [InlineData("byte", "int")] [InlineData("byte", "byte")] [InlineData("byte", "ushort")] [InlineData("ushort", "char")] [InlineData("ushort", "sbyte")] [InlineData("ushort", "short")] [InlineData("ushort", "int")] [InlineData("ushort", "byte")] [InlineData("ushort", "ushort")] [InlineData("uint", "char")] [InlineData("uint", "sbyte")] [InlineData("uint", "short")] [InlineData("uint", "int")] [InlineData("uint", "byte")] [InlineData("uint", "ushort")] [InlineData("ulong", "char")] [InlineData("ulong", "sbyte")] [InlineData("ulong", "short")] [InlineData("ulong", "int")] [InlineData("ulong", "byte")] [InlineData("ulong", "ushort")] [InlineData("nint", "char")] [InlineData("nint", "sbyte")] [InlineData("nint", "short")] [InlineData("nint", "int")] [InlineData("nint", "byte")] [InlineData("nint", "ushort")] [InlineData("nuint", "char")] [InlineData("nuint", "sbyte")] [InlineData("nuint", "short")] [InlineData("nuint", "int")] [InlineData("nuint", "byte")] [InlineData("nuint", "ushort")] public void BuiltIn_CompoundAssignment_LangVersion_01(string left, string right) { var source1 = @" class C { static void Main() { " + left + @" x = default; " + right + @" y = default; x >>>= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10); compilation1.VerifyDiagnostics( // (8,9): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x >>>= y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x >>>= y").WithArguments("unsigned right shift").WithLocation(8, 9) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); compilation2.VerifyDiagnostics(); } [Theory] [InlineData("char", "char")] [InlineData("char", "sbyte")] [InlineData("char", "short")] [InlineData("char", "int")] [InlineData("char", "byte")] [InlineData("char", "ushort")] [InlineData("sbyte", "char")] [InlineData("sbyte", "sbyte")] [InlineData("sbyte", "short")] [InlineData("sbyte", "int")] [InlineData("sbyte", "byte")] [InlineData("sbyte", "ushort")] [InlineData("short", "char")] [InlineData("short", "sbyte")] [InlineData("short", "short")] [InlineData("short", "int")] [InlineData("short", "byte")] [InlineData("short", "ushort")] [InlineData("int", "char")] [InlineData("int", "sbyte")] [InlineData("int", "short")] [InlineData("int", "int")] [InlineData("int", "byte")] [InlineData("int", "ushort")] [InlineData("long", "char")] [InlineData("long", "sbyte")] [InlineData("long", "short")] [InlineData("long", "int")] [InlineData("long", "byte")] [InlineData("long", "ushort")] [InlineData("byte", "char")] [InlineData("byte", "sbyte")] [InlineData("byte", "short")] [InlineData("byte", "int")] [InlineData("byte", "byte")] [InlineData("byte", "ushort")] [InlineData("ushort", "char")] [InlineData("ushort", "sbyte")] [InlineData("ushort", "short")] [InlineData("ushort", "int")] [InlineData("ushort", "byte")] [InlineData("ushort", "ushort")] [InlineData("uint", "char")] [InlineData("uint", "sbyte")] [InlineData("uint", "short")] [InlineData("uint", "int")] [InlineData("uint", "byte")] [InlineData("uint", "ushort")] [InlineData("ulong", "char")] [InlineData("ulong", "sbyte")] [InlineData("ulong", "short")] [InlineData("ulong", "int")] [InlineData("ulong", "byte")] [InlineData("ulong", "ushort")] [InlineData("nint", "char")] [InlineData("nint", "sbyte")] [InlineData("nint", "short")] [InlineData("nint", "int")] [InlineData("nint", "byte")] [InlineData("nint", "ushort")] [InlineData("nuint", "char")] [InlineData("nuint", "sbyte")] [InlineData("nuint", "short")] [InlineData("nuint", "int")] [InlineData("nuint", "byte")] [InlineData("nuint", "ushort")] public void BuiltIn_Lifted_LangVersion_01(string left, string right) { var source1 = @" class C { static void Main() { " + left + @"? x = default; " + right + @"? y = default; _ = x >>> y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10); compilation1.VerifyDiagnostics( // (8,13): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x >>> y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x >>> y").WithArguments("unsigned right shift").WithLocation(8, 13) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); compilation2.VerifyDiagnostics(); } [Theory] [InlineData("char", "char")] [InlineData("char", "sbyte")] [InlineData("char", "short")] [InlineData("char", "int")] [InlineData("char", "byte")] [InlineData("char", "ushort")] [InlineData("sbyte", "char")] [InlineData("sbyte", "sbyte")] [InlineData("sbyte", "short")] [InlineData("sbyte", "int")] [InlineData("sbyte", "byte")] [InlineData("sbyte", "ushort")] [InlineData("short", "char")] [InlineData("short", "sbyte")] [InlineData("short", "short")] [InlineData("short", "int")] [InlineData("short", "byte")] [InlineData("short", "ushort")] [InlineData("int", "char")] [InlineData("int", "sbyte")] [InlineData("int", "short")] [InlineData("int", "int")] [InlineData("int", "byte")] [InlineData("int", "ushort")] [InlineData("long", "char")] [InlineData("long", "sbyte")] [InlineData("long", "short")] [InlineData("long", "int")] [InlineData("long", "byte")] [InlineData("long", "ushort")] [InlineData("byte", "char")] [InlineData("byte", "sbyte")] [InlineData("byte", "short")] [InlineData("byte", "int")] [InlineData("byte", "byte")] [InlineData("byte", "ushort")] [InlineData("ushort", "char")] [InlineData("ushort", "sbyte")] [InlineData("ushort", "short")] [InlineData("ushort", "int")] [InlineData("ushort", "byte")] [InlineData("ushort", "ushort")] [InlineData("uint", "char")] [InlineData("uint", "sbyte")] [InlineData("uint", "short")] [InlineData("uint", "int")] [InlineData("uint", "byte")] [InlineData("uint", "ushort")] [InlineData("ulong", "char")] [InlineData("ulong", "sbyte")] [InlineData("ulong", "short")] [InlineData("ulong", "int")] [InlineData("ulong", "byte")] [InlineData("ulong", "ushort")] [InlineData("nint", "char")] [InlineData("nint", "sbyte")] [InlineData("nint", "short")] [InlineData("nint", "int")] [InlineData("nint", "byte")] [InlineData("nint", "ushort")] [InlineData("nuint", "char")] [InlineData("nuint", "sbyte")] [InlineData("nuint", "short")] [InlineData("nuint", "int")] [InlineData("nuint", "byte")] [InlineData("nuint", "ushort")] public void BuiltIn_Lifted_CompoundAssignment_LangVersion_01(string left, string right) { var source1 = @" class C { static void Main() { " + left + @"? x = default; " + right + @"? y = default; x >>>= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10); compilation1.VerifyDiagnostics( // (8,9): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x >>>= y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x >>>= y").WithArguments("unsigned right shift").WithLocation(8, 9) ); var compilation2 = CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularNext); compilation2.VerifyDiagnostics(); } [Fact] public void UserDefined_LangVersion_01() { var source0 = @" public class C1 { public static C1 operator >>>(C1 x, int y) { System.Console.WriteLine("">>>""); return x; } } "; var source1 = @" class C { static C1 Test1(C1 x, int y) => x >>> y; } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyDiagnostics( // (4,31): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public static C1 operator >>>(C1 x, int y) Diagnostic(ErrorCode.ERR_FeatureInPreview, ">>>").WithArguments("unsigned right shift").WithLocation(4, 31) ); compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyDiagnostics(); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); foreach (var reference in new[] { compilation0.ToMetadataReference(), compilation0.EmitToImageReference() }) { var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular10); compilation2.VerifyDiagnostics( // (4,37): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static C1 Test1(C1 x, int y) => x >>> y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x >>> y").WithArguments("unsigned right shift").WithLocation(4, 37) ); compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.RegularNext); compilation2.VerifyDiagnostics(); } } [Fact] public void UserDefined_CompountAssignment_LangVersion_01() { var source0 = @" public class C1 { public static C1 operator >>>(C1 x, int y) { System.Console.WriteLine("">>>""); return x; } } "; var source1 = @" class C { static C1 Test1(C1 x, int y) => x >>>= y; } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyDiagnostics( // (4,31): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public static C1 operator >>>(C1 x, int y) Diagnostic(ErrorCode.ERR_FeatureInPreview, ">>>").WithArguments("unsigned right shift").WithLocation(4, 31) ); compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyDiagnostics(); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); foreach (var reference in new[] { compilation0.ToMetadataReference(), compilation0.EmitToImageReference() }) { var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular10); compilation2.VerifyDiagnostics( // (4,37): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static C1 Test1(C1 x, int y) => x >>>= y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x >>>= y").WithArguments("unsigned right shift").WithLocation(4, 37) ); compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.RegularNext); compilation2.VerifyDiagnostics(); } } [Fact] public void UserDefined_Lifted_LangVersion_01() { var source0 = @" public struct C1 { public static C1 operator >>>(C1 x, int y) { System.Console.WriteLine("">>>""); return x; } } "; var source1 = @" class C { static C1? Test1(C1? x, int? y) => x >>> y; } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyDiagnostics( // (4,31): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public static C1 operator >>>(C1 x, int y) Diagnostic(ErrorCode.ERR_FeatureInPreview, ">>>").WithArguments("unsigned right shift").WithLocation(4, 31) ); compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyDiagnostics(); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); foreach (var reference in new[] { compilation0.ToMetadataReference(), compilation0.EmitToImageReference() }) { var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular10); compilation2.VerifyDiagnostics( // (4,40): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static C1? Test1(C1? x, int? y) => x >>> y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x >>> y").WithArguments("unsigned right shift").WithLocation(4, 40) ); compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.RegularNext); compilation2.VerifyDiagnostics(); } } [Fact] public void UserDefined_Lifted_CompountAssignment_LangVersion_01() { var source0 = @" public struct C1 { public static C1 operator >>>(C1 x, int y) { System.Console.WriteLine("">>>""); return x; } } "; var source1 = @" class C { static C1? Test1(C1? x, int? y) => x >>>= y; } "; var compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular10); compilation1.VerifyDiagnostics( // (4,31): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public static C1 operator >>>(C1 x, int y) Diagnostic(ErrorCode.ERR_FeatureInPreview, ">>>").WithArguments("unsigned right shift").WithLocation(4, 31) ); compilation1 = CreateCompilation(source0 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularNext); compilation1.VerifyDiagnostics(); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); foreach (var reference in new[] { compilation0.ToMetadataReference(), compilation0.EmitToImageReference() }) { var compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.Regular10); compilation2.VerifyDiagnostics( // (4,40): error CS8652: The feature 'unsigned right shift' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static C1? Test1(C1? x, int? y) => x >>>= y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x >>>= y").WithArguments("unsigned right shift").WithLocation(4, 40) ); compilation2 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { reference }, parseOptions: TestOptions.RegularNext); compilation2.VerifyDiagnostics(); } } [Fact] public void TestGenericArgWithGreaterThan_05() { var source1 = @" class C { void M() { var added = ImmutableDictionary<T<(S a, U b)>>> ProjectChange = projectChange; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview); compilation1.VerifyDiagnostics( // (6,21): error CS0103: The name 'ImmutableDictionary' does not exist in the current context // var added = ImmutableDictionary<T<(S a, U b)>>> Diagnostic(ErrorCode.ERR_NameNotInContext, "ImmutableDictionary").WithArguments("ImmutableDictionary").WithLocation(6, 21), // (6,41): error CS0103: The name 'T' does not exist in the current context // var added = ImmutableDictionary<T<(S a, U b)>>> Diagnostic(ErrorCode.ERR_NameNotInContext, "T").WithArguments("T").WithLocation(6, 41), // (6,44): error CS0246: The type or namespace name 'S' could not be found (are you missing a using directive or an assembly reference?) // var added = ImmutableDictionary<T<(S a, U b)>>> Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "S").WithArguments("S").WithLocation(6, 44), // (6,44): error CS8185: A declaration is not allowed in this context. // var added = ImmutableDictionary<T<(S a, U b)>>> Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "S a").WithLocation(6, 44), // (6,49): error CS0246: The type or namespace name 'U' could not be found (are you missing a using directive or an assembly reference?) // var added = ImmutableDictionary<T<(S a, U b)>>> Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "U").WithArguments("U").WithLocation(6, 49), // (6,49): error CS8185: A declaration is not allowed in this context. // var added = ImmutableDictionary<T<(S a, U b)>>> Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "U b").WithLocation(6, 49), // (8,9): error CS0103: The name 'ProjectChange' does not exist in the current context // ProjectChange = projectChange; Diagnostic(ErrorCode.ERR_NameNotInContext, "ProjectChange").WithArguments("ProjectChange").WithLocation(8, 9), // (8,25): error CS0103: The name 'projectChange' does not exist in the current context // ProjectChange = projectChange; Diagnostic(ErrorCode.ERR_NameNotInContext, "projectChange").WithArguments("projectChange").WithLocation(8, 25) ); } [Fact] public void CanBeValidAttributeArgument() { string source = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; public class Parent { public void TestRightShift([Optional][DefaultParameterValue(300 >> 1)] int i) { Console.Write(i); } public void TestUnsignedRightShift([Optional][DefaultParameterValue(300 >>> 1)] int i) { Console.Write(i); } } class Test { public static void Main() { var p = new Parent(); p.TestRightShift(); p.TestUnsignedRightShift(); } } "; CompileAndVerify(source, expectedOutput: @"150150", parseOptions: TestOptions.RegularNext); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/Portable/Syntax/InternalSyntax/SyntaxSubKind.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend Enum SyntaxSubKind None BeginDocTypeToken LessThanExclamationToken OpenBracketToken CloseBracketToken End Enum End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend Enum SyntaxSubKind None BeginDocTypeToken LessThanExclamationToken OpenBracketToken CloseBracketToken End Enum End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/CSharp/Portable/ConvertCast/CSharpConvertTryCastToDirectCastCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertCast; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Microsoft.CodeAnalysis.CSharp.ConvertCast { /// <summary> /// Refactor: /// var o = 1 as object; /// /// Into: /// var o = (object)1; /// </summary> [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertTryCastToDirectCast), Shared] internal partial class CSharpConvertTryCastToDirectCastCodeRefactoringProvider : AbstractConvertCastCodeRefactoringProvider<TypeSyntax, BinaryExpressionSyntax, CastExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertTryCastToDirectCastCodeRefactoringProvider() { } protected override string GetTitle() => CSharpFeaturesResources.Change_to_cast; protected override int FromKind => (int)SyntaxKind.AsExpression; protected override TypeSyntax GetTypeNode(BinaryExpressionSyntax expression) => (TypeSyntax)expression.Right; protected override CastExpressionSyntax ConvertExpression(BinaryExpressionSyntax asExpression) { var expression = asExpression.Left; var typeNode = GetTypeNode(asExpression); // Trivia handling: // #0 exp #1 as #2 Type #3 // #0 #2 (Type)exp #1 #3 // Some trivia in the middle (#1 and #2) is moved to the front or behind the expression // #1 and #2 change their position in the expression (#2 goes in front to stay near the type and #1 to the end to stay near the expression) // Some whitespace around the as operator is removed to follow the formatting rules of (Type)expr var openParen = Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty); var closeParen = Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty); var newTrailingTrivia = asExpression.Left.GetTrailingTrivia().SkipInitialWhitespace().ToSyntaxTriviaList().AddRange(asExpression.GetTrailingTrivia()); var newLeadingTrivia = asExpression.GetLeadingTrivia().AddRange(asExpression.OperatorToken.TrailingTrivia.SkipInitialWhitespace()); typeNode = typeNode.WithoutTrailingTrivia(); var castExpression = CastExpression(openParen, typeNode, closeParen, expression.WithoutTrailingTrivia()) .WithLeadingTrivia(newLeadingTrivia) .WithTrailingTrivia(newTrailingTrivia); return castExpression; } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertCast; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Microsoft.CodeAnalysis.CSharp.ConvertCast { /// <summary> /// Refactor: /// var o = 1 as object; /// /// Into: /// var o = (object)1; /// </summary> [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertTryCastToDirectCast), Shared] internal partial class CSharpConvertTryCastToDirectCastCodeRefactoringProvider : AbstractConvertCastCodeRefactoringProvider<TypeSyntax, BinaryExpressionSyntax, CastExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertTryCastToDirectCastCodeRefactoringProvider() { } protected override string GetTitle() => CSharpFeaturesResources.Change_to_cast; protected override int FromKind => (int)SyntaxKind.AsExpression; protected override TypeSyntax GetTypeNode(BinaryExpressionSyntax expression) => (TypeSyntax)expression.Right; protected override CastExpressionSyntax ConvertExpression(BinaryExpressionSyntax asExpression) { var expression = asExpression.Left; var typeNode = GetTypeNode(asExpression); // Trivia handling: // #0 exp #1 as #2 Type #3 // #0 #2 (Type)exp #1 #3 // Some trivia in the middle (#1 and #2) is moved to the front or behind the expression // #1 and #2 change their position in the expression (#2 goes in front to stay near the type and #1 to the end to stay near the expression) // Some whitespace around the as operator is removed to follow the formatting rules of (Type)expr var openParen = Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty); var closeParen = Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty); var newTrailingTrivia = asExpression.Left.GetTrailingTrivia().SkipInitialWhitespace().ToSyntaxTriviaList().AddRange(asExpression.GetTrailingTrivia()); var newLeadingTrivia = asExpression.GetLeadingTrivia().AddRange(asExpression.OperatorToken.TrailingTrivia.SkipInitialWhitespace()); typeNode = typeNode.WithoutTrailingTrivia(); var castExpression = CastExpression(openParen, typeNode, closeParen, expression.WithoutTrailingTrivia()) .WithLeadingTrivia(newLeadingTrivia) .WithTrailingTrivia(newTrailingTrivia); return castExpression; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/DisableKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class DisableKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public DisableKeywordRecommender() : base(SyntaxKind.DisableKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var previousToken1 = context.TargetToken; var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true); var previousToken3 = previousToken2.GetPreviousToken(includeSkipped: true); if (previousToken1.Kind() == SyntaxKind.NullableKeyword && previousToken2.Kind() == SyntaxKind.HashToken) { // # nullable | // # nullable d| return true; } // # pragma warning | // # pragma warning d| return previousToken1.Kind() == SyntaxKind.WarningKeyword && previousToken2.Kind() == SyntaxKind.PragmaKeyword && previousToken3.Kind() == SyntaxKind.HashToken; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class DisableKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public DisableKeywordRecommender() : base(SyntaxKind.DisableKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var previousToken1 = context.TargetToken; var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true); var previousToken3 = previousToken2.GetPreviousToken(includeSkipped: true); if (previousToken1.Kind() == SyntaxKind.NullableKeyword && previousToken2.Kind() == SyntaxKind.HashToken) { // # nullable | // # nullable d| return true; } // # pragma warning | // # pragma warning d| return previousToken1.Kind() == SyntaxKind.WarningKeyword && previousToken2.Kind() == SyntaxKind.PragmaKeyword && previousToken3.Kind() == SyntaxKind.HashToken; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Portable/Symbols/PublicModel/MethodSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using System.Threading; using Microsoft.Cci; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class MethodSymbol : Symbol, IMethodSymbol { private readonly Symbols.MethodSymbol _underlying; private ITypeSymbol _lazyReturnType; private ImmutableArray<ITypeSymbol> _lazyTypeArguments; private ITypeSymbol _lazyReceiverType; public MethodSymbol(Symbols.MethodSymbol underlying) { Debug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; internal Symbols.MethodSymbol UnderlyingMethodSymbol => _underlying; MethodKind IMethodSymbol.MethodKind { get { switch (_underlying.MethodKind) { case MethodKind.AnonymousFunction: return MethodKind.AnonymousFunction; case MethodKind.Constructor: return MethodKind.Constructor; case MethodKind.Conversion: return MethodKind.Conversion; case MethodKind.DelegateInvoke: return MethodKind.DelegateInvoke; case MethodKind.Destructor: return MethodKind.Destructor; case MethodKind.EventAdd: return MethodKind.EventAdd; case MethodKind.EventRemove: return MethodKind.EventRemove; case MethodKind.ExplicitInterfaceImplementation: return MethodKind.ExplicitInterfaceImplementation; case MethodKind.UserDefinedOperator: return MethodKind.UserDefinedOperator; case MethodKind.BuiltinOperator: return MethodKind.BuiltinOperator; case MethodKind.Ordinary: return MethodKind.Ordinary; case MethodKind.PropertyGet: return MethodKind.PropertyGet; case MethodKind.PropertySet: return MethodKind.PropertySet; case MethodKind.ReducedExtension: return MethodKind.ReducedExtension; case MethodKind.StaticConstructor: return MethodKind.StaticConstructor; case MethodKind.LocalFunction: return MethodKind.LocalFunction; case MethodKind.FunctionPointerSignature: return MethodKind.FunctionPointerSignature; default: throw ExceptionUtilities.UnexpectedValue(_underlying.MethodKind); } } } ITypeSymbol IMethodSymbol.ReturnType { get { if (_lazyReturnType is null) { Interlocked.CompareExchange(ref _lazyReturnType, _underlying.ReturnTypeWithAnnotations.GetPublicSymbol(), null); } return _lazyReturnType; } } CodeAnalysis.NullableAnnotation IMethodSymbol.ReturnNullableAnnotation { get { return _underlying.ReturnTypeWithAnnotations.ToPublicAnnotation(); } } ImmutableArray<ITypeSymbol> IMethodSymbol.TypeArguments { get { if (_lazyTypeArguments.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeArguments, _underlying.TypeArgumentsWithAnnotations.GetPublicSymbols(), default); } return _lazyTypeArguments; } } ImmutableArray<CodeAnalysis.NullableAnnotation> IMethodSymbol.TypeArgumentNullableAnnotations => _underlying.TypeArgumentsWithAnnotations.ToPublicAnnotations(); ImmutableArray<ITypeParameterSymbol> IMethodSymbol.TypeParameters { get { return _underlying.TypeParameters.GetPublicSymbols(); } } ImmutableArray<IParameterSymbol> IMethodSymbol.Parameters { get { return _underlying.Parameters.GetPublicSymbols(); } } IMethodSymbol IMethodSymbol.ConstructedFrom { get { return _underlying.ConstructedFrom.GetPublicSymbol(); } } bool IMethodSymbol.IsReadOnly { get { return _underlying.IsEffectivelyReadOnly; } } bool IMethodSymbol.IsInitOnly { get { return _underlying.IsInitOnly; } } IMethodSymbol IMethodSymbol.OriginalDefinition { get { return _underlying.OriginalDefinition.GetPublicSymbol(); } } IMethodSymbol IMethodSymbol.OverriddenMethod { get { return _underlying.OverriddenMethod.GetPublicSymbol(); } } ITypeSymbol IMethodSymbol.ReceiverType { get { if (_lazyReceiverType is null) { Interlocked.CompareExchange(ref _lazyReceiverType, _underlying.ReceiverType?.GetITypeSymbol(_underlying.ReceiverNullableAnnotation), null); } return _lazyReceiverType; } } CodeAnalysis.NullableAnnotation IMethodSymbol.ReceiverNullableAnnotation => _underlying.ReceiverNullableAnnotation; IMethodSymbol IMethodSymbol.ReducedFrom { get { return _underlying.ReducedFrom.GetPublicSymbol(); } } ITypeSymbol IMethodSymbol.GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter) { return _underlying.GetTypeInferredDuringReduction( reducedFromTypeParameter.EnsureCSharpSymbolOrNull(nameof(reducedFromTypeParameter))). GetPublicSymbol(); } IMethodSymbol IMethodSymbol.ReduceExtensionMethod(ITypeSymbol receiverType) { return _underlying.ReduceExtensionMethod( receiverType.EnsureCSharpSymbolOrNull(nameof(receiverType)), compilation: null). GetPublicSymbol(); } ImmutableArray<IMethodSymbol> IMethodSymbol.ExplicitInterfaceImplementations { get { return _underlying.ExplicitInterfaceImplementations.GetPublicSymbols(); } } ISymbol IMethodSymbol.AssociatedSymbol { get { return _underlying.AssociatedSymbol.GetPublicSymbol(); } } bool IMethodSymbol.IsGenericMethod { get { return _underlying.IsGenericMethod; } } bool IMethodSymbol.IsAsync { get { return _underlying.IsAsync; } } bool IMethodSymbol.HidesBaseMethodsByName { get { return _underlying.HidesBaseMethodsByName; } } ImmutableArray<CustomModifier> IMethodSymbol.ReturnTypeCustomModifiers { get { return _underlying.ReturnTypeWithAnnotations.CustomModifiers; } } ImmutableArray<CustomModifier> IMethodSymbol.RefCustomModifiers { get { return _underlying.RefCustomModifiers; } } ImmutableArray<AttributeData> IMethodSymbol.GetReturnTypeAttributes() { return _underlying.GetReturnTypeAttributes().Cast<CSharpAttributeData, AttributeData>(); } SignatureCallingConvention IMethodSymbol.CallingConvention => _underlying.CallingConvention.ToSignatureConvention(); ImmutableArray<INamedTypeSymbol> IMethodSymbol.UnmanagedCallingConventionTypes => _underlying.UnmanagedCallingConventionTypes.SelectAsArray(t => t.GetPublicSymbol()); IMethodSymbol IMethodSymbol.Construct(params ITypeSymbol[] typeArguments) { return _underlying.Construct(ConstructTypeArguments(typeArguments)).GetPublicSymbol(); } IMethodSymbol IMethodSymbol.Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<CodeAnalysis.NullableAnnotation> typeArgumentNullableAnnotations) { return _underlying.Construct(ConstructTypeArguments(typeArguments, typeArgumentNullableAnnotations)).GetPublicSymbol(); } IMethodSymbol IMethodSymbol.PartialImplementationPart { get { return _underlying.PartialImplementationPart.GetPublicSymbol(); } } IMethodSymbol IMethodSymbol.PartialDefinitionPart { get { return _underlying.PartialDefinitionPart.GetPublicSymbol(); } } bool IMethodSymbol.IsPartialDefinition => _underlying.IsPartialDefinition(); INamedTypeSymbol IMethodSymbol.AssociatedAnonymousDelegate { get { return null; } } int IMethodSymbol.Arity => _underlying.Arity; bool IMethodSymbol.IsExtensionMethod => _underlying.IsExtensionMethod; System.Reflection.MethodImplAttributes IMethodSymbol.MethodImplementationFlags => _underlying.ImplementationAttributes; bool IMethodSymbol.IsVararg => _underlying.IsVararg; bool IMethodSymbol.IsCheckedBuiltin => _underlying.IsCheckedBuiltin; bool IMethodSymbol.ReturnsVoid => _underlying.ReturnsVoid; bool IMethodSymbol.ReturnsByRef => _underlying.ReturnsByRef; bool IMethodSymbol.ReturnsByRefReadonly => _underlying.ReturnsByRefReadonly; RefKind IMethodSymbol.RefKind => _underlying.RefKind; bool IMethodSymbol.IsConditional => _underlying.IsConditional; DllImportData IMethodSymbol.GetDllImportData() => _underlying.GetDllImportData(); #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitMethod(this); } protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitMethod(this); } protected override TResult Accept<TArgument, TResult>(SymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitMethod(this, argument); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using System.Threading; using Microsoft.Cci; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class MethodSymbol : Symbol, IMethodSymbol { private readonly Symbols.MethodSymbol _underlying; private ITypeSymbol _lazyReturnType; private ImmutableArray<ITypeSymbol> _lazyTypeArguments; private ITypeSymbol _lazyReceiverType; public MethodSymbol(Symbols.MethodSymbol underlying) { Debug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; internal Symbols.MethodSymbol UnderlyingMethodSymbol => _underlying; MethodKind IMethodSymbol.MethodKind { get { switch (_underlying.MethodKind) { case MethodKind.AnonymousFunction: return MethodKind.AnonymousFunction; case MethodKind.Constructor: return MethodKind.Constructor; case MethodKind.Conversion: return MethodKind.Conversion; case MethodKind.DelegateInvoke: return MethodKind.DelegateInvoke; case MethodKind.Destructor: return MethodKind.Destructor; case MethodKind.EventAdd: return MethodKind.EventAdd; case MethodKind.EventRemove: return MethodKind.EventRemove; case MethodKind.ExplicitInterfaceImplementation: return MethodKind.ExplicitInterfaceImplementation; case MethodKind.UserDefinedOperator: return MethodKind.UserDefinedOperator; case MethodKind.BuiltinOperator: return MethodKind.BuiltinOperator; case MethodKind.Ordinary: return MethodKind.Ordinary; case MethodKind.PropertyGet: return MethodKind.PropertyGet; case MethodKind.PropertySet: return MethodKind.PropertySet; case MethodKind.ReducedExtension: return MethodKind.ReducedExtension; case MethodKind.StaticConstructor: return MethodKind.StaticConstructor; case MethodKind.LocalFunction: return MethodKind.LocalFunction; case MethodKind.FunctionPointerSignature: return MethodKind.FunctionPointerSignature; default: throw ExceptionUtilities.UnexpectedValue(_underlying.MethodKind); } } } ITypeSymbol IMethodSymbol.ReturnType { get { if (_lazyReturnType is null) { Interlocked.CompareExchange(ref _lazyReturnType, _underlying.ReturnTypeWithAnnotations.GetPublicSymbol(), null); } return _lazyReturnType; } } CodeAnalysis.NullableAnnotation IMethodSymbol.ReturnNullableAnnotation { get { return _underlying.ReturnTypeWithAnnotations.ToPublicAnnotation(); } } ImmutableArray<ITypeSymbol> IMethodSymbol.TypeArguments { get { if (_lazyTypeArguments.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeArguments, _underlying.TypeArgumentsWithAnnotations.GetPublicSymbols(), default); } return _lazyTypeArguments; } } ImmutableArray<CodeAnalysis.NullableAnnotation> IMethodSymbol.TypeArgumentNullableAnnotations => _underlying.TypeArgumentsWithAnnotations.ToPublicAnnotations(); ImmutableArray<ITypeParameterSymbol> IMethodSymbol.TypeParameters { get { return _underlying.TypeParameters.GetPublicSymbols(); } } ImmutableArray<IParameterSymbol> IMethodSymbol.Parameters { get { return _underlying.Parameters.GetPublicSymbols(); } } IMethodSymbol IMethodSymbol.ConstructedFrom { get { return _underlying.ConstructedFrom.GetPublicSymbol(); } } bool IMethodSymbol.IsReadOnly { get { return _underlying.IsEffectivelyReadOnly; } } bool IMethodSymbol.IsInitOnly { get { return _underlying.IsInitOnly; } } IMethodSymbol IMethodSymbol.OriginalDefinition { get { return _underlying.OriginalDefinition.GetPublicSymbol(); } } IMethodSymbol IMethodSymbol.OverriddenMethod { get { return _underlying.OverriddenMethod.GetPublicSymbol(); } } ITypeSymbol IMethodSymbol.ReceiverType { get { if (_lazyReceiverType is null) { Interlocked.CompareExchange(ref _lazyReceiverType, _underlying.ReceiverType?.GetITypeSymbol(_underlying.ReceiverNullableAnnotation), null); } return _lazyReceiverType; } } CodeAnalysis.NullableAnnotation IMethodSymbol.ReceiverNullableAnnotation => _underlying.ReceiverNullableAnnotation; IMethodSymbol IMethodSymbol.ReducedFrom { get { return _underlying.ReducedFrom.GetPublicSymbol(); } } ITypeSymbol IMethodSymbol.GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter) { return _underlying.GetTypeInferredDuringReduction( reducedFromTypeParameter.EnsureCSharpSymbolOrNull(nameof(reducedFromTypeParameter))). GetPublicSymbol(); } IMethodSymbol IMethodSymbol.ReduceExtensionMethod(ITypeSymbol receiverType) { return _underlying.ReduceExtensionMethod( receiverType.EnsureCSharpSymbolOrNull(nameof(receiverType)), compilation: null). GetPublicSymbol(); } ImmutableArray<IMethodSymbol> IMethodSymbol.ExplicitInterfaceImplementations { get { return _underlying.ExplicitInterfaceImplementations.GetPublicSymbols(); } } ISymbol IMethodSymbol.AssociatedSymbol { get { return _underlying.AssociatedSymbol.GetPublicSymbol(); } } bool IMethodSymbol.IsGenericMethod { get { return _underlying.IsGenericMethod; } } bool IMethodSymbol.IsAsync { get { return _underlying.IsAsync; } } bool IMethodSymbol.HidesBaseMethodsByName { get { return _underlying.HidesBaseMethodsByName; } } ImmutableArray<CustomModifier> IMethodSymbol.ReturnTypeCustomModifiers { get { return _underlying.ReturnTypeWithAnnotations.CustomModifiers; } } ImmutableArray<CustomModifier> IMethodSymbol.RefCustomModifiers { get { return _underlying.RefCustomModifiers; } } ImmutableArray<AttributeData> IMethodSymbol.GetReturnTypeAttributes() { return _underlying.GetReturnTypeAttributes().Cast<CSharpAttributeData, AttributeData>(); } SignatureCallingConvention IMethodSymbol.CallingConvention => _underlying.CallingConvention.ToSignatureConvention(); ImmutableArray<INamedTypeSymbol> IMethodSymbol.UnmanagedCallingConventionTypes => _underlying.UnmanagedCallingConventionTypes.SelectAsArray(t => t.GetPublicSymbol()); IMethodSymbol IMethodSymbol.Construct(params ITypeSymbol[] typeArguments) { return _underlying.Construct(ConstructTypeArguments(typeArguments)).GetPublicSymbol(); } IMethodSymbol IMethodSymbol.Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<CodeAnalysis.NullableAnnotation> typeArgumentNullableAnnotations) { return _underlying.Construct(ConstructTypeArguments(typeArguments, typeArgumentNullableAnnotations)).GetPublicSymbol(); } IMethodSymbol IMethodSymbol.PartialImplementationPart { get { return _underlying.PartialImplementationPart.GetPublicSymbol(); } } IMethodSymbol IMethodSymbol.PartialDefinitionPart { get { return _underlying.PartialDefinitionPart.GetPublicSymbol(); } } bool IMethodSymbol.IsPartialDefinition => _underlying.IsPartialDefinition(); INamedTypeSymbol IMethodSymbol.AssociatedAnonymousDelegate { get { return null; } } int IMethodSymbol.Arity => _underlying.Arity; bool IMethodSymbol.IsExtensionMethod => _underlying.IsExtensionMethod; System.Reflection.MethodImplAttributes IMethodSymbol.MethodImplementationFlags => _underlying.ImplementationAttributes; bool IMethodSymbol.IsVararg => _underlying.IsVararg; bool IMethodSymbol.IsCheckedBuiltin => _underlying.IsCheckedBuiltin; bool IMethodSymbol.ReturnsVoid => _underlying.ReturnsVoid; bool IMethodSymbol.ReturnsByRef => _underlying.ReturnsByRef; bool IMethodSymbol.ReturnsByRefReadonly => _underlying.ReturnsByRefReadonly; RefKind IMethodSymbol.RefKind => _underlying.RefKind; bool IMethodSymbol.IsConditional => _underlying.IsConditional; DllImportData IMethodSymbol.GetDllImportData() => _underlying.GetDllImportData(); #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitMethod(this); } protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitMethod(this); } protected override TResult Accept<TArgument, TResult>(SymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitMethod(this, argument); } #endregion } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectCreation.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Diagnostics Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode ' save the object initializer away to rewrite them later on and set the initializers to nothing to not rewrite them ' two times. Dim objectInitializer = node.InitializerOpt node = node.Update(node.ConstructorOpt, node.Arguments, node.DefaultArguments, Nothing, node.Type) Dim ctor = node.ConstructorOpt Dim result As BoundExpression = node If ctor IsNot Nothing Then Dim temporaries As ImmutableArray(Of SynthesizedLocal) = Nothing Dim copyBack As ImmutableArray(Of BoundExpression) = Nothing result = node.Update(ctor, RewriteCallArguments(node.Arguments, ctor.Parameters, temporaries, copyBack, False), node.DefaultArguments, Nothing, ctor.ContainingType) If Not temporaries.IsDefault Then result = GenerateSequenceValueSideEffects(_currentMethodOrLambda, result, StaticCast(Of LocalSymbol).From(temporaries), copyBack) End If ' If a coclass was instantiated, convert the class to the interface type. If node.Type.IsInterfaceType() Then Debug.Assert(result.Type.Equals(DirectCast(node.Type, NamedTypeSymbol).CoClassType)) Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim conv As ConversionKind = Conversions.ClassifyDirectCastConversion(result.Type, node.Type, useSiteInfo) Debug.Assert(Conversions.ConversionExists(conv)) _diagnostics.Add(result, useSiteInfo) result = New BoundDirectCast(node.Syntax, result, conv, node.Type, Nothing) Else Debug.Assert(node.Type.IsSameTypeIgnoringAll(result.Type)) End If End If If objectInitializer IsNot Nothing Then Return VisitObjectCreationInitializer(objectInitializer, node, result) End If Return result End Function Public Overrides Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression) As BoundNode ' For the NoPIA feature, we need to gather the GUID from the coclass, and ' generate the following: ' DirectCast(System.Activator.CreateInstance(System.Runtime.InteropServices.Marshal.GetTypeFromCLSID(New Guid(GUID))), IPiaType) ' ' If System.Runtime.InteropServices.Marshal.GetTypeFromCLSID is not available (older framework), ' System.Type.GetTypeFromCLSID() is used to get the type for the CLSID. Dim factory As New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, node.Syntax, _compilationState, _diagnostics) Dim ctor = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Guid__ctor) Dim newGuid As BoundExpression If ctor IsNot Nothing Then newGuid = factory.[New](ctor, factory.Literal(node.GuidString)) Else newGuid = New BoundBadExpression(node.Syntax, LookupResultKind.NotCreatable, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End If Dim getTypeFromCLSID = If(factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Runtime_InteropServices_Marshal__GetTypeFromCLSID, isOptional:=True), factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Type__GetTypeFromCLSID)) Dim callGetTypeFromCLSID As BoundExpression If getTypeFromCLSID IsNot Nothing Then callGetTypeFromCLSID = factory.Call(Nothing, getTypeFromCLSID, newGuid) Else callGetTypeFromCLSID = New BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End If Dim createInstance = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Activator__CreateInstance) Dim rewrittenObjectCreation As BoundExpression If createInstance IsNot Nothing AndAlso Not createInstance.ReturnType.IsErrorType() Then Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim conversion = Conversions.ClassifyDirectCastConversion(createInstance.ReturnType, node.Type, useSiteInfo) _diagnostics.Add(node, useSiteInfo) rewrittenObjectCreation = New BoundDirectCast(node.Syntax, factory.Call(Nothing, createInstance, callGetTypeFromCLSID), conversion, node.Type) Else rewrittenObjectCreation = New BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, node.Type, hasErrors:=True) End If If node.InitializerOpt Is Nothing OrElse node.InitializerOpt.HasErrors Then Return rewrittenObjectCreation End If Return VisitObjectCreationInitializer(node.InitializerOpt, node, rewrittenObjectCreation) End Function Private Function VisitObjectCreationInitializer( objectInitializer As BoundObjectInitializerExpressionBase, objectCreationExpression As BoundExpression, rewrittenObjectCreationExpression As BoundExpression ) As BoundNode If objectInitializer.Kind = BoundKind.CollectionInitializerExpression Then Return RewriteCollectionInitializerExpression(DirectCast(objectInitializer, BoundCollectionInitializerExpression), objectCreationExpression, rewrittenObjectCreationExpression) Else Return RewriteObjectInitializerExpression(DirectCast(objectInitializer, BoundObjectInitializerExpression), objectCreationExpression, rewrittenObjectCreationExpression) End If End Function Public Overrides Function VisitNewT(node As BoundNewT) As BoundNode ' Unlike C#, "New T()" is always rewritten as "Activator.CreateInstance<T>()", ' even if T is known to be a value type or reference type. This matches Dev10 VB. If _inExpressionLambda Then ' NOTE: If we are in expression lambda, we want to keep BoundNewT ' NOTE: node, but we need to rewrite initializers if any. If node.InitializerOpt IsNot Nothing Then Return VisitObjectCreationInitializer(node.InitializerOpt, node, node) Else Return node End If End If Dim syntax = node.Syntax Dim typeParameter = DirectCast(node.Type, TypeParameterSymbol) Dim result As BoundExpression Dim method As MethodSymbol = Nothing If TryGetWellknownMember(method, WellKnownMember.System_Activator__CreateInstance_T, syntax) Then Debug.Assert(method IsNot Nothing) method = method.Construct(ImmutableArray.Create(Of TypeSymbol)(typeParameter)) result = New BoundCall(syntax, method, methodGroupOpt:=Nothing, receiverOpt:=Nothing, arguments:=ImmutableArray(Of BoundExpression).Empty, constantValueOpt:=Nothing, isLValue:=False, suppressObjectClone:=False, type:=typeParameter) Else result = New BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, typeParameter, hasErrors:=True) End If If node.InitializerOpt IsNot Nothing Then Return VisitObjectCreationInitializer(node.InitializerOpt, result, result) End If Return result End Function ''' <summary> ''' Rewrites a CollectionInitializerExpression to a list of Add calls and returns the temporary. ''' E.g. the following code: ''' Dim x As New CollectionType(param1) From {1, {2, 3}, {4, {5, 6, 7}}} ''' gets rewritten to ''' Dim temp as CollectionType ''' temp = new CollectionType(param1) ''' temp.Add(1) ''' temp.Add(2, 3) ''' temp.Add(4, {5, 6, 7}) ''' x = temp ''' where the last assignment is not part of this rewriting, because the BoundCollectionInitializerExpression ''' only represents the object creation expression with the initialization. ''' </summary> ''' <param name="node">The BoundCollectionInitializerExpression that should be rewritten.</param> ''' <returns>A bound sequence for the object creation expression containing the invocation expressions.</returns> Public Function RewriteCollectionInitializerExpression( node As BoundCollectionInitializerExpression, objectCreationExpression As BoundExpression, rewrittenObjectCreationExpression As BoundExpression ) As BoundNode Debug.Assert(node.PlaceholderOpt IsNot Nothing) Dim expressionType = node.Type Dim syntaxNode = node.Syntax Dim tempLocalSymbol As LocalSymbol Dim tempLocal As BoundLocal Dim expressions = ArrayBuilder(Of BoundExpression).GetInstance() Dim newPlaceholder As BoundWithLValueExpressionPlaceholder If _inExpressionLambda Then ' A temp is not needed for this case tempLocalSymbol = Nothing tempLocal = Nothing ' Simply replace placeholder with a copy, it will be dropped by Expression Tree rewriter. The copy is needed to ' keep the double rewrite tracking happy. newPlaceholder = New BoundWithLValueExpressionPlaceholder(node.PlaceholderOpt.Syntax, node.PlaceholderOpt.Type) AddPlaceholderReplacement(node.PlaceholderOpt, newPlaceholder) Else ' Create a temp symbol ' Dim temp as CollectionType ' Create assignment for the rewritten object ' creation expression to the temp ' temp = new CollectionType(param1) tempLocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, expressionType, SynthesizedLocalKind.LoweringTemp) tempLocal = New BoundLocal(syntaxNode, tempLocalSymbol, expressionType) Dim temporaryAssignment = New BoundAssignmentOperator(syntaxNode, tempLocal, GenerateObjectCloneIfNeeded(objectCreationExpression, rewrittenObjectCreationExpression), suppressObjectClone:=True, type:=expressionType) expressions.Add(temporaryAssignment) newPlaceholder = Nothing AddPlaceholderReplacement(node.PlaceholderOpt, tempLocal) End If Dim initializerCount = node.Initializers.Length ' rewrite the invocation expressions and add them to the expression of the sequence ' temp.Add(...) For initializerIndex = 0 To initializerCount - 1 ' NOTE: if the method Add(...) is omitted we build a local which ' seems to be redundant, this will optimized out later ' by stack scheduler Dim initializer As BoundExpression = node.Initializers(initializerIndex) If Not IsOmittedBoundCall(initializer) Then expressions.Add(VisitExpressionNode(initializer)) End If Next RemovePlaceholderReplacement(node.PlaceholderOpt) If _inExpressionLambda Then Debug.Assert(tempLocalSymbol Is Nothing) Debug.Assert(tempLocal Is Nothing) ' NOTE: if inside expression lambda we rewrite the collection initializer ' NOTE: node and attach it back to object creation expression, it will be ' NOTE: rewritten later in ExpressionLambdaRewriter ' Rewrite object creation Return ReplaceObjectOrCollectionInitializer( rewrittenObjectCreationExpression, node.Update(newPlaceholder, expressions.ToImmutableAndFree(), node.Type)) Else Debug.Assert(tempLocalSymbol IsNot Nothing) Debug.Assert(tempLocal IsNot Nothing) Return New BoundSequence(syntaxNode, ImmutableArray.Create(Of LocalSymbol)(tempLocalSymbol), expressions.ToImmutableAndFree(), tempLocal.MakeRValue(), expressionType) End If End Function ''' <summary> ''' Rewrites a ObjectInitializerExpression to either a statement list (in case the there is no temporary used) or a bound ''' sequence expression (in case there is a temporary used). The information whether to use a temporary or not is ''' stored in the bound object member initializer node itself. ''' ''' E.g. the following code: ''' Dim x = New RefTypeName(param1) With {.FieldName1 = 23, .FieldName2 = .FieldName3, .FieldName4 = x.FieldName1} ''' gets rewritten to ''' Dim temp as RefTypeName ''' temp = new RefTypeName(param1) ''' temp.FieldName1 = 23 ''' temp.FieldName2 = temp.FieldName3 ''' temp.FieldName4 = x.FieldName1 ''' x = temp ''' where the last assignment is not part of this rewriting, because the BoundObjectInitializerExpression ''' only represents the object creation expression with the initialization. ''' ''' In a case where no temporary is used the following code: ''' Dim x As New ValueTypeName(param1) With {.FieldName1 = 23, .FieldName2 = .FieldName3, .FieldName4 = x.FieldName1} ''' gets rewritten to ''' x = new ValueTypeName(param1) ''' x.FieldName1 = 23 ''' x.FieldName2 = x.FieldName3 ''' x.FieldName4 = x.FieldName1 ''' </summary> ''' <param name="node">The BoundObjectInitializerExpression that should be rewritten.</param> ''' <returns>A bound sequence for the object creation expression containing the invocation expressions, or a ''' bound statement list if no temporary should be used.</returns> Public Function RewriteObjectInitializerExpression( node As BoundObjectInitializerExpression, objectCreationExpression As BoundExpression, rewrittenObjectCreationExpression As BoundExpression ) As BoundNode Dim targetObjectReference As BoundExpression Dim expressionType = node.Type Dim initializerCount = node.Initializers.Length Dim syntaxNode = node.Syntax Dim sequenceType As TypeSymbol Dim sequenceTemporaries As ImmutableArray(Of LocalSymbol) Dim sequenceValueExpression As BoundExpression Debug.Assert(node.PlaceholderOpt IsNot Nothing) ' NOTE: If we are in an expression lambda not all object initializers are allowed, essentially ' NOTE: everything requiring temp local creation is disabled; this rule is not applicable to ' NOTE: locals that are created and ONLY used on left-hand-side of initializer assignments, ' NOTE: ExpressionLambdaRewriter will get rid of them ' NOTE: In order ExpressionLambdaRewriter to be able to detect such locals being used on the ' NOTE: *right* side of initializer assignments we rewrite node.PlaceholderOpt into itself If node.CreateTemporaryLocalForInitialization Then ' create temporary ' Dim temp as RefTypeName Dim tempLocalSymbol As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, expressionType, SynthesizedLocalKind.LoweringTemp) sequenceType = expressionType sequenceTemporaries = ImmutableArray.Create(Of LocalSymbol)(tempLocalSymbol) targetObjectReference = If(_inExpressionLambda, DirectCast(node.PlaceholderOpt, BoundExpression), New BoundLocal(syntaxNode, tempLocalSymbol, expressionType)) sequenceValueExpression = targetObjectReference.MakeRValue() AddPlaceholderReplacement(node.PlaceholderOpt, targetObjectReference) Else ' Get the receiver for the current initialized variable in case of an "AsNew" declaration ' this is the only case where there might be no temporary needed. ' The replacement for this placeholder was added in VisitAsNewLocalDeclarations. targetObjectReference = PlaceholderReplacement(node.PlaceholderOpt) sequenceType = GetSpecialType(SpecialType.System_Void) sequenceTemporaries = ImmutableArray(Of LocalSymbol).Empty sequenceValueExpression = Nothing End If Dim sequenceExpressions(initializerCount) As BoundExpression ' create assignment for object creation expression to temporary or variable declaration ' x = new TypeName(...) ' or ' temp = new TypeName(...) sequenceExpressions(0) = New BoundAssignmentOperator(syntaxNode, targetObjectReference, GenerateObjectCloneIfNeeded(objectCreationExpression, rewrittenObjectCreationExpression), suppressObjectClone:=True, type:=expressionType) ' rewrite the assignment expressions and add them to the statement list ' x.FieldName = value expression ' or ' temp.FieldName = value expression For initializerIndex = 0 To initializerCount - 1 If _inExpressionLambda Then ' NOTE: Inside expression lambda we rewrite only right-hand-side of the assignments, left part ' NOTE: will be kept unchanged to make sure we got proper symbol out of it Dim assignment = DirectCast(node.Initializers(initializerIndex), BoundAssignmentOperator) Debug.Assert(assignment.LeftOnTheRightOpt Is Nothing) sequenceExpressions(initializerIndex + 1) = assignment.Update(assignment.Left, assignment.LeftOnTheRightOpt, VisitExpressionNode(assignment.Right), True, assignment.Type) Else sequenceExpressions(initializerIndex + 1) = VisitExpressionNode(node.Initializers(initializerIndex)) End If Next If node.CreateTemporaryLocalForInitialization Then RemovePlaceholderReplacement(node.PlaceholderOpt) End If If _inExpressionLambda Then ' when converting object initializer inside expression lambdas we want to keep ' object initializer in object creation expression; we just store visited initializers ' back to the original object initializer and update the original object creation expression ' create new initializers Dim newInitializers(initializerCount - 1) As BoundExpression Dim errors As Boolean = False For index = 0 To initializerCount - 1 newInitializers(index) = sequenceExpressions(index + 1) Next ' Rewrite object creation Return ReplaceObjectOrCollectionInitializer( rewrittenObjectCreationExpression, node.Update(node.CreateTemporaryLocalForInitialization, node.PlaceholderOpt, newInitializers.AsImmutableOrNull(), node.Type)) End If Return New BoundSequence(syntaxNode, sequenceTemporaries, sequenceExpressions.AsImmutableOrNull, sequenceValueExpression, sequenceType) End Function Private Function ReplaceObjectOrCollectionInitializer(rewrittenObjectCreationExpression As BoundExpression, rewrittenInitializer As BoundObjectInitializerExpressionBase) As BoundExpression Select Case rewrittenObjectCreationExpression.Kind Case BoundKind.ObjectCreationExpression Dim objCreation = DirectCast(rewrittenObjectCreationExpression, BoundObjectCreationExpression) Return objCreation.Update(objCreation.ConstructorOpt, objCreation.Arguments, objCreation.DefaultArguments, rewrittenInitializer, objCreation.Type) Case BoundKind.NewT Dim newT = DirectCast(rewrittenObjectCreationExpression, BoundNewT) Return newT.Update(rewrittenInitializer, newT.Type) Case BoundKind.Sequence ' NOTE: is rewrittenObjectCreationExpression is not an object creation expression, it ' NOTE: was probably wrapped with sequence which means that this case is not supported ' NOTE: inside expression lambdas. Dim sequence = DirectCast(rewrittenObjectCreationExpression, BoundSequence) Debug.Assert(sequence.ValueOpt IsNot Nothing AndAlso sequence.ValueOpt.Kind = BoundKind.ObjectCreationExpression) Return sequence.Update(sequence.Locals, sequence.SideEffects, ReplaceObjectOrCollectionInitializer(sequence.ValueOpt, rewrittenInitializer), sequence.Type) Case Else Throw ExceptionUtilities.UnexpectedValue(rewrittenObjectCreationExpression.Kind) End Select End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Diagnostics Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode ' save the object initializer away to rewrite them later on and set the initializers to nothing to not rewrite them ' two times. Dim objectInitializer = node.InitializerOpt node = node.Update(node.ConstructorOpt, node.Arguments, node.DefaultArguments, Nothing, node.Type) Dim ctor = node.ConstructorOpt Dim result As BoundExpression = node If ctor IsNot Nothing Then Dim temporaries As ImmutableArray(Of SynthesizedLocal) = Nothing Dim copyBack As ImmutableArray(Of BoundExpression) = Nothing result = node.Update(ctor, RewriteCallArguments(node.Arguments, ctor.Parameters, temporaries, copyBack, False), node.DefaultArguments, Nothing, ctor.ContainingType) If Not temporaries.IsDefault Then result = GenerateSequenceValueSideEffects(_currentMethodOrLambda, result, StaticCast(Of LocalSymbol).From(temporaries), copyBack) End If ' If a coclass was instantiated, convert the class to the interface type. If node.Type.IsInterfaceType() Then Debug.Assert(result.Type.Equals(DirectCast(node.Type, NamedTypeSymbol).CoClassType)) Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim conv As ConversionKind = Conversions.ClassifyDirectCastConversion(result.Type, node.Type, useSiteInfo) Debug.Assert(Conversions.ConversionExists(conv)) _diagnostics.Add(result, useSiteInfo) result = New BoundDirectCast(node.Syntax, result, conv, node.Type, Nothing) Else Debug.Assert(node.Type.IsSameTypeIgnoringAll(result.Type)) End If End If If objectInitializer IsNot Nothing Then Return VisitObjectCreationInitializer(objectInitializer, node, result) End If Return result End Function Public Overrides Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression) As BoundNode ' For the NoPIA feature, we need to gather the GUID from the coclass, and ' generate the following: ' DirectCast(System.Activator.CreateInstance(System.Runtime.InteropServices.Marshal.GetTypeFromCLSID(New Guid(GUID))), IPiaType) ' ' If System.Runtime.InteropServices.Marshal.GetTypeFromCLSID is not available (older framework), ' System.Type.GetTypeFromCLSID() is used to get the type for the CLSID. Dim factory As New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, node.Syntax, _compilationState, _diagnostics) Dim ctor = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Guid__ctor) Dim newGuid As BoundExpression If ctor IsNot Nothing Then newGuid = factory.[New](ctor, factory.Literal(node.GuidString)) Else newGuid = New BoundBadExpression(node.Syntax, LookupResultKind.NotCreatable, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End If Dim getTypeFromCLSID = If(factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Runtime_InteropServices_Marshal__GetTypeFromCLSID, isOptional:=True), factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Type__GetTypeFromCLSID)) Dim callGetTypeFromCLSID As BoundExpression If getTypeFromCLSID IsNot Nothing Then callGetTypeFromCLSID = factory.Call(Nothing, getTypeFromCLSID, newGuid) Else callGetTypeFromCLSID = New BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End If Dim createInstance = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Activator__CreateInstance) Dim rewrittenObjectCreation As BoundExpression If createInstance IsNot Nothing AndAlso Not createInstance.ReturnType.IsErrorType() Then Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim conversion = Conversions.ClassifyDirectCastConversion(createInstance.ReturnType, node.Type, useSiteInfo) _diagnostics.Add(node, useSiteInfo) rewrittenObjectCreation = New BoundDirectCast(node.Syntax, factory.Call(Nothing, createInstance, callGetTypeFromCLSID), conversion, node.Type) Else rewrittenObjectCreation = New BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, node.Type, hasErrors:=True) End If If node.InitializerOpt Is Nothing OrElse node.InitializerOpt.HasErrors Then Return rewrittenObjectCreation End If Return VisitObjectCreationInitializer(node.InitializerOpt, node, rewrittenObjectCreation) End Function Private Function VisitObjectCreationInitializer( objectInitializer As BoundObjectInitializerExpressionBase, objectCreationExpression As BoundExpression, rewrittenObjectCreationExpression As BoundExpression ) As BoundNode If objectInitializer.Kind = BoundKind.CollectionInitializerExpression Then Return RewriteCollectionInitializerExpression(DirectCast(objectInitializer, BoundCollectionInitializerExpression), objectCreationExpression, rewrittenObjectCreationExpression) Else Return RewriteObjectInitializerExpression(DirectCast(objectInitializer, BoundObjectInitializerExpression), objectCreationExpression, rewrittenObjectCreationExpression) End If End Function Public Overrides Function VisitNewT(node As BoundNewT) As BoundNode ' Unlike C#, "New T()" is always rewritten as "Activator.CreateInstance<T>()", ' even if T is known to be a value type or reference type. This matches Dev10 VB. If _inExpressionLambda Then ' NOTE: If we are in expression lambda, we want to keep BoundNewT ' NOTE: node, but we need to rewrite initializers if any. If node.InitializerOpt IsNot Nothing Then Return VisitObjectCreationInitializer(node.InitializerOpt, node, node) Else Return node End If End If Dim syntax = node.Syntax Dim typeParameter = DirectCast(node.Type, TypeParameterSymbol) Dim result As BoundExpression Dim method As MethodSymbol = Nothing If TryGetWellknownMember(method, WellKnownMember.System_Activator__CreateInstance_T, syntax) Then Debug.Assert(method IsNot Nothing) method = method.Construct(ImmutableArray.Create(Of TypeSymbol)(typeParameter)) result = New BoundCall(syntax, method, methodGroupOpt:=Nothing, receiverOpt:=Nothing, arguments:=ImmutableArray(Of BoundExpression).Empty, constantValueOpt:=Nothing, isLValue:=False, suppressObjectClone:=False, type:=typeParameter) Else result = New BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, typeParameter, hasErrors:=True) End If If node.InitializerOpt IsNot Nothing Then Return VisitObjectCreationInitializer(node.InitializerOpt, result, result) End If Return result End Function ''' <summary> ''' Rewrites a CollectionInitializerExpression to a list of Add calls and returns the temporary. ''' E.g. the following code: ''' Dim x As New CollectionType(param1) From {1, {2, 3}, {4, {5, 6, 7}}} ''' gets rewritten to ''' Dim temp as CollectionType ''' temp = new CollectionType(param1) ''' temp.Add(1) ''' temp.Add(2, 3) ''' temp.Add(4, {5, 6, 7}) ''' x = temp ''' where the last assignment is not part of this rewriting, because the BoundCollectionInitializerExpression ''' only represents the object creation expression with the initialization. ''' </summary> ''' <param name="node">The BoundCollectionInitializerExpression that should be rewritten.</param> ''' <returns>A bound sequence for the object creation expression containing the invocation expressions.</returns> Public Function RewriteCollectionInitializerExpression( node As BoundCollectionInitializerExpression, objectCreationExpression As BoundExpression, rewrittenObjectCreationExpression As BoundExpression ) As BoundNode Debug.Assert(node.PlaceholderOpt IsNot Nothing) Dim expressionType = node.Type Dim syntaxNode = node.Syntax Dim tempLocalSymbol As LocalSymbol Dim tempLocal As BoundLocal Dim expressions = ArrayBuilder(Of BoundExpression).GetInstance() Dim newPlaceholder As BoundWithLValueExpressionPlaceholder If _inExpressionLambda Then ' A temp is not needed for this case tempLocalSymbol = Nothing tempLocal = Nothing ' Simply replace placeholder with a copy, it will be dropped by Expression Tree rewriter. The copy is needed to ' keep the double rewrite tracking happy. newPlaceholder = New BoundWithLValueExpressionPlaceholder(node.PlaceholderOpt.Syntax, node.PlaceholderOpt.Type) AddPlaceholderReplacement(node.PlaceholderOpt, newPlaceholder) Else ' Create a temp symbol ' Dim temp as CollectionType ' Create assignment for the rewritten object ' creation expression to the temp ' temp = new CollectionType(param1) tempLocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, expressionType, SynthesizedLocalKind.LoweringTemp) tempLocal = New BoundLocal(syntaxNode, tempLocalSymbol, expressionType) Dim temporaryAssignment = New BoundAssignmentOperator(syntaxNode, tempLocal, GenerateObjectCloneIfNeeded(objectCreationExpression, rewrittenObjectCreationExpression), suppressObjectClone:=True, type:=expressionType) expressions.Add(temporaryAssignment) newPlaceholder = Nothing AddPlaceholderReplacement(node.PlaceholderOpt, tempLocal) End If Dim initializerCount = node.Initializers.Length ' rewrite the invocation expressions and add them to the expression of the sequence ' temp.Add(...) For initializerIndex = 0 To initializerCount - 1 ' NOTE: if the method Add(...) is omitted we build a local which ' seems to be redundant, this will optimized out later ' by stack scheduler Dim initializer As BoundExpression = node.Initializers(initializerIndex) If Not IsOmittedBoundCall(initializer) Then expressions.Add(VisitExpressionNode(initializer)) End If Next RemovePlaceholderReplacement(node.PlaceholderOpt) If _inExpressionLambda Then Debug.Assert(tempLocalSymbol Is Nothing) Debug.Assert(tempLocal Is Nothing) ' NOTE: if inside expression lambda we rewrite the collection initializer ' NOTE: node and attach it back to object creation expression, it will be ' NOTE: rewritten later in ExpressionLambdaRewriter ' Rewrite object creation Return ReplaceObjectOrCollectionInitializer( rewrittenObjectCreationExpression, node.Update(newPlaceholder, expressions.ToImmutableAndFree(), node.Type)) Else Debug.Assert(tempLocalSymbol IsNot Nothing) Debug.Assert(tempLocal IsNot Nothing) Return New BoundSequence(syntaxNode, ImmutableArray.Create(Of LocalSymbol)(tempLocalSymbol), expressions.ToImmutableAndFree(), tempLocal.MakeRValue(), expressionType) End If End Function ''' <summary> ''' Rewrites a ObjectInitializerExpression to either a statement list (in case the there is no temporary used) or a bound ''' sequence expression (in case there is a temporary used). The information whether to use a temporary or not is ''' stored in the bound object member initializer node itself. ''' ''' E.g. the following code: ''' Dim x = New RefTypeName(param1) With {.FieldName1 = 23, .FieldName2 = .FieldName3, .FieldName4 = x.FieldName1} ''' gets rewritten to ''' Dim temp as RefTypeName ''' temp = new RefTypeName(param1) ''' temp.FieldName1 = 23 ''' temp.FieldName2 = temp.FieldName3 ''' temp.FieldName4 = x.FieldName1 ''' x = temp ''' where the last assignment is not part of this rewriting, because the BoundObjectInitializerExpression ''' only represents the object creation expression with the initialization. ''' ''' In a case where no temporary is used the following code: ''' Dim x As New ValueTypeName(param1) With {.FieldName1 = 23, .FieldName2 = .FieldName3, .FieldName4 = x.FieldName1} ''' gets rewritten to ''' x = new ValueTypeName(param1) ''' x.FieldName1 = 23 ''' x.FieldName2 = x.FieldName3 ''' x.FieldName4 = x.FieldName1 ''' </summary> ''' <param name="node">The BoundObjectInitializerExpression that should be rewritten.</param> ''' <returns>A bound sequence for the object creation expression containing the invocation expressions, or a ''' bound statement list if no temporary should be used.</returns> Public Function RewriteObjectInitializerExpression( node As BoundObjectInitializerExpression, objectCreationExpression As BoundExpression, rewrittenObjectCreationExpression As BoundExpression ) As BoundNode Dim targetObjectReference As BoundExpression Dim expressionType = node.Type Dim initializerCount = node.Initializers.Length Dim syntaxNode = node.Syntax Dim sequenceType As TypeSymbol Dim sequenceTemporaries As ImmutableArray(Of LocalSymbol) Dim sequenceValueExpression As BoundExpression Debug.Assert(node.PlaceholderOpt IsNot Nothing) ' NOTE: If we are in an expression lambda not all object initializers are allowed, essentially ' NOTE: everything requiring temp local creation is disabled; this rule is not applicable to ' NOTE: locals that are created and ONLY used on left-hand-side of initializer assignments, ' NOTE: ExpressionLambdaRewriter will get rid of them ' NOTE: In order ExpressionLambdaRewriter to be able to detect such locals being used on the ' NOTE: *right* side of initializer assignments we rewrite node.PlaceholderOpt into itself If node.CreateTemporaryLocalForInitialization Then ' create temporary ' Dim temp as RefTypeName Dim tempLocalSymbol As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, expressionType, SynthesizedLocalKind.LoweringTemp) sequenceType = expressionType sequenceTemporaries = ImmutableArray.Create(Of LocalSymbol)(tempLocalSymbol) targetObjectReference = If(_inExpressionLambda, DirectCast(node.PlaceholderOpt, BoundExpression), New BoundLocal(syntaxNode, tempLocalSymbol, expressionType)) sequenceValueExpression = targetObjectReference.MakeRValue() AddPlaceholderReplacement(node.PlaceholderOpt, targetObjectReference) Else ' Get the receiver for the current initialized variable in case of an "AsNew" declaration ' this is the only case where there might be no temporary needed. ' The replacement for this placeholder was added in VisitAsNewLocalDeclarations. targetObjectReference = PlaceholderReplacement(node.PlaceholderOpt) sequenceType = GetSpecialType(SpecialType.System_Void) sequenceTemporaries = ImmutableArray(Of LocalSymbol).Empty sequenceValueExpression = Nothing End If Dim sequenceExpressions(initializerCount) As BoundExpression ' create assignment for object creation expression to temporary or variable declaration ' x = new TypeName(...) ' or ' temp = new TypeName(...) sequenceExpressions(0) = New BoundAssignmentOperator(syntaxNode, targetObjectReference, GenerateObjectCloneIfNeeded(objectCreationExpression, rewrittenObjectCreationExpression), suppressObjectClone:=True, type:=expressionType) ' rewrite the assignment expressions and add them to the statement list ' x.FieldName = value expression ' or ' temp.FieldName = value expression For initializerIndex = 0 To initializerCount - 1 If _inExpressionLambda Then ' NOTE: Inside expression lambda we rewrite only right-hand-side of the assignments, left part ' NOTE: will be kept unchanged to make sure we got proper symbol out of it Dim assignment = DirectCast(node.Initializers(initializerIndex), BoundAssignmentOperator) Debug.Assert(assignment.LeftOnTheRightOpt Is Nothing) sequenceExpressions(initializerIndex + 1) = assignment.Update(assignment.Left, assignment.LeftOnTheRightOpt, VisitExpressionNode(assignment.Right), True, assignment.Type) Else sequenceExpressions(initializerIndex + 1) = VisitExpressionNode(node.Initializers(initializerIndex)) End If Next If node.CreateTemporaryLocalForInitialization Then RemovePlaceholderReplacement(node.PlaceholderOpt) End If If _inExpressionLambda Then ' when converting object initializer inside expression lambdas we want to keep ' object initializer in object creation expression; we just store visited initializers ' back to the original object initializer and update the original object creation expression ' create new initializers Dim newInitializers(initializerCount - 1) As BoundExpression Dim errors As Boolean = False For index = 0 To initializerCount - 1 newInitializers(index) = sequenceExpressions(index + 1) Next ' Rewrite object creation Return ReplaceObjectOrCollectionInitializer( rewrittenObjectCreationExpression, node.Update(node.CreateTemporaryLocalForInitialization, node.PlaceholderOpt, newInitializers.AsImmutableOrNull(), node.Type)) End If Return New BoundSequence(syntaxNode, sequenceTemporaries, sequenceExpressions.AsImmutableOrNull, sequenceValueExpression, sequenceType) End Function Private Function ReplaceObjectOrCollectionInitializer(rewrittenObjectCreationExpression As BoundExpression, rewrittenInitializer As BoundObjectInitializerExpressionBase) As BoundExpression Select Case rewrittenObjectCreationExpression.Kind Case BoundKind.ObjectCreationExpression Dim objCreation = DirectCast(rewrittenObjectCreationExpression, BoundObjectCreationExpression) Return objCreation.Update(objCreation.ConstructorOpt, objCreation.Arguments, objCreation.DefaultArguments, rewrittenInitializer, objCreation.Type) Case BoundKind.NewT Dim newT = DirectCast(rewrittenObjectCreationExpression, BoundNewT) Return newT.Update(rewrittenInitializer, newT.Type) Case BoundKind.Sequence ' NOTE: is rewrittenObjectCreationExpression is not an object creation expression, it ' NOTE: was probably wrapped with sequence which means that this case is not supported ' NOTE: inside expression lambdas. Dim sequence = DirectCast(rewrittenObjectCreationExpression, BoundSequence) Debug.Assert(sequence.ValueOpt IsNot Nothing AndAlso sequence.ValueOpt.Kind = BoundKind.ObjectCreationExpression) Return sequence.Update(sequence.Locals, sequence.SideEffects, ReplaceObjectOrCollectionInitializer(sequence.ValueOpt, rewrittenInitializer), sequence.Type) Case Else Throw ExceptionUtilities.UnexpectedValue(rewrittenObjectCreationExpression.Kind) End Select End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/SymbolDisplay/SymbolDisplayGenericsOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies the options for how generics are displayed in the description of a symbol. /// </summary> [Flags] public enum SymbolDisplayGenericsOptions { /// <summary> /// Omits the type parameter list entirely. /// </summary> None = 0, /// <summary> /// Includes the type parameters. /// For example, "Goo&lt;T&gt;" in C# or "Goo(Of T)" in Visual Basic. /// </summary> IncludeTypeParameters = 1 << 0, /// <summary> /// Includes type parameters and constraints. /// For example, "where T : new()" in C# or "Of T as New" in Visual Basic. /// </summary> IncludeTypeConstraints = 1 << 1, /// <summary> /// Includes <c>in</c> or <c>out</c> keywords before variant type parameters. /// For example, "Goo&lt;out T&gt;" in C# or (Goo Of Out T" in Visual Basic. /// </summary> IncludeVariance = 1 << 2, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies the options for how generics are displayed in the description of a symbol. /// </summary> [Flags] public enum SymbolDisplayGenericsOptions { /// <summary> /// Omits the type parameter list entirely. /// </summary> None = 0, /// <summary> /// Includes the type parameters. /// For example, "Goo&lt;T&gt;" in C# or "Goo(Of T)" in Visual Basic. /// </summary> IncludeTypeParameters = 1 << 0, /// <summary> /// Includes type parameters and constraints. /// For example, "where T : new()" in C# or "Of T as New" in Visual Basic. /// </summary> IncludeTypeConstraints = 1 << 1, /// <summary> /// Includes <c>in</c> or <c>out</c> keywords before variant type parameters. /// For example, "Goo&lt;out T&gt;" in C# or (Goo Of Out T" in Visual Basic. /// </summary> IncludeVariance = 1 << 2, } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/Core/Portable/Diagnostics/LiveDiagnosticUpdateArgsId.cs
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal class LiveDiagnosticUpdateArgsId : AnalyzerUpdateArgsId { private readonly string _analyzerPackageName; public readonly object ProjectOrDocumentId; public readonly AnalysisKind Kind; public LiveDiagnosticUpdateArgsId(DiagnosticAnalyzer analyzer, object projectOrDocumentId, AnalysisKind kind, string analyzerPackageName) : base(analyzer) { Contract.ThrowIfNull(projectOrDocumentId); ProjectOrDocumentId = projectOrDocumentId; Kind = kind; _analyzerPackageName = analyzerPackageName; } public override string BuildTool => _analyzerPackageName; public override bool Equals(object? obj) { if (obj is not LiveDiagnosticUpdateArgsId other) { return false; } return Kind == other.Kind && Equals(ProjectOrDocumentId, other.ProjectOrDocumentId) && base.Equals(obj); } public override int GetHashCode() => Hash.Combine(ProjectOrDocumentId, Hash.Combine((int)Kind, base.GetHashCode())); } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal class LiveDiagnosticUpdateArgsId : AnalyzerUpdateArgsId { private readonly string _analyzerPackageName; public readonly object ProjectOrDocumentId; public readonly AnalysisKind Kind; public LiveDiagnosticUpdateArgsId(DiagnosticAnalyzer analyzer, object projectOrDocumentId, AnalysisKind kind, string analyzerPackageName) : base(analyzer) { Contract.ThrowIfNull(projectOrDocumentId); ProjectOrDocumentId = projectOrDocumentId; Kind = kind; _analyzerPackageName = analyzerPackageName; } public override string BuildTool => _analyzerPackageName; public override bool Equals(object? obj) { if (obj is not LiveDiagnosticUpdateArgsId other) { return false; } return Kind == other.Kind && Equals(ProjectOrDocumentId, other.ProjectOrDocumentId) && base.Equals(obj); } public override int GetHashCode() => Hash.Combine(ProjectOrDocumentId, Hash.Combine((int)Kind, base.GetHashCode())); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/Core/Portable/GenerateMember/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.MethodSignatureInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 Microsoft.CodeAnalysis.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember { internal partial class AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> { protected class MethodSignatureInfo : SignatureInfo { private readonly IMethodSymbol _methodSymbol; public MethodSignatureInfo( SemanticDocument document, State state, IMethodSymbol methodSymbol) : base(document, state) { _methodSymbol = methodSymbol; } protected override ITypeSymbol DetermineReturnTypeWorker(CancellationToken cancellationToken) => _methodSymbol.ReturnType; protected override RefKind DetermineRefKind(CancellationToken cancellationToken) => _methodSymbol.RefKind; protected override ImmutableArray<ITypeParameterSymbol> DetermineTypeParametersWorker(CancellationToken cancellationToken) => _methodSymbol.TypeParameters; protected override ImmutableArray<RefKind> DetermineParameterModifiers(CancellationToken cancellationToken) => _methodSymbol.Parameters.SelectAsArray(p => p.RefKind); protected override ImmutableArray<bool> DetermineParameterOptionality(CancellationToken cancellationToken) => _methodSymbol.Parameters.SelectAsArray(p => p.IsOptional); protected override ImmutableArray<ITypeSymbol> DetermineParameterTypes(CancellationToken cancellationToken) => _methodSymbol.Parameters.SelectAsArray(p => p.Type); protected override ImmutableArray<ParameterName> DetermineParameterNames(CancellationToken cancellationToken) => _methodSymbol.Parameters.SelectAsArray(p => new ParameterName(p.Name, isFixed: true)); protected override ImmutableArray<ITypeSymbol> DetermineTypeArguments(CancellationToken cancellationToken) => ImmutableArray<ITypeSymbol>.Empty; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember { internal partial class AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> { protected class MethodSignatureInfo : SignatureInfo { private readonly IMethodSymbol _methodSymbol; public MethodSignatureInfo( SemanticDocument document, State state, IMethodSymbol methodSymbol) : base(document, state) { _methodSymbol = methodSymbol; } protected override ITypeSymbol DetermineReturnTypeWorker(CancellationToken cancellationToken) => _methodSymbol.ReturnType; protected override RefKind DetermineRefKind(CancellationToken cancellationToken) => _methodSymbol.RefKind; protected override ImmutableArray<ITypeParameterSymbol> DetermineTypeParametersWorker(CancellationToken cancellationToken) => _methodSymbol.TypeParameters; protected override ImmutableArray<RefKind> DetermineParameterModifiers(CancellationToken cancellationToken) => _methodSymbol.Parameters.SelectAsArray(p => p.RefKind); protected override ImmutableArray<bool> DetermineParameterOptionality(CancellationToken cancellationToken) => _methodSymbol.Parameters.SelectAsArray(p => p.IsOptional); protected override ImmutableArray<ITypeSymbol> DetermineParameterTypes(CancellationToken cancellationToken) => _methodSymbol.Parameters.SelectAsArray(p => p.Type); protected override ImmutableArray<ParameterName> DetermineParameterNames(CancellationToken cancellationToken) => _methodSymbol.Parameters.SelectAsArray(p => new ParameterName(p.Name, isFixed: true)); protected override ImmutableArray<ITypeSymbol> DetermineTypeArguments(CancellationToken cancellationToken) => ImmutableArray<ITypeSymbol>.Empty; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Utilities/TokenComparer.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities Friend Class TokenComparer Implements IComparer(Of SyntaxToken) Private Const s_systemNamespace = "System" Public Shared ReadOnly NormalInstance As TokenComparer = New TokenComparer(specialCaseSystem:=False) Public Shared ReadOnly SystemFirstInstance As TokenComparer = New TokenComparer(specialCaseSystem:=True) Private ReadOnly _specialCaseSystem As Boolean Private Sub New(specialCaseSystem As Boolean) Me._specialCaseSystem = specialCaseSystem End Sub Public Function Compare(token1 As SyntaxToken, token2 As SyntaxToken) As Integer Implements IComparer(Of SyntaxToken).Compare If _specialCaseSystem AndAlso token1.GetPreviousToken().Kind = SyntaxKind.ImportsKeyword AndAlso token2.GetPreviousToken().Kind = SyntaxKind.ImportsKeyword Then Dim token1IsSystem = IsSystem(token1.ToString()) Dim token2IsSystem = IsSystem(token2.ToString()) If token1IsSystem AndAlso Not token2IsSystem Then Return -1 ElseIf Not token1IsSystem And token2IsSystem Then Return 1 End If End If Return CompareWorker(token1, token2) End Function Private Shared Function IsSystem(s As String) As Boolean Return s = s_systemNamespace End Function Private Shared Function CompareWorker(x As SyntaxToken, y As SyntaxToken) As Integer ' By using 'ValueText' we get the value that is normalized. i.e. ' [class] will be 'class', and unicode escapes will be converted ' to actual unicode. This allows sorting to work properly across ' tokens that have different source representations, but which ' mean the same thing. Dim string1 = x.GetIdentifierText() Dim string2 = y.GetIdentifierText() ' First check in a case insensitive manner. This will put ' everything that starts with an 'a' or 'A' above everything ' that starts with a 'b' or 'B'. Dim value = CultureInfo.InvariantCulture.CompareInfo.Compare(string1, string2, CompareOptions.IgnoreCase Or CompareOptions.IgnoreNonSpace Or CompareOptions.IgnoreWidth) If (value <> 0) Then Return value End If ' Now, once we've grouped such that 'a' words and 'A' words are ' together, sort such that 'a' words come before 'A' words. Return CultureInfo.InvariantCulture.CompareInfo.Compare(string1, string2, CompareOptions.IgnoreNonSpace Or CompareOptions.IgnoreWidth) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities Friend Class TokenComparer Implements IComparer(Of SyntaxToken) Private Const s_systemNamespace = "System" Public Shared ReadOnly NormalInstance As TokenComparer = New TokenComparer(specialCaseSystem:=False) Public Shared ReadOnly SystemFirstInstance As TokenComparer = New TokenComparer(specialCaseSystem:=True) Private ReadOnly _specialCaseSystem As Boolean Private Sub New(specialCaseSystem As Boolean) Me._specialCaseSystem = specialCaseSystem End Sub Public Function Compare(token1 As SyntaxToken, token2 As SyntaxToken) As Integer Implements IComparer(Of SyntaxToken).Compare If _specialCaseSystem AndAlso token1.GetPreviousToken().Kind = SyntaxKind.ImportsKeyword AndAlso token2.GetPreviousToken().Kind = SyntaxKind.ImportsKeyword Then Dim token1IsSystem = IsSystem(token1.ToString()) Dim token2IsSystem = IsSystem(token2.ToString()) If token1IsSystem AndAlso Not token2IsSystem Then Return -1 ElseIf Not token1IsSystem And token2IsSystem Then Return 1 End If End If Return CompareWorker(token1, token2) End Function Private Shared Function IsSystem(s As String) As Boolean Return s = s_systemNamespace End Function Private Shared Function CompareWorker(x As SyntaxToken, y As SyntaxToken) As Integer ' By using 'ValueText' we get the value that is normalized. i.e. ' [class] will be 'class', and unicode escapes will be converted ' to actual unicode. This allows sorting to work properly across ' tokens that have different source representations, but which ' mean the same thing. Dim string1 = x.GetIdentifierText() Dim string2 = y.GetIdentifierText() ' First check in a case insensitive manner. This will put ' everything that starts with an 'a' or 'A' above everything ' that starts with a 'b' or 'B'. Dim value = CultureInfo.InvariantCulture.CompareInfo.Compare(string1, string2, CompareOptions.IgnoreCase Or CompareOptions.IgnoreNonSpace Or CompareOptions.IgnoreWidth) If (value <> 0) Then Return value End If ' Now, once we've grouped such that 'a' words and 'A' words are ' together, sort such that 'a' words come before 'A' words. Return CultureInfo.InvariantCulture.CompareInfo.Compare(string1, string2, CompareOptions.IgnoreNonSpace Or CompareOptions.IgnoreWidth) End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/LanguageServer/Protocol/Features/Options/NamingStyleOptionsStorage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CodeStyle; internal static class NamingStyleOptionsStorage { public static NamingStylePreferences GetNamingStylePreferences(this IGlobalOptionService globalOptions, string language) => globalOptions.GetOption(NamingStyleOptions.NamingPreferences, 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CodeStyle; internal static class NamingStyleOptionsStorage { public static NamingStylePreferences GetNamingStylePreferences(this IGlobalOptionService globalOptions, string language) => globalOptions.GetOption(NamingStyleOptions.NamingPreferences, language); }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/Core/Portable/GenerateMember/GenerateEnumMember/IGenerateEnumMemberService.cs
// Licensed to the .NET Foundation under one or more 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.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateEnumMember { internal interface IGenerateEnumMemberService : ILanguageService { Task<ImmutableArray<CodeAction>> GenerateEnumMemberAsync(Document document, SyntaxNode node, CodeAndImportGenerationOptionsProvider fallbackOptions, 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.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateEnumMember { internal interface IGenerateEnumMemberService : ILanguageService { Task<ImmutableArray<CodeAction>> GenerateEnumMemberAsync(Document document, SyntaxNode node, CodeAndImportGenerationOptionsProvider fallbackOptions, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/Core/RenameTracking/RenameTrackingTag.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking { internal class RenameTrackingTag : TextMarkerTag { internal const string TagId = "RenameTrackingTag"; public static readonly RenameTrackingTag Instance = new(); private RenameTrackingTag() : base(TagId) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking { internal class RenameTrackingTag : TextMarkerTag { internal const string TagId = "RenameTrackingTag"; public static readonly RenameTrackingTag Instance = new(); private RenameTrackingTag() : base(TagId) { } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/DiaSymReader/Utilities/HResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.DiaSymReader { internal static class HResult { internal const int S_OK = 0; internal const int S_FALSE = 1; internal const int E_NOTIMPL = unchecked((int)0x80004001); internal const int E_FAIL = unchecked((int)0x80004005); internal const int E_INVALIDARG = unchecked((int)0x80070057); internal const int E_UNEXPECTED = unchecked((int)0x8000FFFF); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.DiaSymReader { internal static class HResult { internal const int S_OK = 0; internal const int S_FALSE = 1; internal const int E_NOTIMPL = unchecked((int)0x80004001); internal const int E_FAIL = unchecked((int)0x80004005); internal const int E_INVALIDARG = unchecked((int)0x80070057); internal const int E_UNEXPECTED = unchecked((int)0x8000FFFF); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/VisualBasicTest/CodeActions/ConvertNumericLiteral/ConvertNumericLiteralTests.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.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertNumericLiteral Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.ConvertNumericLiteral Public Class ConvertNumericLiteralTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicConvertNumericLiteralCodeRefactoringProvider() End Function Private Enum Refactoring ChangeBase1 ChangeBase2 AddOrRemoveDigitSeparators End Enum Private Async Function TestMissingOneAsync(initial As String) As Task Await TestMissingInRegularAndScriptAsync(CreateTreeText("[||]" + initial)) End Function Private Async Function TestFixOneAsync(initial As String, expected As String, refactoring As Refactoring) As Task Await TestInRegularAndScriptAsync(CreateTreeText("[||]" + initial), CreateTreeText(expected), index:=DirectCast(refactoring, Integer)) End Function Private Shared Function CreateTreeText(initial As String) As String Return " Class X Sub M() Dim x = " + initial + " End Sub End Class" End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestRemoveDigitSeparators() As Task Await TestFixOneAsync("&B1_0_01UL", "&B1001UL", Refactoring.AddOrRemoveDigitSeparators) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestConvertToBinary() As Task Await TestFixOneAsync("5", "&B101", Refactoring.ChangeBase1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestConvertToDecimal() As Task Await TestFixOneAsync("&B101", "5", Refactoring.ChangeBase1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestConvertToHex() As Task Await TestFixOneAsync("10", "&HA", Refactoring.ChangeBase2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestSeparateThousands() As Task Await TestFixOneAsync("100000000", "100_000_000", Refactoring.AddOrRemoveDigitSeparators) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestSeparateWords() As Task Await TestFixOneAsync("&H1111abcd1111", "&H1111_abcd_1111", Refactoring.AddOrRemoveDigitSeparators) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestSeparateNibbles() As Task Await TestFixOneAsync("&B10101010", "&B1010_1010", Refactoring.AddOrRemoveDigitSeparators) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestMissingOnFloatingPoint() As Task Await TestMissingOneAsync("1.1") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestMissingOnScientificNotation() As Task Await TestMissingOneAsync("1e5") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestConvertToDecimal_02() As Task Await TestFixOneAsync("&H1e5", "485", Refactoring.ChangeBase1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestTypeCharacter() As Task Await TestFixOneAsync("&H1e5UL", "&B111100101UL", Refactoring.ChangeBase2) End Function <WorkItem(19225, "https://github.com/dotnet/roslyn/issues/19225")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestPreserveTrivia() As Task Await TestInRegularAndScriptAsync( "Class X Sub M() Dim x As Integer() = { [||]&H1, &H2 } End Sub End Class", "Class X Sub M() Dim x As Integer() = { &B1, &H2 } End Sub End Class", index:=Refactoring.ChangeBase2) End Function <WorkItem(19369, "https://github.com/dotnet/roslyn/issues/19369")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestCaretPositionAtTheEnd() As Task Await TestInRegularAndScriptAsync( "Class C Dim a As Integer = 42[||] End Class", "Class C Dim a As Integer = &B101010 End Class", index:=Refactoring.ChangeBase1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestSelectionMatchesToken() As Task Await TestInRegularAndScriptAsync( "Class C Dim a As Integer = [|42|] End Class", "Class C Dim a As Integer = &B101010 End Class", index:=Refactoring.ChangeBase1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestSelectionDoesntMatchToken() As Task Await TestMissingInRegularAndScriptAsync( "Class C Dim a As Integer = [|42 * 2|] End Class") End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertNumericLiteral Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.ConvertNumericLiteral Public Class ConvertNumericLiteralTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicConvertNumericLiteralCodeRefactoringProvider() End Function Private Enum Refactoring ChangeBase1 ChangeBase2 AddOrRemoveDigitSeparators End Enum Private Async Function TestMissingOneAsync(initial As String) As Task Await TestMissingInRegularAndScriptAsync(CreateTreeText("[||]" + initial)) End Function Private Async Function TestFixOneAsync(initial As String, expected As String, refactoring As Refactoring) As Task Await TestInRegularAndScriptAsync(CreateTreeText("[||]" + initial), CreateTreeText(expected), index:=DirectCast(refactoring, Integer)) End Function Private Shared Function CreateTreeText(initial As String) As String Return " Class X Sub M() Dim x = " + initial + " End Sub End Class" End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestRemoveDigitSeparators() As Task Await TestFixOneAsync("&B1_0_01UL", "&B1001UL", Refactoring.AddOrRemoveDigitSeparators) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestConvertToBinary() As Task Await TestFixOneAsync("5", "&B101", Refactoring.ChangeBase1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestConvertToDecimal() As Task Await TestFixOneAsync("&B101", "5", Refactoring.ChangeBase1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestConvertToHex() As Task Await TestFixOneAsync("10", "&HA", Refactoring.ChangeBase2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestSeparateThousands() As Task Await TestFixOneAsync("100000000", "100_000_000", Refactoring.AddOrRemoveDigitSeparators) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestSeparateWords() As Task Await TestFixOneAsync("&H1111abcd1111", "&H1111_abcd_1111", Refactoring.AddOrRemoveDigitSeparators) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestSeparateNibbles() As Task Await TestFixOneAsync("&B10101010", "&B1010_1010", Refactoring.AddOrRemoveDigitSeparators) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestMissingOnFloatingPoint() As Task Await TestMissingOneAsync("1.1") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestMissingOnScientificNotation() As Task Await TestMissingOneAsync("1e5") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestConvertToDecimal_02() As Task Await TestFixOneAsync("&H1e5", "485", Refactoring.ChangeBase1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestTypeCharacter() As Task Await TestFixOneAsync("&H1e5UL", "&B111100101UL", Refactoring.ChangeBase2) End Function <WorkItem(19225, "https://github.com/dotnet/roslyn/issues/19225")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestPreserveTrivia() As Task Await TestInRegularAndScriptAsync( "Class X Sub M() Dim x As Integer() = { [||]&H1, &H2 } End Sub End Class", "Class X Sub M() Dim x As Integer() = { &B1, &H2 } End Sub End Class", index:=Refactoring.ChangeBase2) End Function <WorkItem(19369, "https://github.com/dotnet/roslyn/issues/19369")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestCaretPositionAtTheEnd() As Task Await TestInRegularAndScriptAsync( "Class C Dim a As Integer = 42[||] End Class", "Class C Dim a As Integer = &B101010 End Class", index:=Refactoring.ChangeBase1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestSelectionMatchesToken() As Task Await TestInRegularAndScriptAsync( "Class C Dim a As Integer = [|42|] End Class", "Class C Dim a As Integer = &B101010 End Class", index:=Refactoring.ChangeBase1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertNumericLiteral)> Public Async Function TestSelectionDoesntMatchToken() As Task Await TestMissingInRegularAndScriptAsync( "Class C Dim a As Integer = [|42 * 2|] End Class") End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./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.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.GetService<IThreadingContext>(), workspace.GlobalOptions); 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.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.GetService<IThreadingContext>(), workspace.GlobalOptions); 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,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/Core/Portable/Shared/Extensions/FileLinePositionSpanExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class FileLinePositionSpanExtensions { /// <summary> /// Get mapped file path if exist, otherwise return null. /// </summary> public static string? GetMappedFilePathIfExist(this FileLinePositionSpan fileLinePositionSpan) => fileLinePositionSpan.HasMappedPath ? fileLinePositionSpan.Path : 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. namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class FileLinePositionSpanExtensions { /// <summary> /// Get mapped file path if exist, otherwise return null. /// </summary> public static string? GetMappedFilePathIfExist(this FileLinePositionSpan fileLinePositionSpan) => fileLinePositionSpan.HasMappedPath ? fileLinePositionSpan.Path : null; } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/Core/Portable/Completion/CompletionTriggerKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// The kind of action that triggered completion to start. /// </summary> public enum CompletionTriggerKind { /// <summary> /// Completion was triggered via some other mechanism. /// </summary> [Obsolete("Use 'Invoke' instead.")] Other = 0, /// <summary> /// Completion was trigger by a direct invocation of the completion feature /// (ctrl-j in Visual Studio). /// </summary> Invoke = 0, /// <summary> /// Completion was triggered via an action inserting a character into the document. /// </summary> Insertion = 1, /// <summary> /// Completion was triggered via an action deleting a character from the document. /// </summary> Deletion = 2, /// <summary> /// Completion was triggered for snippets only. /// </summary> Snippets = 3, /// <summary> /// Completion was triggered with a request to commit if a unique item would be selected /// (ctrl-space in Visual Studio). /// </summary> InvokeAndCommitIfUnique = 4 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// The kind of action that triggered completion to start. /// </summary> public enum CompletionTriggerKind { /// <summary> /// Completion was triggered via some other mechanism. /// </summary> [Obsolete("Use 'Invoke' instead.")] Other = 0, /// <summary> /// Completion was trigger by a direct invocation of the completion feature /// (ctrl-j in Visual Studio). /// </summary> Invoke = 0, /// <summary> /// Completion was triggered via an action inserting a character into the document. /// </summary> Insertion = 1, /// <summary> /// Completion was triggered via an action deleting a character from the document. /// </summary> Deletion = 2, /// <summary> /// Completion was triggered for snippets only. /// </summary> Snippets = 3, /// <summary> /// Completion was triggered with a request to commit if a unique item would be selected /// (ctrl-space in Visual Studio). /// </summary> InvokeAndCommitIfUnique = 4 } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Test/Core/Platform/Desktop/ErrorDiagnostics.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if NET472 using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Roslyn.Test.Utilities { public sealed class ErrorDiagnostics { public enum WellKnownDll { PlatformVsEditor, PlatformEditor, TextLogic, TextUI, TextWpf, TextData, UIUndo, StandardClassification } public enum DllVersion { Unknown, Beta2, RC } public static List<string> DiagnoseMefProblems() { var list = new List<string>(); var dllList = GetWellKnownDllsWithVersion().ToList(); foreach (var tuple in dllList) { if (tuple.Item3 == DllVersion.RC) { var assembly = tuple.Item1; list.Add(string.Format("Loaded RC version of assembly {0} instead of beta2: {1} - {2}", assembly.GetName().Name, assembly.CodeBase, assembly.Location)); } } return list; } public static IEnumerable<Tuple<Assembly, WellKnownDll>> GetWellKnownDlls() { var list = AppDomain.CurrentDomain.GetAssemblies().ToList(); foreach (var assembly in list) { switch (assembly.GetName().Name) { case "Microsoft.VisualStudio.Platform.VSEditor": yield return Tuple.Create(assembly, WellKnownDll.PlatformVsEditor); break; case "Microsoft.VisualStudio.Platform.Editor": yield return Tuple.Create(assembly, WellKnownDll.PlatformEditor); break; case "Microsoft.VisualStudio.Text.Logic": yield return Tuple.Create(assembly, WellKnownDll.TextLogic); break; case "Microsoft.VisualStudio.Text.UI": yield return Tuple.Create(assembly, WellKnownDll.TextUI); break; case "Microsoft.VisualStudio.Text.Data": yield return Tuple.Create(assembly, WellKnownDll.TextData); break; case "Microsoft.VisualStudio.Text.UI.Wpf": yield return Tuple.Create(assembly, WellKnownDll.TextWpf); break; case "Microsoft.VisualStudio.UI.Undo": yield return Tuple.Create(assembly, WellKnownDll.UIUndo); break; case "Microsoft.VisualStudio.Language.StandardClassification": yield return Tuple.Create(assembly, WellKnownDll.StandardClassification); break; } } } private static IEnumerable<Tuple<Assembly, WellKnownDll, DllVersion>> GetWellKnownDllsWithVersion() { foreach (var pair in GetWellKnownDlls()) { switch (pair.Item2) { case WellKnownDll.PlatformVsEditor: { var type = pair.Item1.GetType("Microsoft.VisualStudio.Text.Implementation.BaseSnapshot"); var ct = type.GetProperty("ContentType"); var version = ct == null ? DllVersion.Beta2 : DllVersion.RC; yield return Tuple.Create(pair.Item1, pair.Item2, version); } break; case WellKnownDll.TextData: { var type = pair.Item1.GetType("Microsoft.VisualStudio.Text.ITextSnapshot"); var ct = type.GetProperty("ContentType"); var version = ct == null ? DllVersion.Beta2 : DllVersion.RC; yield return Tuple.Create(pair.Item1, pair.Item2, version); } break; default: yield return Tuple.Create(pair.Item1, pair.Item2, DllVersion.Unknown); break; } } } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if NET472 using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Roslyn.Test.Utilities { public sealed class ErrorDiagnostics { public enum WellKnownDll { PlatformVsEditor, PlatformEditor, TextLogic, TextUI, TextWpf, TextData, UIUndo, StandardClassification } public enum DllVersion { Unknown, Beta2, RC } public static List<string> DiagnoseMefProblems() { var list = new List<string>(); var dllList = GetWellKnownDllsWithVersion().ToList(); foreach (var tuple in dllList) { if (tuple.Item3 == DllVersion.RC) { var assembly = tuple.Item1; list.Add(string.Format("Loaded RC version of assembly {0} instead of beta2: {1} - {2}", assembly.GetName().Name, assembly.CodeBase, assembly.Location)); } } return list; } public static IEnumerable<Tuple<Assembly, WellKnownDll>> GetWellKnownDlls() { var list = AppDomain.CurrentDomain.GetAssemblies().ToList(); foreach (var assembly in list) { switch (assembly.GetName().Name) { case "Microsoft.VisualStudio.Platform.VSEditor": yield return Tuple.Create(assembly, WellKnownDll.PlatformVsEditor); break; case "Microsoft.VisualStudio.Platform.Editor": yield return Tuple.Create(assembly, WellKnownDll.PlatformEditor); break; case "Microsoft.VisualStudio.Text.Logic": yield return Tuple.Create(assembly, WellKnownDll.TextLogic); break; case "Microsoft.VisualStudio.Text.UI": yield return Tuple.Create(assembly, WellKnownDll.TextUI); break; case "Microsoft.VisualStudio.Text.Data": yield return Tuple.Create(assembly, WellKnownDll.TextData); break; case "Microsoft.VisualStudio.Text.UI.Wpf": yield return Tuple.Create(assembly, WellKnownDll.TextWpf); break; case "Microsoft.VisualStudio.UI.Undo": yield return Tuple.Create(assembly, WellKnownDll.UIUndo); break; case "Microsoft.VisualStudio.Language.StandardClassification": yield return Tuple.Create(assembly, WellKnownDll.StandardClassification); break; } } } private static IEnumerable<Tuple<Assembly, WellKnownDll, DllVersion>> GetWellKnownDllsWithVersion() { foreach (var pair in GetWellKnownDlls()) { switch (pair.Item2) { case WellKnownDll.PlatformVsEditor: { var type = pair.Item1.GetType("Microsoft.VisualStudio.Text.Implementation.BaseSnapshot"); var ct = type.GetProperty("ContentType"); var version = ct == null ? DllVersion.Beta2 : DllVersion.RC; yield return Tuple.Create(pair.Item1, pair.Item2, version); } break; case WellKnownDll.TextData: { var type = pair.Item1.GetType("Microsoft.VisualStudio.Text.ITextSnapshot"); var ct = type.GetProperty("ContentType"); var version = ct == null ? DllVersion.Beta2 : DllVersion.RC; yield return Tuple.Create(pair.Item1, pair.Item2, version); } break; default: yield return Tuple.Create(pair.Item1, pair.Item2, DllVersion.Unknown); break; } } } } } #endif
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/FlowDiagnosticTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.[Text] Imports System.Collections.Generic Imports System.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestMetadata Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SimpleFlowTests Inherits FlowTestBase <Fact> Public Sub TestUninitializedIntegerLocal() Dim program = <compilation name="TestUninitializedIntegerLocal"> <file name="a.b"> Module Module1 Sub Goo(z As Integer) Dim x As Integer If z = 2 Then Dim y As Integer = x : x = y ' ok to use unassigned integer local Else dim y as integer = x : x = y ' no diagnostic in unreachable code End If End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <Fact> Public Sub TestUnusedIntegerLocal() Dim program = <compilation name="TestUnusedIntegerLocal"> <file name="a.b"> Module Module1 Public Sub SubWithByRef(ByRef i As Integer) End Sub Sub TestInitialized1() Dim x as integer = 1 ' No warning for a variable assigned a value but not used Dim i1 As Integer Dim i2 As Integer i2 = i1 ' OK to use an uninitialized integer. Spec says all variables are initialized Dim i3 As Integer SubWithByRef(i3) ' Ok to pass an uninitialized integer byref Dim i4 As Integer ' Warning - unused local End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, <expected> BC42024: Unused local variable: 'i4'. Dim i4 As Integer ' Warning - unused local ~~ </expected>) End Sub <Fact> Public Sub TestStructure1() Dim program = <compilation name="TestStructure1"> <file name="a.b"> Module Module1 Structure s1 Dim i As Integer Dim o As Object End Structure Public Sub SubWithByRef(ByRef i As s1, j as integer) End Sub Sub TestInitialized1() Dim i1 As s1 Dim i2 As s1 i2 = i1 ' Warning- use of uninitialized variable Dim i3 As s1 SubWithByRef(j := 1, i := i3) ' Warning- use of uninitialized variable Dim i4 As s1 ' Warning - unused local End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> BC42109: Variable 'i1' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use i2 = i1 ' Warning- use of uninitialized variable ~~ BC42108: Variable 'i3' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use SubWithByRef(j := 1, i := i3) ' Warning- use of uninitialized variable ~~ BC42024: Unused local variable: 'i4'. Dim i4 As s1 ' Warning - unused local ~~ </expected>)) End Sub <Fact> Public Sub TestObject1() Dim program = <compilation name="TestObject1"> <file name="a.b"> Module Module1 Class C1 Public i As Integer Public o As Object End Class Public Sub SubWithByRef(ByRef i As C1) End Sub Sub TestInitialized1() Dim i1 As C1 Dim i2 As C1 i2 = i1 ' Warning- use of uninitialized variable Dim i3 As MyClass SubWithByRef(i3) ' Warning- use of uninitialized variable Dim i4 As C1 ' Warning - unused local End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> BC42104: Variable 'i1' is used before it has been assigned a value. A null reference exception could result at runtime. i2 = i1 ' Warning- use of uninitialized variable ~~ BC42104: Variable 'i3' is used before it has been assigned a value. A null reference exception could result at runtime. SubWithByRef(i3) ' Warning- use of uninitialized variable ~~ BC42024: Unused local variable: 'i4'. Dim i4 As C1 ' Warning - unused local ~~ </expected>)) End Sub <Fact()> Public Sub LambdaInUnimplementedPartial_1() Dim program = <compilation name="LambdaInUnimplementedPartial_1"> <file name="a.b"> Imports System Partial Class C Partial Private Shared Sub Goo(a As action) End Sub Public Shared Sub Main() Goo(DirectCast(Sub() Dim x As Integer Dim y As Integer = x End Sub, Action)) End Sub End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<errors></errors>)) End Sub <Fact()> Public Sub LambdaInUnimplementedPartial_2() Dim program = <compilation name="LambdaInUnimplementedPartial_2"> <file name="a.b"> Imports System Partial Class C Partial Private Shared Sub Goo(a As action) End Sub Public Shared Sub Main() Goo(DirectCast(Sub() Dim x As Integer End Sub, Action)) End Sub End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<errors> BC42024: Unused local variable: 'x'. Dim x As Integer ~ </errors>)) End Sub <WorkItem(722619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722619")> <Fact()> Public Sub Bug_722619() Dim program = <compilation> <file name="a.b"> Imports System Friend Module SubMod Sub Main() Dim x As Exception Try Throw New DivideByZeroException L1: 'COMPILEWARNING: BC42104, "x" Console.WriteLine(x.Message) Catch ex As DivideByZeroException GoTo L1 Finally x = New Exception("finally") End Try End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(comp, <errors> BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. Console.WriteLine(x.Message) ~ </errors>) End Sub <WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")> <Fact()> Public Sub Bug_722575a() Dim program = <compilation> <file name="a.b"> Imports System Friend Module TestNone Structure Str1(Of T) Dim x As T Sub goo() Dim o As Object Dim s1 As Str1(Of T) o = s1 Dim s2 As Str1(Of T) o = s2.x Dim s3 As Str1(Of T) s3.x = Nothing o = s3.x Dim s4 As Str1(Of T) s4.x = Nothing o = s4 End Sub End Structure End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>) End Sub <WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")> <Fact()> Public Sub Bug_722575b() Dim program = <compilation> <file name="a.b"> Imports System Friend Module TestStruct Structure Str1(Of T As Structure) Dim x As T Sub goo() Dim o As Object Dim s1 As Str1(Of T) o = s1 Dim s2 As Str1(Of T) o = s2.x Dim s3 As Str1(Of T) s3.x = Nothing o = s3.x Dim s4 As Str1(Of T) s4.x = Nothing o = s4 End Sub End Structure End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>) End Sub <WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")> <Fact()> Public Sub Bug_722575c() Dim program = <compilation> <file name="a.b"> Imports System Friend Module TestClass Structure Str1(Of T As Class) Dim x As T Sub goo() Dim o As Object Dim s1 As Str1(Of T) o = s1 Dim s2 As Str1(Of T) o = s2.x Dim s3 As Str1(Of T) s3.x = Nothing o = s3.x Dim s4 As Str1(Of T) s4.x = Nothing o = s4 End Sub End Structure End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(comp, <errors> BC42109: Variable 's1' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use o = s1 ~~ BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. o = s2.x ~~~~ </errors>) End Sub <WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")> <Fact()> Public Sub Bug_722575d() Dim program = <compilation> <file name="a.b"> Imports System Friend Module TestNewAndDisposable Structure Str1(Of T As {IDisposable, New}) Dim x As T Sub goo() Dim o As Object Dim s1 As Str1(Of T) o = s1 Dim s2 As Str1(Of T) o = s2.x Dim s3 As Str1(Of T) s3.x = Nothing o = s3.x Dim s4 As Str1(Of T) s4.x = Nothing o = s4 End Sub End Structure End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>) End Sub <WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")> <Fact()> Public Sub Bug_722575e() Dim program = <compilation> <file name="a.b"> Imports System Friend Class TestNone(Of T) Structure Str1 Dim x As T Sub goo() Dim o As Object Dim s1 As Str1 o = s1 Dim s2 As Str1 o = s2.x Dim s3 As Str1 s3.x = Nothing o = s3.x Dim s4 As Str1 s4.x = Nothing o = s4 End Sub End Structure End Class Friend Class TestStruct(Of T As Structure) Structure Str1 Dim x As T Sub goo() Dim o As Object Dim s1 As Str1 o = s1 Dim s2 As Str1 o = s2.x Dim s3 As Str1 s3.x = Nothing o = s3.x Dim s4 As Str1 s4.x = Nothing o = s4 End Sub End Structure End Class Friend Class TestClass(Of T As Class) Structure Str1 Dim x As T Sub goo() Dim o As Object Dim s1 As Str1 o = s1 Dim s2 As Str1 o = s2.x Dim s3 As Str1 s3.x = Nothing o = s3.x Dim s4 As Str1 s4.x = Nothing o = s4 End Sub End Structure End Class Friend Class TestNewAndDisposable(Of T As {IDisposable, New}) Structure Str1 Dim x As T Sub goo() Dim o As Object Dim s1 As Str1 o = s1 Dim s2 As Str1 o = s2.x Dim s3 As Str1 s3.x = Nothing o = s3.x Dim s4 As Str1 s4.x = Nothing o = s4 End Sub End Structure End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(comp, <errors> BC42109: Variable 's1' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use o = s1 ~~ BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. o = s2.x ~~~~ </errors>) End Sub <WorkItem(617061, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617061")> <Fact()> Public Sub Bug_617061() Dim program = <compilation> <file name="a.b"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim a(100) As MEMORY_BASIC_INFORMATION Dim b = From x In a Select x.BaseAddress End Sub End Module Structure MEMORY_BASIC_INFORMATION Dim BaseAddress As UIntPtr End Structure </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>) End Sub <WorkItem(544072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544072")> <Fact()> Public Sub TestBug12221a() Dim program = <compilation name="TestBug12221a"> <file name="a.b"> Imports System Structure SS Public S As String End Structure Module Program222 Sub Main(args As String()) Dim s As SS Dim dict As New Dictionary(Of String, SS) If dict.TryGetValue("", s) Then End If End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> BC42109: Variable 's' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use If dict.TryGetValue("", s) Then ~ </expected>)) End Sub <WorkItem(544072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544072")> <Fact()> Public Sub TestBug12221b() Dim program = <compilation name="TestBug12221b"> <file name="a.b"> Imports System Structure SS Public S As Integer End Structure Module Program222 Sub Main(args As String()) Dim s As SS Dim dict As New Dictionary(Of String, SS) If dict.TryGetValue("", s) Then End If End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> </expected>)) End Sub <WorkItem(544072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544072")> <Fact()> Public Sub TestBug12221c() Dim program = <compilation name="TestBug12221c"> <file name="a.b"> Module Program222 Interface I End Interface Sub Main(Of T As I)(args As String()) Dim s As T Dim dict As New Dictionary(Of String, T) If dict.TryGetValue("", s) Then End If End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> </expected>)) End Sub <WorkItem(544072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544072")> <Fact()> Public Sub TestBug12221d() Dim program = <compilation name="TestBug12221d"> <file name="a.b"> Module Program222 Sub Main(Of T As Class)(args As String()) Dim s As T Dim dict As New Dictionary(Of String, T) If dict.TryGetValue("", s) Then End If End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> BC42104: Variable 's' is used before it has been assigned a value. A null reference exception could result at runtime. If dict.TryGetValue("", s) Then ~ </expected>)) End Sub <Fact()> Public Sub TestReachable1() Dim program = <compilation name="TestReachable1"> <file name="a.b"> Imports System Module Module1 Sub TestUnreachable1() Dim i As Integer ' Dev10 Warning - unused local Return Dim j As Integer ' Dev10 No warning because this is unreachable Console.WriteLine(i, j) End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> </expected>)) End Sub <Fact> Public Sub TestReachable2() Dim program = <compilation name="TestReachable2"> <file name="a.b"> Imports System Module Module1 Sub TestUnreachable1() Dim i As Integer ' Dev10 Warning - unused local Return Dim j As Integer = 1 ' Dev10 No warning because this is unreachable Console.WriteLine(i, j) End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> </expected>)) End Sub <Fact> Public Sub TestGoto1() Dim program = <compilation name="TestGoto1"> <file name="a.b"> Imports System Module Module1 Sub TestGoto1() Dim o1, o2 As Object GoTo l1 l2: o1 = o2 return l1: If false Then o2 = "a" end if GoTo l2 End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> BC42104: Variable 'o2' is used before it has been assigned a value. A null reference exception could result at runtime. o1 = o2 ~~ </expected>)) End Sub <Fact> Public Sub LambdaEntryPointIsReachable1() Dim program = <compilation name="LambdaEntryPointIsReachable1"> <file name="a.b"> Imports System Public Module Program Public Sub Main(args As String()) Dim i As Integer Return Dim x As Integer = i Dim a As action = DirectCast(Sub() Dim j As Integer = i + j End Sub, action) End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> </expected>)) End Sub <Fact> Public Sub LambdaEntryPointIsReachable2() Dim program = <compilation name="LambdaEntryPointIsReachable2"> <file name="a.b"> Imports System Public Module Program Public Sub Main(args As String()) Dim i As Integer Return Dim a As action = DirectCast(Sub() Dim j As Integer = i + j End Sub, action) End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> </expected>)) End Sub <Fact> Public Sub LambdaEntryPointIsReachable3() Dim program = <compilation name="LambdaEntryPointIsReachable3"> <file name="a.b"> Imports System Public Module Program Public Sub Main(args As String()) Dim i As Integer Return Dim a As action = DirectCast(Sub() Dim j As Integer = i + j Return Dim k = j End Sub, action) End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> </expected>)) End Sub <Fact> Public Sub TestDoLoop1() Dim program = <compilation name="TestDoLoop1"> <file name="a.b"> Imports System Module Module1 Sub TestGoto1() Dim o1, o2 As Object GoTo l1 l2: o1 = o2 return l1: do exit do o2 = "a" loop GoTo l2 End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> BC42104: Variable 'o2' is used before it has been assigned a value. A null reference exception could result at runtime. o1 = o2 ~~ </expected>)) End Sub <Fact> Public Sub TestDoLoop2() Dim program = <compilation name="TestDoLoop2"> <file name="a.b"> Imports System Module Module1 Sub TestGoto1() Dim o1, o2 As Object GoTo l1 l2: o1 = o2 return do l1: o2 = "a" exit do loop goto l2 End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <Fact> Public Sub TestBlocks() Dim program = <compilation name="TestDoLoop2"> <file name="a.b"> Imports System Module Module1 Sub TestGoto1() do until false while false end while loop do while true while true end while loop End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <Fact> Public Sub RefParameter01() Dim program = <compilation name="RefParameter01"> <file name="a.b"> class Program public shared Sub Main(args as string()) dim i as string F(i) ' use of unassigned local variable &apos;i&apos; end sub shared sub F(byref i as string) end sub end class</file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Assert.NotEmpty(Me.FlowDiagnostics(comp).AsEnumerable().Where(Function(e) e.Severity = DiagnosticSeverity.[Warning])) End Sub <Fact> Public Sub FunctionDoesNotReturnAValue() Dim program = <compilation name="FunctionDoesNotReturnAValue"> <file name="a.b"> class Program public function goo() as integer end function end class</file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<errors> BC42353: Function 'goo' doesn't return a value on all code paths. Are you missing a 'Return' statement? end function ~~~~~~~~~~~~ </errors>)) End Sub <Fact> Public Sub FunctionReturnsAValue() Dim program = <compilation name="FunctionDoesNotReturnAValue"> <file name="a.b"> class Program public function goo() as integer return 0 end function public function bar() as integer bar = 0 end function end class</file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<errors> </errors>)) End Sub <WorkItem(540687, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540687")> <Fact> Public Sub FunctionDoesNotReturnAnEnumValue() Dim program = <compilation name="FunctionDoesNotReturnAValue"> <file name="a.b"> Imports System Imports System.Collections.Generic Imports System.Linq Enum e1 a b End Enum Module Program Function f As e1 End Function Sub Main(args As String()) Dim x As Func(Of e1) = Function() End Function End Sub End Module</file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<errors> <![CDATA[ BC42353: Function 'f' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Function ~~~~~~~~~~~~ BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Function ~~~~~~~~~~~~ ]]> </errors>)) End Sub <WorkItem(541005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541005")> <Fact> Public Sub TestLocalsInitializedByAsNew() Dim program = <compilation name="TestLocalsInitializedByAsNew"> <file name="a.b"> Module Module1 Class C Public Sub New() End Class End Class Sub Goo() Dim x, y, z as New C End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <WorkItem(542817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542817")> <Fact> Public Sub ConditionalStateInsideQueryLambda() Dim program = <compilation name="ConditionalStateInsideQueryLambda"> <file name="a.b"> Imports System.Linq Class PEModuleSymbol Function IsNoPiaLocalType(i As Integer) As Boolean End Function End Class Class PENamedTypeSymbol Friend Sub New( moduleSymbol As PEModuleSymbol, containingNamespace As PENamespaceSymbol, typeRid As Integer ) End Sub End Class Class PENamespaceSymbol Private Sub LazyInitializeTypes(types As IEnumerable(Of IGrouping(Of String, Integer))) Dim moduleSymbol As PEModuleSymbol = Nothing Dim children As IEnumerable(Of PENamedTypeSymbol) children = (From g In types, t In g Where Not moduleSymbol.IsNoPiaLocalType(t) Select New PENamedTypeSymbol(moduleSymbol, Me, t)) End Sub End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim diags = comp.GetDiagnostics() End Sub <Fact> Public Sub TestSelectCase_CaseClauseExpression_NeverConstantExpr() Dim program = <compilation name="TestUninitializedIntegerLocal"> <file name="a.b"> <![CDATA[ Imports System Module M1 Sub Main() For x = 0 to 11 Console.Write(x.ToString() + ":") Test(x) Next End Sub Sub Test(number as Integer) ' No unreachable code warning for any case block Select Case 1 Case 1 Console.WriteLine("Equal to 1") Case Is < 1 Console.WriteLine("Less than 1") Case 1 To 5 Console.WriteLine("Between 2 and 5, inclusive") Case 6, 7, 8 Console.WriteLine("Between 6 and 8, inclusive") Case 9 To 10 Console.WriteLine("Equal to 9 or 10") Case Else Console.WriteLine("Greater than 10") End Select End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <Fact> Public Sub TestSelectCase_NoCaseBlocks_NoUnusedLocalWarning() Dim program = <compilation name="TestUnusedIntegerLocal"> <file name="a.b"> Imports System Module M1 Sub Main() Dim number as Integer = 10 Select Case number ' no unused integer warning even though select statement is optimized away End Select End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <Fact> Public Sub TestSelectCase_UninitializedLocalWarning() Dim program = <compilation name="TestUnusedIntegerLocal"> <file name="a.b"> Imports System Module M1 Sub Main() Dim obj as Object Select Case 1 Case 1 ' Case clause expression are never compile time constants, hence Case Else is reachable. obj = new Object() Case Else End Select Console.WriteLine(obj) ' Use of uninitialized local warning End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<errors> BC42104: Variable 'obj' is used before it has been assigned a value. A null reference exception could result at runtime. Console.WriteLine(obj) ' Use of uninitialized local warning ~~~ </errors>)) End Sub <Fact> Public Sub TestSelectCase_NoUninitializedLocalWarning() Dim program = <compilation name="TestUnusedIntegerLocal"> <file name="a.b"> Imports System Module M1 Sub Main() Dim obj as Object Select Case 1 Case 1 obj = new Object() Case Is > 1, 2 obj = new Object() Case 1 To 10 obj = new Object() Case Else obj = new Object() End Select Console.WriteLine(obj) End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <Fact> Public Sub TestSelectCase_UninitializedLocalWarning_InvalidRangeClause() Dim program = <compilation name="TestUnusedIntegerLocal"> <file name="a.b"> Imports System Module M1 Sub Main() Dim obj as Object Select Case 1 Case 10 To 1 ' Invalid range clause obj = new Object() End Select Console.WriteLine(obj) ' Use of uninitialized local warning End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<errors> BC42104: Variable 'obj' is used before it has been assigned a value. A null reference exception could result at runtime. Console.WriteLine(obj) ' Use of uninitialized local warning ~~~ </errors>)) End Sub <Fact> Public Sub TestSelectCase_NoUninitializedLocalWarning_JumpToAnotherCaseBlock() Dim program = <compilation name="TestUnusedIntegerLocal"> <file name="a.b"> Imports System Module M1 Sub Main() Dim obj as Object Select Case 1 Case 1 ' Case clause expression are never compile time constants, hence Case Else is reachable. Label1: obj = new Object() Case Else Goto Label1 End Select Console.WriteLine(obj) ' Use of uninitialized local warning End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <WorkItem(543095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543095")> <Fact()> Public Sub TestSelectCase_Error_MissingCaseStatement() Dim program = <compilation name="TestSelectCase_Error_MissingCaseStatement"> <file name="a.b"> Imports System Module Program Sub Main(args As String()) Dim x As New myclass1 Select x Ca End Sub End Module Structure myclass1 Implements IDisposable Public Sub dispose() Implements IDisposable.Dispose End Sub End Structure </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <WorkItem(543095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543095")> <Fact()> Public Sub TestSelectCase_Error_MissingCaseExpression() Dim program = <compilation name="TestSelectCase_Error_MissingCaseExpression"> <file name="a.b"> Imports System Module Program Sub Main(args As String()) Dim x As New myclass1 Select x Case End Select End Sub End Module Structure myclass1 Implements IDisposable Public Sub dispose() Implements IDisposable.Dispose End Sub End Structure </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <Fact> <WorkItem(100475, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems?_a=edit&id=100475")> <WorkItem(529405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529405")> Public Sub TestThrowDoNotReportUnreachable() Dim program = <compilation> <file name="a.b"> Imports System Class Test Sub Method1() Throw New Exception() Return End Sub Function Method2(x As Integer) As Integer If x &lt; 0 Then Return -1 Else Return 1 End If Throw New System.InvalidOperationException() End Function End Class </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40(program).VerifyDiagnostics() End Sub <WorkItem(531310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531310")> <Fact()> Public Sub Bug_17926() Dim program = <compilation> <file name="a.b"> Imports System Imports System.Collections.Generic Module Module1 Public Function RemoveTextWriterTraceListener() As Boolean Try RemoveTextWriterTraceListener = False 'Return true to indicate that the TextWriterTraceListener was removed RemoveTextWriterTraceListener = True Catch e As Exception Console.WriteLine("") End Try Return RemoveTextWriterTraceListener End Function End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program) CompilationUtils.AssertTheseDiagnostics(compilation, <errors></errors>) End Sub <WorkItem(531529, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531529")> <Fact()> Public Sub Bug_18255() Dim program = <compilation> <file name="a.b"> Imports System Public Class TestState ReadOnly Property IsImmediateWindow As Boolean Get Return IsImmediateWindow End Get End Property End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> </errors>) End Sub <WorkItem(531530, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531530")> <Fact()> Public Sub Bug_18256() Dim program = <compilation> <file name="a.b"> Imports System Structure SSSS1 End Structure Structure SSSS2 Private s As String End Structure Enum e1 a End Enum Class CCCCCC Public ReadOnly Property Prop1 As System.Threading.CancellationToken Get End Get End Property Public ReadOnly Property Prop2 As SSSS1 Get End Get End Property Public ReadOnly Property Prop3 As SSSS2 Get End Get End Property Public ReadOnly Property Prop4 As e1 Get End Get End Property Public ReadOnly Property Prop5 As String Get End Get End Property Public ReadOnly Property Prop6 As Integer Get End Get End Property End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC42107: Property 'Prop3' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Get ~~~~~~~ BC42355: Property 'Prop4' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Get ~~~~~~~ BC42107: Property 'Prop5' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Get ~~~~~~~ BC42355: Property 'Prop6' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Get ~~~~~~~ </errors>) End Sub <Fact(), WorkItem(531237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531237")> Public Sub Bug17796() Dim program = <compilation> <file name="a.b"><![CDATA[ Imports System, System.Runtime.CompilerServices Public Module Program Sub Main() End Sub Interface ITextView Event Closed As EventHandler End Interface <Extension()> Public Sub AddOneTimeCloseHandler(ByVal view As ITextView, ByVal del As Action) Dim del2 As EventHandler = Sub(notUsed1, notUsed2) del() RemoveHandler view.Closed, del2 End Sub Dim del3 As Object = Function() As Object del() return del3 End Function.Invoke() Dim del4 As EventHandler del4 = Sub(notUsed1, notUsed2) del() RemoveHandler view.Closed, del4 End Sub Dim del5 As Object del5 = Function() As Object del() return del5 End Function.Invoke() Dim del6 As EventHandler = DirectCast(TryCast(CType( Sub(notUsed1, notUsed2) del() RemoveHandler view.Closed, del6 End Sub, EventHandler), EventHandler), EventHandler) Dim del7 As EventHandler = (Sub(notUsed1, notUsed2) del() RemoveHandler view.Closed, del7 End Sub) End Sub End Module ]]></file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(comp, <errors> BC42104: Variable 'del3' is used before it has been assigned a value. A null reference exception could result at runtime. return del3 ~~~~ BC42104: Variable 'del5' is used before it has been assigned a value. A null reference exception could result at runtime. return del5 ~~~~ </errors>) End Sub <Fact(), WorkItem(530465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530465")> Public Sub SuppressErrorReportingForSynthesizedLocalSymbolWithEmptyName() Dim program = <compilation> <file name="a.b"><![CDATA[ Module Module1 Sub Main() Dim End Sub Sub M() Static End Sub End Module ]]></file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program) CompilationUtils.AssertTheseDiagnostics(comp, <errors> BC30203: Identifier expected. Dim ~ BC30203: Identifier expected. Static ~ </errors>) End Sub <Fact(), WorkItem(2896, "https://github.com/dotnet/roslyn/issues/2896")> Public Sub Issue2896() Dim program = <compilation> <file name="a.b"><![CDATA[ Public Class Test Private _f1 As Boolean = Not Me.DaysTimesInputEnable Private _f2 As Boolean = Me.DaysTimesInputEnable Public ReadOnly Property DaysTimesInputEnable As Boolean Get Return True End Get End Property End Class ]]></file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program) CompilationUtils.AssertTheseDiagnostics(comp) End Sub <Fact> Public Sub LogicalExpressionInErroneousObjectInitializer() Dim program = <compilation> <file name="a.b"> Public Class Class1 Sub Test() Dim x As S1 Dim y As New C1() With {.F1 = x.F1 AndAlso x.F2, .F3 = x.F3} End Sub End Class Public Structure S1 Public F1 As Boolean Public F2 As Boolean Public F3 As Object End Structure </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program, options:=TestOptions.DebugDll) comp.AssertTheseDiagnostics( <expected> BC30002: Type 'C1' is not defined. Dim y As New C1() With {.F1 = x.F1 AndAlso x.F2, .F3 = x.F3} ~~ BC42104: Variable 'F3' is used before it has been assigned a value. A null reference exception could result at runtime. Dim y As New C1() With {.F1 = x.F1 AndAlso x.F2, .F3 = x.F3} ~~~~ </expected> ) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.[Text] Imports System.Collections.Generic Imports System.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestMetadata Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SimpleFlowTests Inherits FlowTestBase <Fact> Public Sub TestUninitializedIntegerLocal() Dim program = <compilation name="TestUninitializedIntegerLocal"> <file name="a.b"> Module Module1 Sub Goo(z As Integer) Dim x As Integer If z = 2 Then Dim y As Integer = x : x = y ' ok to use unassigned integer local Else dim y as integer = x : x = y ' no diagnostic in unreachable code End If End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <Fact> Public Sub TestUnusedIntegerLocal() Dim program = <compilation name="TestUnusedIntegerLocal"> <file name="a.b"> Module Module1 Public Sub SubWithByRef(ByRef i As Integer) End Sub Sub TestInitialized1() Dim x as integer = 1 ' No warning for a variable assigned a value but not used Dim i1 As Integer Dim i2 As Integer i2 = i1 ' OK to use an uninitialized integer. Spec says all variables are initialized Dim i3 As Integer SubWithByRef(i3) ' Ok to pass an uninitialized integer byref Dim i4 As Integer ' Warning - unused local End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, <expected> BC42024: Unused local variable: 'i4'. Dim i4 As Integer ' Warning - unused local ~~ </expected>) End Sub <Fact> Public Sub TestStructure1() Dim program = <compilation name="TestStructure1"> <file name="a.b"> Module Module1 Structure s1 Dim i As Integer Dim o As Object End Structure Public Sub SubWithByRef(ByRef i As s1, j as integer) End Sub Sub TestInitialized1() Dim i1 As s1 Dim i2 As s1 i2 = i1 ' Warning- use of uninitialized variable Dim i3 As s1 SubWithByRef(j := 1, i := i3) ' Warning- use of uninitialized variable Dim i4 As s1 ' Warning - unused local End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> BC42109: Variable 'i1' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use i2 = i1 ' Warning- use of uninitialized variable ~~ BC42108: Variable 'i3' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use SubWithByRef(j := 1, i := i3) ' Warning- use of uninitialized variable ~~ BC42024: Unused local variable: 'i4'. Dim i4 As s1 ' Warning - unused local ~~ </expected>)) End Sub <Fact> Public Sub TestObject1() Dim program = <compilation name="TestObject1"> <file name="a.b"> Module Module1 Class C1 Public i As Integer Public o As Object End Class Public Sub SubWithByRef(ByRef i As C1) End Sub Sub TestInitialized1() Dim i1 As C1 Dim i2 As C1 i2 = i1 ' Warning- use of uninitialized variable Dim i3 As MyClass SubWithByRef(i3) ' Warning- use of uninitialized variable Dim i4 As C1 ' Warning - unused local End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> BC42104: Variable 'i1' is used before it has been assigned a value. A null reference exception could result at runtime. i2 = i1 ' Warning- use of uninitialized variable ~~ BC42104: Variable 'i3' is used before it has been assigned a value. A null reference exception could result at runtime. SubWithByRef(i3) ' Warning- use of uninitialized variable ~~ BC42024: Unused local variable: 'i4'. Dim i4 As C1 ' Warning - unused local ~~ </expected>)) End Sub <Fact()> Public Sub LambdaInUnimplementedPartial_1() Dim program = <compilation name="LambdaInUnimplementedPartial_1"> <file name="a.b"> Imports System Partial Class C Partial Private Shared Sub Goo(a As action) End Sub Public Shared Sub Main() Goo(DirectCast(Sub() Dim x As Integer Dim y As Integer = x End Sub, Action)) End Sub End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<errors></errors>)) End Sub <Fact()> Public Sub LambdaInUnimplementedPartial_2() Dim program = <compilation name="LambdaInUnimplementedPartial_2"> <file name="a.b"> Imports System Partial Class C Partial Private Shared Sub Goo(a As action) End Sub Public Shared Sub Main() Goo(DirectCast(Sub() Dim x As Integer End Sub, Action)) End Sub End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<errors> BC42024: Unused local variable: 'x'. Dim x As Integer ~ </errors>)) End Sub <WorkItem(722619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722619")> <Fact()> Public Sub Bug_722619() Dim program = <compilation> <file name="a.b"> Imports System Friend Module SubMod Sub Main() Dim x As Exception Try Throw New DivideByZeroException L1: 'COMPILEWARNING: BC42104, "x" Console.WriteLine(x.Message) Catch ex As DivideByZeroException GoTo L1 Finally x = New Exception("finally") End Try End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(comp, <errors> BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. Console.WriteLine(x.Message) ~ </errors>) End Sub <WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")> <Fact()> Public Sub Bug_722575a() Dim program = <compilation> <file name="a.b"> Imports System Friend Module TestNone Structure Str1(Of T) Dim x As T Sub goo() Dim o As Object Dim s1 As Str1(Of T) o = s1 Dim s2 As Str1(Of T) o = s2.x Dim s3 As Str1(Of T) s3.x = Nothing o = s3.x Dim s4 As Str1(Of T) s4.x = Nothing o = s4 End Sub End Structure End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>) End Sub <WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")> <Fact()> Public Sub Bug_722575b() Dim program = <compilation> <file name="a.b"> Imports System Friend Module TestStruct Structure Str1(Of T As Structure) Dim x As T Sub goo() Dim o As Object Dim s1 As Str1(Of T) o = s1 Dim s2 As Str1(Of T) o = s2.x Dim s3 As Str1(Of T) s3.x = Nothing o = s3.x Dim s4 As Str1(Of T) s4.x = Nothing o = s4 End Sub End Structure End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>) End Sub <WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")> <Fact()> Public Sub Bug_722575c() Dim program = <compilation> <file name="a.b"> Imports System Friend Module TestClass Structure Str1(Of T As Class) Dim x As T Sub goo() Dim o As Object Dim s1 As Str1(Of T) o = s1 Dim s2 As Str1(Of T) o = s2.x Dim s3 As Str1(Of T) s3.x = Nothing o = s3.x Dim s4 As Str1(Of T) s4.x = Nothing o = s4 End Sub End Structure End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(comp, <errors> BC42109: Variable 's1' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use o = s1 ~~ BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. o = s2.x ~~~~ </errors>) End Sub <WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")> <Fact()> Public Sub Bug_722575d() Dim program = <compilation> <file name="a.b"> Imports System Friend Module TestNewAndDisposable Structure Str1(Of T As {IDisposable, New}) Dim x As T Sub goo() Dim o As Object Dim s1 As Str1(Of T) o = s1 Dim s2 As Str1(Of T) o = s2.x Dim s3 As Str1(Of T) s3.x = Nothing o = s3.x Dim s4 As Str1(Of T) s4.x = Nothing o = s4 End Sub End Structure End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>) End Sub <WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")> <Fact()> Public Sub Bug_722575e() Dim program = <compilation> <file name="a.b"> Imports System Friend Class TestNone(Of T) Structure Str1 Dim x As T Sub goo() Dim o As Object Dim s1 As Str1 o = s1 Dim s2 As Str1 o = s2.x Dim s3 As Str1 s3.x = Nothing o = s3.x Dim s4 As Str1 s4.x = Nothing o = s4 End Sub End Structure End Class Friend Class TestStruct(Of T As Structure) Structure Str1 Dim x As T Sub goo() Dim o As Object Dim s1 As Str1 o = s1 Dim s2 As Str1 o = s2.x Dim s3 As Str1 s3.x = Nothing o = s3.x Dim s4 As Str1 s4.x = Nothing o = s4 End Sub End Structure End Class Friend Class TestClass(Of T As Class) Structure Str1 Dim x As T Sub goo() Dim o As Object Dim s1 As Str1 o = s1 Dim s2 As Str1 o = s2.x Dim s3 As Str1 s3.x = Nothing o = s3.x Dim s4 As Str1 s4.x = Nothing o = s4 End Sub End Structure End Class Friend Class TestNewAndDisposable(Of T As {IDisposable, New}) Structure Str1 Dim x As T Sub goo() Dim o As Object Dim s1 As Str1 o = s1 Dim s2 As Str1 o = s2.x Dim s3 As Str1 s3.x = Nothing o = s3.x Dim s4 As Str1 s4.x = Nothing o = s4 End Sub End Structure End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(comp, <errors> BC42109: Variable 's1' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use o = s1 ~~ BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. o = s2.x ~~~~ </errors>) End Sub <WorkItem(617061, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617061")> <Fact()> Public Sub Bug_617061() Dim program = <compilation> <file name="a.b"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim a(100) As MEMORY_BASIC_INFORMATION Dim b = From x In a Select x.BaseAddress End Sub End Module Structure MEMORY_BASIC_INFORMATION Dim BaseAddress As UIntPtr End Structure </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>) End Sub <WorkItem(544072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544072")> <Fact()> Public Sub TestBug12221a() Dim program = <compilation name="TestBug12221a"> <file name="a.b"> Imports System Structure SS Public S As String End Structure Module Program222 Sub Main(args As String()) Dim s As SS Dim dict As New Dictionary(Of String, SS) If dict.TryGetValue("", s) Then End If End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> BC42109: Variable 's' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use If dict.TryGetValue("", s) Then ~ </expected>)) End Sub <WorkItem(544072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544072")> <Fact()> Public Sub TestBug12221b() Dim program = <compilation name="TestBug12221b"> <file name="a.b"> Imports System Structure SS Public S As Integer End Structure Module Program222 Sub Main(args As String()) Dim s As SS Dim dict As New Dictionary(Of String, SS) If dict.TryGetValue("", s) Then End If End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> </expected>)) End Sub <WorkItem(544072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544072")> <Fact()> Public Sub TestBug12221c() Dim program = <compilation name="TestBug12221c"> <file name="a.b"> Module Program222 Interface I End Interface Sub Main(Of T As I)(args As String()) Dim s As T Dim dict As New Dictionary(Of String, T) If dict.TryGetValue("", s) Then End If End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> </expected>)) End Sub <WorkItem(544072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544072")> <Fact()> Public Sub TestBug12221d() Dim program = <compilation name="TestBug12221d"> <file name="a.b"> Module Program222 Sub Main(Of T As Class)(args As String()) Dim s As T Dim dict As New Dictionary(Of String, T) If dict.TryGetValue("", s) Then End If End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> BC42104: Variable 's' is used before it has been assigned a value. A null reference exception could result at runtime. If dict.TryGetValue("", s) Then ~ </expected>)) End Sub <Fact()> Public Sub TestReachable1() Dim program = <compilation name="TestReachable1"> <file name="a.b"> Imports System Module Module1 Sub TestUnreachable1() Dim i As Integer ' Dev10 Warning - unused local Return Dim j As Integer ' Dev10 No warning because this is unreachable Console.WriteLine(i, j) End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> </expected>)) End Sub <Fact> Public Sub TestReachable2() Dim program = <compilation name="TestReachable2"> <file name="a.b"> Imports System Module Module1 Sub TestUnreachable1() Dim i As Integer ' Dev10 Warning - unused local Return Dim j As Integer = 1 ' Dev10 No warning because this is unreachable Console.WriteLine(i, j) End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> </expected>)) End Sub <Fact> Public Sub TestGoto1() Dim program = <compilation name="TestGoto1"> <file name="a.b"> Imports System Module Module1 Sub TestGoto1() Dim o1, o2 As Object GoTo l1 l2: o1 = o2 return l1: If false Then o2 = "a" end if GoTo l2 End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> BC42104: Variable 'o2' is used before it has been assigned a value. A null reference exception could result at runtime. o1 = o2 ~~ </expected>)) End Sub <Fact> Public Sub LambdaEntryPointIsReachable1() Dim program = <compilation name="LambdaEntryPointIsReachable1"> <file name="a.b"> Imports System Public Module Program Public Sub Main(args As String()) Dim i As Integer Return Dim x As Integer = i Dim a As action = DirectCast(Sub() Dim j As Integer = i + j End Sub, action) End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> </expected>)) End Sub <Fact> Public Sub LambdaEntryPointIsReachable2() Dim program = <compilation name="LambdaEntryPointIsReachable2"> <file name="a.b"> Imports System Public Module Program Public Sub Main(args As String()) Dim i As Integer Return Dim a As action = DirectCast(Sub() Dim j As Integer = i + j End Sub, action) End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> </expected>)) End Sub <Fact> Public Sub LambdaEntryPointIsReachable3() Dim program = <compilation name="LambdaEntryPointIsReachable3"> <file name="a.b"> Imports System Public Module Program Public Sub Main(args As String()) Dim i As Integer Return Dim a As action = DirectCast(Sub() Dim j As Integer = i + j Return Dim k = j End Sub, action) End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> </expected>)) End Sub <Fact> Public Sub TestDoLoop1() Dim program = <compilation name="TestDoLoop1"> <file name="a.b"> Imports System Module Module1 Sub TestGoto1() Dim o1, o2 As Object GoTo l1 l2: o1 = o2 return l1: do exit do o2 = "a" loop GoTo l2 End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<expected> BC42104: Variable 'o2' is used before it has been assigned a value. A null reference exception could result at runtime. o1 = o2 ~~ </expected>)) End Sub <Fact> Public Sub TestDoLoop2() Dim program = <compilation name="TestDoLoop2"> <file name="a.b"> Imports System Module Module1 Sub TestGoto1() Dim o1, o2 As Object GoTo l1 l2: o1 = o2 return do l1: o2 = "a" exit do loop goto l2 End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <Fact> Public Sub TestBlocks() Dim program = <compilation name="TestDoLoop2"> <file name="a.b"> Imports System Module Module1 Sub TestGoto1() do until false while false end while loop do while true while true end while loop End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <Fact> Public Sub RefParameter01() Dim program = <compilation name="RefParameter01"> <file name="a.b"> class Program public shared Sub Main(args as string()) dim i as string F(i) ' use of unassigned local variable &apos;i&apos; end sub shared sub F(byref i as string) end sub end class</file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Assert.NotEmpty(Me.FlowDiagnostics(comp).AsEnumerable().Where(Function(e) e.Severity = DiagnosticSeverity.[Warning])) End Sub <Fact> Public Sub FunctionDoesNotReturnAValue() Dim program = <compilation name="FunctionDoesNotReturnAValue"> <file name="a.b"> class Program public function goo() as integer end function end class</file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<errors> BC42353: Function 'goo' doesn't return a value on all code paths. Are you missing a 'Return' statement? end function ~~~~~~~~~~~~ </errors>)) End Sub <Fact> Public Sub FunctionReturnsAValue() Dim program = <compilation name="FunctionDoesNotReturnAValue"> <file name="a.b"> class Program public function goo() as integer return 0 end function public function bar() as integer bar = 0 end function end class</file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<errors> </errors>)) End Sub <WorkItem(540687, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540687")> <Fact> Public Sub FunctionDoesNotReturnAnEnumValue() Dim program = <compilation name="FunctionDoesNotReturnAValue"> <file name="a.b"> Imports System Imports System.Collections.Generic Imports System.Linq Enum e1 a b End Enum Module Program Function f As e1 End Function Sub Main(args As String()) Dim x As Func(Of e1) = Function() End Function End Sub End Module</file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<errors> <![CDATA[ BC42353: Function 'f' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Function ~~~~~~~~~~~~ BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Function ~~~~~~~~~~~~ ]]> </errors>)) End Sub <WorkItem(541005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541005")> <Fact> Public Sub TestLocalsInitializedByAsNew() Dim program = <compilation name="TestLocalsInitializedByAsNew"> <file name="a.b"> Module Module1 Class C Public Sub New() End Class End Class Sub Goo() Dim x, y, z as New C End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <WorkItem(542817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542817")> <Fact> Public Sub ConditionalStateInsideQueryLambda() Dim program = <compilation name="ConditionalStateInsideQueryLambda"> <file name="a.b"> Imports System.Linq Class PEModuleSymbol Function IsNoPiaLocalType(i As Integer) As Boolean End Function End Class Class PENamedTypeSymbol Friend Sub New( moduleSymbol As PEModuleSymbol, containingNamespace As PENamespaceSymbol, typeRid As Integer ) End Sub End Class Class PENamespaceSymbol Private Sub LazyInitializeTypes(types As IEnumerable(Of IGrouping(Of String, Integer))) Dim moduleSymbol As PEModuleSymbol = Nothing Dim children As IEnumerable(Of PENamedTypeSymbol) children = (From g In types, t In g Where Not moduleSymbol.IsNoPiaLocalType(t) Select New PENamedTypeSymbol(moduleSymbol, Me, t)) End Sub End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim diags = comp.GetDiagnostics() End Sub <Fact> Public Sub TestSelectCase_CaseClauseExpression_NeverConstantExpr() Dim program = <compilation name="TestUninitializedIntegerLocal"> <file name="a.b"> <![CDATA[ Imports System Module M1 Sub Main() For x = 0 to 11 Console.Write(x.ToString() + ":") Test(x) Next End Sub Sub Test(number as Integer) ' No unreachable code warning for any case block Select Case 1 Case 1 Console.WriteLine("Equal to 1") Case Is < 1 Console.WriteLine("Less than 1") Case 1 To 5 Console.WriteLine("Between 2 and 5, inclusive") Case 6, 7, 8 Console.WriteLine("Between 6 and 8, inclusive") Case 9 To 10 Console.WriteLine("Equal to 9 or 10") Case Else Console.WriteLine("Greater than 10") End Select End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <Fact> Public Sub TestSelectCase_NoCaseBlocks_NoUnusedLocalWarning() Dim program = <compilation name="TestUnusedIntegerLocal"> <file name="a.b"> Imports System Module M1 Sub Main() Dim number as Integer = 10 Select Case number ' no unused integer warning even though select statement is optimized away End Select End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <Fact> Public Sub TestSelectCase_UninitializedLocalWarning() Dim program = <compilation name="TestUnusedIntegerLocal"> <file name="a.b"> Imports System Module M1 Sub Main() Dim obj as Object Select Case 1 Case 1 ' Case clause expression are never compile time constants, hence Case Else is reachable. obj = new Object() Case Else End Select Console.WriteLine(obj) ' Use of uninitialized local warning End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<errors> BC42104: Variable 'obj' is used before it has been assigned a value. A null reference exception could result at runtime. Console.WriteLine(obj) ' Use of uninitialized local warning ~~~ </errors>)) End Sub <Fact> Public Sub TestSelectCase_NoUninitializedLocalWarning() Dim program = <compilation name="TestUnusedIntegerLocal"> <file name="a.b"> Imports System Module M1 Sub Main() Dim obj as Object Select Case 1 Case 1 obj = new Object() Case Is > 1, 2 obj = new Object() Case 1 To 10 obj = new Object() Case Else obj = new Object() End Select Console.WriteLine(obj) End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <Fact> Public Sub TestSelectCase_UninitializedLocalWarning_InvalidRangeClause() Dim program = <compilation name="TestUnusedIntegerLocal"> <file name="a.b"> Imports System Module M1 Sub Main() Dim obj as Object Select Case 1 Case 10 To 1 ' Invalid range clause obj = new Object() End Select Console.WriteLine(obj) ' Use of uninitialized local warning End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) CompilationUtils.AssertTheseDiagnostics(errs, (<errors> BC42104: Variable 'obj' is used before it has been assigned a value. A null reference exception could result at runtime. Console.WriteLine(obj) ' Use of uninitialized local warning ~~~ </errors>)) End Sub <Fact> Public Sub TestSelectCase_NoUninitializedLocalWarning_JumpToAnotherCaseBlock() Dim program = <compilation name="TestUnusedIntegerLocal"> <file name="a.b"> Imports System Module M1 Sub Main() Dim obj as Object Select Case 1 Case 1 ' Case clause expression are never compile time constants, hence Case Else is reachable. Label1: obj = new Object() Case Else Goto Label1 End Select Console.WriteLine(obj) ' Use of uninitialized local warning End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <WorkItem(543095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543095")> <Fact()> Public Sub TestSelectCase_Error_MissingCaseStatement() Dim program = <compilation name="TestSelectCase_Error_MissingCaseStatement"> <file name="a.b"> Imports System Module Program Sub Main(args As String()) Dim x As New myclass1 Select x Ca End Sub End Module Structure myclass1 Implements IDisposable Public Sub dispose() Implements IDisposable.Dispose End Sub End Structure </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <WorkItem(543095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543095")> <Fact()> Public Sub TestSelectCase_Error_MissingCaseExpression() Dim program = <compilation name="TestSelectCase_Error_MissingCaseExpression"> <file name="a.b"> Imports System Module Program Sub Main(args As String()) Dim x As New myclass1 Select x Case End Select End Sub End Module Structure myclass1 Implements IDisposable Public Sub dispose() Implements IDisposable.Dispose End Sub End Structure </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program) Dim errs = Me.FlowDiagnostics(comp) errs.AssertNoErrors() End Sub <Fact> <WorkItem(100475, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems?_a=edit&id=100475")> <WorkItem(529405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529405")> Public Sub TestThrowDoNotReportUnreachable() Dim program = <compilation> <file name="a.b"> Imports System Class Test Sub Method1() Throw New Exception() Return End Sub Function Method2(x As Integer) As Integer If x &lt; 0 Then Return -1 Else Return 1 End If Throw New System.InvalidOperationException() End Function End Class </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40(program).VerifyDiagnostics() End Sub <WorkItem(531310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531310")> <Fact()> Public Sub Bug_17926() Dim program = <compilation> <file name="a.b"> Imports System Imports System.Collections.Generic Module Module1 Public Function RemoveTextWriterTraceListener() As Boolean Try RemoveTextWriterTraceListener = False 'Return true to indicate that the TextWriterTraceListener was removed RemoveTextWriterTraceListener = True Catch e As Exception Console.WriteLine("") End Try Return RemoveTextWriterTraceListener End Function End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program) CompilationUtils.AssertTheseDiagnostics(compilation, <errors></errors>) End Sub <WorkItem(531529, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531529")> <Fact()> Public Sub Bug_18255() Dim program = <compilation> <file name="a.b"> Imports System Public Class TestState ReadOnly Property IsImmediateWindow As Boolean Get Return IsImmediateWindow End Get End Property End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> </errors>) End Sub <WorkItem(531530, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531530")> <Fact()> Public Sub Bug_18256() Dim program = <compilation> <file name="a.b"> Imports System Structure SSSS1 End Structure Structure SSSS2 Private s As String End Structure Enum e1 a End Enum Class CCCCCC Public ReadOnly Property Prop1 As System.Threading.CancellationToken Get End Get End Property Public ReadOnly Property Prop2 As SSSS1 Get End Get End Property Public ReadOnly Property Prop3 As SSSS2 Get End Get End Property Public ReadOnly Property Prop4 As e1 Get End Get End Property Public ReadOnly Property Prop5 As String Get End Get End Property Public ReadOnly Property Prop6 As Integer Get End Get End Property End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC42107: Property 'Prop3' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Get ~~~~~~~ BC42355: Property 'Prop4' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Get ~~~~~~~ BC42107: Property 'Prop5' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Get ~~~~~~~ BC42355: Property 'Prop6' doesn't return a value on all code paths. Are you missing a 'Return' statement? End Get ~~~~~~~ </errors>) End Sub <Fact(), WorkItem(531237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531237")> Public Sub Bug17796() Dim program = <compilation> <file name="a.b"><![CDATA[ Imports System, System.Runtime.CompilerServices Public Module Program Sub Main() End Sub Interface ITextView Event Closed As EventHandler End Interface <Extension()> Public Sub AddOneTimeCloseHandler(ByVal view As ITextView, ByVal del As Action) Dim del2 As EventHandler = Sub(notUsed1, notUsed2) del() RemoveHandler view.Closed, del2 End Sub Dim del3 As Object = Function() As Object del() return del3 End Function.Invoke() Dim del4 As EventHandler del4 = Sub(notUsed1, notUsed2) del() RemoveHandler view.Closed, del4 End Sub Dim del5 As Object del5 = Function() As Object del() return del5 End Function.Invoke() Dim del6 As EventHandler = DirectCast(TryCast(CType( Sub(notUsed1, notUsed2) del() RemoveHandler view.Closed, del6 End Sub, EventHandler), EventHandler), EventHandler) Dim del7 As EventHandler = (Sub(notUsed1, notUsed2) del() RemoveHandler view.Closed, del7 End Sub) End Sub End Module ]]></file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, {Net40.SystemCore}) CompilationUtils.AssertTheseDiagnostics(comp, <errors> BC42104: Variable 'del3' is used before it has been assigned a value. A null reference exception could result at runtime. return del3 ~~~~ BC42104: Variable 'del5' is used before it has been assigned a value. A null reference exception could result at runtime. return del5 ~~~~ </errors>) End Sub <Fact(), WorkItem(530465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530465")> Public Sub SuppressErrorReportingForSynthesizedLocalSymbolWithEmptyName() Dim program = <compilation> <file name="a.b"><![CDATA[ Module Module1 Sub Main() Dim End Sub Sub M() Static End Sub End Module ]]></file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program) CompilationUtils.AssertTheseDiagnostics(comp, <errors> BC30203: Identifier expected. Dim ~ BC30203: Identifier expected. Static ~ </errors>) End Sub <Fact(), WorkItem(2896, "https://github.com/dotnet/roslyn/issues/2896")> Public Sub Issue2896() Dim program = <compilation> <file name="a.b"><![CDATA[ Public Class Test Private _f1 As Boolean = Not Me.DaysTimesInputEnable Private _f2 As Boolean = Me.DaysTimesInputEnable Public ReadOnly Property DaysTimesInputEnable As Boolean Get Return True End Get End Property End Class ]]></file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program) CompilationUtils.AssertTheseDiagnostics(comp) End Sub <Fact> Public Sub LogicalExpressionInErroneousObjectInitializer() Dim program = <compilation> <file name="a.b"> Public Class Class1 Sub Test() Dim x As S1 Dim y As New C1() With {.F1 = x.F1 AndAlso x.F2, .F3 = x.F3} End Sub End Class Public Structure S1 Public F1 As Boolean Public F2 As Boolean Public F3 As Object End Structure </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program, options:=TestOptions.DebugDll) comp.AssertTheseDiagnostics( <expected> BC30002: Type 'C1' is not defined. Dim y As New C1() With {.F1 = x.F1 AndAlso x.F2, .F3 = x.F3} ~~ BC42104: Variable 'F3' is used before it has been assigned a value. A null reference exception could result at runtime. Dim y As New C1() With {.F1 = x.F1 AndAlso x.F2, .F3 = x.F3} ~~~~ </expected> ) End Sub End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.cs
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { // EncEditSessionInfo is populated on a background thread and then read from the UI thread internal sealed class EditSessionTelemetry { internal readonly struct Data { public readonly ImmutableArray<(ushort EditKind, ushort SyntaxKind)> RudeEdits; public readonly ImmutableArray<string> EmitErrorIds; public readonly ImmutableArray<Guid> ProjectsWithValidDelta; public readonly EditAndContinueCapabilities Capabilities; public readonly bool HadCompilationErrors; public readonly bool HadRudeEdits; public readonly bool HadValidChanges; public readonly bool HadValidInsignificantChanges; public readonly bool InBreakState; public readonly bool IsEmpty; public readonly bool Committed; public Data(EditSessionTelemetry telemetry) { Contract.ThrowIfNull(telemetry._inBreakState); RudeEdits = telemetry._rudeEdits.AsImmutable(); EmitErrorIds = telemetry._emitErrorIds.AsImmutable(); ProjectsWithValidDelta = telemetry._projectsWithValidDelta.AsImmutable(); HadCompilationErrors = telemetry._hadCompilationErrors; HadRudeEdits = telemetry._hadRudeEdits; HadValidChanges = telemetry._hadValidChanges; HadValidInsignificantChanges = telemetry._hadValidInsignificantChanges; InBreakState = telemetry._inBreakState.Value; Capabilities = telemetry._capabilities; IsEmpty = telemetry.IsEmpty; Committed = telemetry._committed; } } private readonly object _guard = new(); // Limit the number of reported items to limit the size of the telemetry event (max total size is 64K). private const int MaxReportedProjectIds = 20; private readonly HashSet<(ushort, ushort)> _rudeEdits = new(); private readonly HashSet<string> _emitErrorIds = new(); private readonly HashSet<Guid> _projectsWithValidDelta = new(); private bool _hadCompilationErrors; private bool _hadRudeEdits; private bool _hadValidChanges; private bool _hadValidInsignificantChanges; private bool? _inBreakState; private bool _committed; private EditAndContinueCapabilities _capabilities; public Data GetDataAndClear() { lock (_guard) { var data = new Data(this); _rudeEdits.Clear(); _emitErrorIds.Clear(); _projectsWithValidDelta.Clear(); _hadCompilationErrors = false; _hadRudeEdits = false; _hadValidChanges = false; _hadValidInsignificantChanges = false; _inBreakState = null; _capabilities = EditAndContinueCapabilities.None; _committed = false; return data; } } public bool IsEmpty => !(_hadCompilationErrors || _hadRudeEdits || _hadValidChanges || _hadValidInsignificantChanges); public void SetBreakState(bool value) => _inBreakState = value; public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, Guid projectTelemetryId, ImmutableArray<string> errorsIds) { lock (_guard) { _emitErrorIds.AddRange(errorsIds); switch (summary) { case ProjectAnalysisSummary.NoChanges: break; case ProjectAnalysisSummary.CompilationErrors: _hadCompilationErrors = true; break; case ProjectAnalysisSummary.RudeEdits: _hadRudeEdits = true; break; case ProjectAnalysisSummary.ValidChanges: _hadValidChanges = true; if (errorsIds.IsEmpty && _projectsWithValidDelta.Count < MaxReportedProjectIds) { _projectsWithValidDelta.Add(projectTelemetryId); } break; case ProjectAnalysisSummary.ValidInsignificantChanges: _hadValidInsignificantChanges = true; break; default: throw ExceptionUtilities.UnexpectedValue(summary); } } } public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, Guid projectTelemetryId, ImmutableArray<Diagnostic> emitDiagnostics) => LogProjectAnalysisSummary(summary, projectTelemetryId, emitDiagnostics.SelectAsArray(d => d.Severity == DiagnosticSeverity.Error, d => d.Id)); public void LogRudeEditDiagnostics(ImmutableArray<RudeEditDiagnostic> diagnostics) { lock (_guard) { foreach (var diagnostic in diagnostics) { _rudeEdits.Add(((ushort)diagnostic.Kind, diagnostic.SyntaxKind)); } } } public void LogRuntimeCapabilities(EditAndContinueCapabilities capabilities) { lock (_guard) { Debug.Assert(_capabilities == EditAndContinueCapabilities.None || _capabilities == capabilities); _capabilities = capabilities; } } internal void LogCommitted() => _committed = true; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { // EncEditSessionInfo is populated on a background thread and then read from the UI thread internal sealed class EditSessionTelemetry { internal readonly struct Data { public readonly ImmutableArray<(ushort EditKind, ushort SyntaxKind)> RudeEdits; public readonly ImmutableArray<string> EmitErrorIds; public readonly ImmutableArray<Guid> ProjectsWithValidDelta; public readonly EditAndContinueCapabilities Capabilities; public readonly bool HadCompilationErrors; public readonly bool HadRudeEdits; public readonly bool HadValidChanges; public readonly bool HadValidInsignificantChanges; public readonly bool InBreakState; public readonly bool IsEmpty; public readonly bool Committed; public Data(EditSessionTelemetry telemetry) { Contract.ThrowIfNull(telemetry._inBreakState); RudeEdits = telemetry._rudeEdits.AsImmutable(); EmitErrorIds = telemetry._emitErrorIds.AsImmutable(); ProjectsWithValidDelta = telemetry._projectsWithValidDelta.AsImmutable(); HadCompilationErrors = telemetry._hadCompilationErrors; HadRudeEdits = telemetry._hadRudeEdits; HadValidChanges = telemetry._hadValidChanges; HadValidInsignificantChanges = telemetry._hadValidInsignificantChanges; InBreakState = telemetry._inBreakState.Value; Capabilities = telemetry._capabilities; IsEmpty = telemetry.IsEmpty; Committed = telemetry._committed; } } private readonly object _guard = new(); // Limit the number of reported items to limit the size of the telemetry event (max total size is 64K). private const int MaxReportedProjectIds = 20; private readonly HashSet<(ushort, ushort)> _rudeEdits = new(); private readonly HashSet<string> _emitErrorIds = new(); private readonly HashSet<Guid> _projectsWithValidDelta = new(); private bool _hadCompilationErrors; private bool _hadRudeEdits; private bool _hadValidChanges; private bool _hadValidInsignificantChanges; private bool? _inBreakState; private bool _committed; private EditAndContinueCapabilities _capabilities; public Data GetDataAndClear() { lock (_guard) { var data = new Data(this); _rudeEdits.Clear(); _emitErrorIds.Clear(); _projectsWithValidDelta.Clear(); _hadCompilationErrors = false; _hadRudeEdits = false; _hadValidChanges = false; _hadValidInsignificantChanges = false; _inBreakState = null; _capabilities = EditAndContinueCapabilities.None; _committed = false; return data; } } public bool IsEmpty => !(_hadCompilationErrors || _hadRudeEdits || _hadValidChanges || _hadValidInsignificantChanges); public void SetBreakState(bool value) => _inBreakState = value; public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, Guid projectTelemetryId, ImmutableArray<string> errorsIds) { lock (_guard) { _emitErrorIds.AddRange(errorsIds); switch (summary) { case ProjectAnalysisSummary.NoChanges: break; case ProjectAnalysisSummary.CompilationErrors: _hadCompilationErrors = true; break; case ProjectAnalysisSummary.RudeEdits: _hadRudeEdits = true; break; case ProjectAnalysisSummary.ValidChanges: _hadValidChanges = true; if (errorsIds.IsEmpty && _projectsWithValidDelta.Count < MaxReportedProjectIds) { _projectsWithValidDelta.Add(projectTelemetryId); } break; case ProjectAnalysisSummary.ValidInsignificantChanges: _hadValidInsignificantChanges = true; break; default: throw ExceptionUtilities.UnexpectedValue(summary); } } } public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, Guid projectTelemetryId, ImmutableArray<Diagnostic> emitDiagnostics) => LogProjectAnalysisSummary(summary, projectTelemetryId, emitDiagnostics.SelectAsArray(d => d.Severity == DiagnosticSeverity.Error, d => d.Id)); public void LogRudeEditDiagnostics(ImmutableArray<RudeEditDiagnostic> diagnostics) { lock (_guard) { foreach (var diagnostic in diagnostics) { _rudeEdits.Add(((ushort)diagnostic.Kind, diagnostic.SyntaxKind)); } } } public void LogRuntimeCapabilities(EditAndContinueCapabilities capabilities) { lock (_guard) { Debug.Assert(_capabilities == EditAndContinueCapabilities.None || _capabilities == capabilities); _capabilities = capabilities; } } internal void LogCommitted() => _committed = true; } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Analyzers/Core/Analyzers/RemoveRedundantEquality/AbstractRemoveRedundantEqualityDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.RemoveRedundantEquality { internal abstract class AbstractRemoveRedundantEqualityDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { private readonly ISyntaxFacts _syntaxFacts; protected AbstractRemoveRedundantEqualityDiagnosticAnalyzer(ISyntaxFacts syntaxFacts) : base(IDEDiagnosticIds.RemoveRedundantEqualityDiagnosticId, EnforceOnBuildValues.RemoveRedundantEquality, option: null, new LocalizableResourceString(nameof(AnalyzersResources.Remove_redundant_equality), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { _syntaxFacts = syntaxFacts; } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterOperationAction(AnalyzeBinaryOperator, OperationKind.BinaryOperator); private void AnalyzeBinaryOperator(OperationAnalysisContext context) { var operation = (IBinaryOperation)context.Operation; if (operation.OperatorMethod is not null) { // We shouldn't report diagnostic on overloaded operator as the behavior can change. return; } if (operation.OperatorKind is not (BinaryOperatorKind.Equals or BinaryOperatorKind.NotEquals)) { return; } if (!_syntaxFacts.IsBinaryExpression(operation.Syntax)) { return; } var rightOperand = operation.RightOperand; var leftOperand = operation.LeftOperand; if (rightOperand.Type is null || leftOperand.Type is null) { return; } if (rightOperand.Type.SpecialType != SpecialType.System_Boolean || leftOperand.Type.SpecialType != SpecialType.System_Boolean) { return; } var isOperatorEquals = operation.OperatorKind == BinaryOperatorKind.Equals; _syntaxFacts.GetPartsOfBinaryExpression(operation.Syntax, out _, out var operatorToken, out _); var properties = ImmutableDictionary.CreateBuilder<string, string?>(); if (TryGetLiteralValue(rightOperand) == isOperatorEquals) { properties.Add(RedundantEqualityConstants.RedundantSide, RedundantEqualityConstants.Right); } else if (TryGetLiteralValue(leftOperand) == isOperatorEquals) { properties.Add(RedundantEqualityConstants.RedundantSide, RedundantEqualityConstants.Left); } if (properties.Count == 1) { context.ReportDiagnostic(Diagnostic.Create(Descriptor, operatorToken.GetLocation(), additionalLocations: new[] { operation.Syntax.GetLocation() }, properties: properties.ToImmutable())); } return; static bool? TryGetLiteralValue(IOperation operand) { // Make sure we only simplify literals to avoid changing // something like the following example: // const bool Activated = true; ... if (state == Activated) if (operand.ConstantValue.HasValue && operand.Kind == OperationKind.Literal && operand.ConstantValue.Value is bool constValue) { return constValue; } return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.RemoveRedundantEquality { internal abstract class AbstractRemoveRedundantEqualityDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { private readonly ISyntaxFacts _syntaxFacts; protected AbstractRemoveRedundantEqualityDiagnosticAnalyzer(ISyntaxFacts syntaxFacts) : base(IDEDiagnosticIds.RemoveRedundantEqualityDiagnosticId, EnforceOnBuildValues.RemoveRedundantEquality, option: null, new LocalizableResourceString(nameof(AnalyzersResources.Remove_redundant_equality), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { _syntaxFacts = syntaxFacts; } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterOperationAction(AnalyzeBinaryOperator, OperationKind.BinaryOperator); private void AnalyzeBinaryOperator(OperationAnalysisContext context) { var operation = (IBinaryOperation)context.Operation; if (operation.OperatorMethod is not null) { // We shouldn't report diagnostic on overloaded operator as the behavior can change. return; } if (operation.OperatorKind is not (BinaryOperatorKind.Equals or BinaryOperatorKind.NotEquals)) { return; } if (!_syntaxFacts.IsBinaryExpression(operation.Syntax)) { return; } var rightOperand = operation.RightOperand; var leftOperand = operation.LeftOperand; if (rightOperand.Type is null || leftOperand.Type is null) { return; } if (rightOperand.Type.SpecialType != SpecialType.System_Boolean || leftOperand.Type.SpecialType != SpecialType.System_Boolean) { return; } var isOperatorEquals = operation.OperatorKind == BinaryOperatorKind.Equals; _syntaxFacts.GetPartsOfBinaryExpression(operation.Syntax, out _, out var operatorToken, out _); var properties = ImmutableDictionary.CreateBuilder<string, string?>(); if (TryGetLiteralValue(rightOperand) == isOperatorEquals) { properties.Add(RedundantEqualityConstants.RedundantSide, RedundantEqualityConstants.Right); } else if (TryGetLiteralValue(leftOperand) == isOperatorEquals) { properties.Add(RedundantEqualityConstants.RedundantSide, RedundantEqualityConstants.Left); } if (properties.Count == 1) { context.ReportDiagnostic(Diagnostic.Create(Descriptor, operatorToken.GetLocation(), additionalLocations: new[] { operation.Syntax.GetLocation() }, properties: properties.ToImmutable())); } return; static bool? TryGetLiteralValue(IOperation operand) { // Make sure we only simplify literals to avoid changing // something like the following example: // const bool Activated = true; ... if (state == Activated) if (operand.ConstantValue.HasValue && operand.Kind == OperationKind.Literal && operand.ConstantValue.Value is bool constValue) { return constValue; } return null; } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal class Matcher { /// <summary> /// Matcher equivalent to (m*) /// </summary> public static Matcher<T> Repeat<T>(Matcher<T> matcher) => Matcher<T>.Repeat(matcher); /// <summary> /// Matcher equivalent to (m+) /// </summary> public static Matcher<T> OneOrMore<T>(Matcher<T> matcher) => Matcher<T>.OneOrMore(matcher); /// <summary> /// Matcher equivalent to (m_1|m_2|...|m_n) /// </summary> public static Matcher<T> Choice<T>(params Matcher<T>[] matchers) => Matcher<T>.Choice(matchers); /// <summary> /// Matcher equivalent to (m_1 ... m_n) /// </summary> public static Matcher<T> Sequence<T>(params Matcher<T>[] matchers) => Matcher<T>.Sequence(matchers); /// <summary> /// Matcher that matches an element if the provide predicate returns true. /// </summary> public static Matcher<T> Single<T>(Func<T, bool> predicate, string description) => Matcher<T>.Single(predicate, description); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal class Matcher { /// <summary> /// Matcher equivalent to (m*) /// </summary> public static Matcher<T> Repeat<T>(Matcher<T> matcher) => Matcher<T>.Repeat(matcher); /// <summary> /// Matcher equivalent to (m+) /// </summary> public static Matcher<T> OneOrMore<T>(Matcher<T> matcher) => Matcher<T>.OneOrMore(matcher); /// <summary> /// Matcher equivalent to (m_1|m_2|...|m_n) /// </summary> public static Matcher<T> Choice<T>(params Matcher<T>[] matchers) => Matcher<T>.Choice(matchers); /// <summary> /// Matcher equivalent to (m_1 ... m_n) /// </summary> public static Matcher<T> Sequence<T>(params Matcher<T>[] matchers) => Matcher<T>.Sequence(matchers); /// <summary> /// Matcher that matches an element if the provide predicate returns true. /// </summary> public static Matcher<T> Single<T>(Func<T, bool> predicate, string description) => Matcher<T>.Single(predicate, description); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Dependencies/Collections/Microsoft.CodeAnalysis.Collections.shproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project> <PropertyGroup Label="Globals"> <ProjectGuid>e919dd77-34f8-4f57-8058-4d3ff4c2b241</ProjectGuid> <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion> </PropertyGroup> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props')" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props')" /> <PropertyGroup /> <Import Project="Microsoft.CodeAnalysis.Collections.projitems" Label="Shared" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets')" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project> <PropertyGroup Label="Globals"> <ProjectGuid>e919dd77-34f8-4f57-8058-4d3ff4c2b241</ProjectGuid> <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion> </PropertyGroup> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props')" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props')" /> <PropertyGroup /> <Import Project="Microsoft.CodeAnalysis.Collections.projitems" Label="Shared" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets')" /> </Project>
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/ToCountConverter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery { /// <summary> /// Provides a conversion to query.Count(). /// </summary> internal sealed class ToCountConverter : AbstractToMethodConverter { public ToCountConverter( ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo, ExpressionSyntax selectExpression, ExpressionSyntax modifyingExpression, SyntaxTrivia[] trivia) : base(forEachInfo, selectExpression, modifyingExpression, trivia) { } protected override string MethodName => nameof(Enumerable.Count); // Checks that the expression is "0". protected override bool CanReplaceInitialization( ExpressionSyntax expression, CancellationToken cancellationToken) => expression is LiteralExpressionSyntax literalExpression && literalExpression.Token.ValueText == "0"; /// Input: /// foreach(...) /// { /// ... /// ... /// counter++; /// } /// /// Output: /// counter += queryGenerated.Count(); protected override StatementSyntax CreateDefaultStatement(ExpressionSyntax queryOrLinqInvocationExpression, ExpressionSyntax expression) => SyntaxFactory.ExpressionStatement( SyntaxFactory.AssignmentExpression( SyntaxKind.AddAssignmentExpression, expression, CreateInvocationExpression(queryOrLinqInvocationExpression))); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery { /// <summary> /// Provides a conversion to query.Count(). /// </summary> internal sealed class ToCountConverter : AbstractToMethodConverter { public ToCountConverter( ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo, ExpressionSyntax selectExpression, ExpressionSyntax modifyingExpression, SyntaxTrivia[] trivia) : base(forEachInfo, selectExpression, modifyingExpression, trivia) { } protected override string MethodName => nameof(Enumerable.Count); // Checks that the expression is "0". protected override bool CanReplaceInitialization( ExpressionSyntax expression, CancellationToken cancellationToken) => expression is LiteralExpressionSyntax literalExpression && literalExpression.Token.ValueText == "0"; /// Input: /// foreach(...) /// { /// ... /// ... /// counter++; /// } /// /// Output: /// counter += queryGenerated.Count(); protected override StatementSyntax CreateDefaultStatement(ExpressionSyntax queryOrLinqInvocationExpression, ExpressionSyntax expression) => SyntaxFactory.ExpressionStatement( SyntaxFactory.AssignmentExpression( SyntaxKind.AddAssignmentExpression, expression, CreateInvocationExpression(queryOrLinqInvocationExpression))); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/TestUtilities/Classification/FormattedClassifications.Json.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis.Classification; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification { public static partial class FormattedClassifications { public static class Json { [DebuggerStepThrough] public static FormattedClassification Array(string value) => New(value, ClassificationTypeNames.JsonArray); [DebuggerStepThrough] public static FormattedClassification Object(string value) => New(value, ClassificationTypeNames.JsonObject); [DebuggerStepThrough] public static FormattedClassification PropertyName(string value) => New(value, ClassificationTypeNames.JsonPropertyName); [DebuggerStepThrough] public static FormattedClassification Punctuation(string value) => New(value, ClassificationTypeNames.JsonPunctuation); [DebuggerStepThrough] public static FormattedClassification Number(string value) => New(value, ClassificationTypeNames.JsonNumber); [DebuggerStepThrough] public static FormattedClassification Operator(string value) => New(value, ClassificationTypeNames.JsonOperator); [DebuggerStepThrough] public static FormattedClassification Keyword(string value) => New(value, ClassificationTypeNames.JsonKeyword); [DebuggerStepThrough] public static FormattedClassification ConstructorName(string value) => New(value, ClassificationTypeNames.JsonConstructorName); [DebuggerStepThrough] public static FormattedClassification Comment(string value) => New(value, ClassificationTypeNames.JsonComment); [DebuggerStepThrough] public static FormattedClassification Text(string value) => New(value, ClassificationTypeNames.JsonText); [DebuggerStepThrough] public static FormattedClassification String(string value) => New(value, ClassificationTypeNames.JsonString); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis.Classification; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification { public static partial class FormattedClassifications { public static class Json { [DebuggerStepThrough] public static FormattedClassification Array(string value) => New(value, ClassificationTypeNames.JsonArray); [DebuggerStepThrough] public static FormattedClassification Object(string value) => New(value, ClassificationTypeNames.JsonObject); [DebuggerStepThrough] public static FormattedClassification PropertyName(string value) => New(value, ClassificationTypeNames.JsonPropertyName); [DebuggerStepThrough] public static FormattedClassification Punctuation(string value) => New(value, ClassificationTypeNames.JsonPunctuation); [DebuggerStepThrough] public static FormattedClassification Number(string value) => New(value, ClassificationTypeNames.JsonNumber); [DebuggerStepThrough] public static FormattedClassification Operator(string value) => New(value, ClassificationTypeNames.JsonOperator); [DebuggerStepThrough] public static FormattedClassification Keyword(string value) => New(value, ClassificationTypeNames.JsonKeyword); [DebuggerStepThrough] public static FormattedClassification ConstructorName(string value) => New(value, ClassificationTypeNames.JsonConstructorName); [DebuggerStepThrough] public static FormattedClassification Comment(string value) => New(value, ClassificationTypeNames.JsonComment); [DebuggerStepThrough] public static FormattedClassification Text(string value) => New(value, ClassificationTypeNames.JsonText); [DebuggerStepThrough] public static FormattedClassification String(string value) => New(value, ClassificationTypeNames.JsonString); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/Collections/ArrayBuilderExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal static class ArrayBuilderExtensions { public static bool Any<T>(this ArrayBuilder<T> builder, Func<T, bool> predicate) { foreach (var item in builder) { if (predicate(item)) { return true; } } return false; } public static bool Any<T, A>(this ArrayBuilder<T> builder, Func<T, A, bool> predicate, A arg) { foreach (var item in builder) { if (predicate(item, arg)) { return true; } } return false; } public static bool All<T>(this ArrayBuilder<T> builder, Func<T, bool> predicate) { foreach (var item in builder) { if (!predicate(item)) { return false; } } return true; } public static bool All<T, A>(this ArrayBuilder<T> builder, Func<T, A, bool> predicate, A arg) { foreach (var item in builder) { if (!predicate(item, arg)) { return false; } } return true; } /// <summary> /// Maps an array builder to immutable array. /// </summary> /// <typeparam name="TItem"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="items">The array to map</param> /// <param name="map">The mapping delegate</param> /// <returns>If the items's length is 0, this will return an empty immutable array</returns> public static ImmutableArray<TResult> SelectAsArray<TItem, TResult>(this ArrayBuilder<TItem> items, Func<TItem, TResult> map) { switch (items.Count) { case 0: return ImmutableArray<TResult>.Empty; case 1: return ImmutableArray.Create(map(items[0])); case 2: return ImmutableArray.Create(map(items[0]), map(items[1])); case 3: return ImmutableArray.Create(map(items[0]), map(items[1]), map(items[2])); case 4: return ImmutableArray.Create(map(items[0]), map(items[1]), map(items[2]), map(items[3])); default: var builder = ArrayBuilder<TResult>.GetInstance(items.Count); foreach (var item in items) { builder.Add(map(item)); } return builder.ToImmutableAndFree(); } } /// <summary> /// Maps an array builder to immutable array. /// </summary> /// <typeparam name="TItem"></typeparam> /// <typeparam name="TArg"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="items">The sequence to map</param> /// <param name="map">The mapping delegate</param> /// <param name="arg">The extra input used by mapping delegate</param> /// <returns>If the items's length is 0, this will return an empty immutable array.</returns> public static ImmutableArray<TResult> SelectAsArray<TItem, TArg, TResult>(this ArrayBuilder<TItem> items, Func<TItem, TArg, TResult> map, TArg arg) { switch (items.Count) { case 0: return ImmutableArray<TResult>.Empty; case 1: return ImmutableArray.Create(map(items[0], arg)); case 2: return ImmutableArray.Create(map(items[0], arg), map(items[1], arg)); case 3: return ImmutableArray.Create(map(items[0], arg), map(items[1], arg), map(items[2], arg)); case 4: return ImmutableArray.Create(map(items[0], arg), map(items[1], arg), map(items[2], arg), map(items[3], arg)); default: var builder = ArrayBuilder<TResult>.GetInstance(items.Count); foreach (var item in items) { builder.Add(map(item, arg)); } return builder.ToImmutableAndFree(); } } /// <summary> /// Maps an array builder to immutable array. /// </summary> /// <typeparam name="TItem"></typeparam> /// <typeparam name="TArg"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="items">The sequence to map</param> /// <param name="map">The mapping delegate</param> /// <param name="arg">The extra input used by mapping delegate</param> /// <returns>If the items's length is 0, this will return an empty immutable array.</returns> public static ImmutableArray<TResult> SelectAsArrayWithIndex<TItem, TArg, TResult>(this ArrayBuilder<TItem> items, Func<TItem, int, TArg, TResult> map, TArg arg) { switch (items.Count) { case 0: return ImmutableArray<TResult>.Empty; case 1: return ImmutableArray.Create(map(items[0], 0, arg)); case 2: return ImmutableArray.Create(map(items[0], 0, arg), map(items[1], 1, arg)); case 3: return ImmutableArray.Create(map(items[0], 0, arg), map(items[1], 1, arg), map(items[2], 2, arg)); case 4: return ImmutableArray.Create(map(items[0], 0, arg), map(items[1], 1, arg), map(items[2], 2, arg), map(items[3], 3, arg)); default: var builder = ArrayBuilder<TResult>.GetInstance(items.Count); foreach (var item in items) { builder.Add(map(item, builder.Count, arg)); } return builder.ToImmutableAndFree(); } } public static void AddOptional<T>(this ArrayBuilder<T> builder, T? item) where T : class { if (item != null) { builder.Add(item); } } // The following extension methods allow an ArrayBuilder to be used as a stack. // Note that the order of an IEnumerable from a List is from bottom to top of stack. An IEnumerable // from the framework Stack is from top to bottom. public static void Push<T>(this ArrayBuilder<T> builder, T e) { builder.Add(e); } public static T Pop<T>(this ArrayBuilder<T> builder) { var e = builder.Peek(); builder.RemoveAt(builder.Count - 1); return e; } public static bool TryPop<T>(this ArrayBuilder<T> builder, [MaybeNullWhen(false)] out T result) { if (builder.Count > 0) { result = builder.Pop(); return true; } result = default; return false; } public static T Peek<T>(this ArrayBuilder<T> builder) { return builder[builder.Count - 1]; } public static ImmutableArray<T> ToImmutableOrEmptyAndFree<T>(this ArrayBuilder<T>? builder) { return builder?.ToImmutableAndFree() ?? ImmutableArray<T>.Empty; } public static void AddIfNotNull<T>(this ArrayBuilder<T> builder, T? value) where T : struct { if (value != null) { builder.Add(value.Value); } } public static void AddIfNotNull<T>(this ArrayBuilder<T> builder, T? value) where T : class { if (value != null) { builder.Add(value); } } #nullable disable public static void FreeAll<T>(this ArrayBuilder<T> builder, Func<T, ArrayBuilder<T>> getNested) { foreach (var item in builder) { getNested(item)?.FreeAll(getNested); } builder.Free(); } #nullable enable } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal static class ArrayBuilderExtensions { public static bool Any<T>(this ArrayBuilder<T> builder, Func<T, bool> predicate) { foreach (var item in builder) { if (predicate(item)) { return true; } } return false; } public static bool Any<T, A>(this ArrayBuilder<T> builder, Func<T, A, bool> predicate, A arg) { foreach (var item in builder) { if (predicate(item, arg)) { return true; } } return false; } public static bool All<T>(this ArrayBuilder<T> builder, Func<T, bool> predicate) { foreach (var item in builder) { if (!predicate(item)) { return false; } } return true; } public static bool All<T, A>(this ArrayBuilder<T> builder, Func<T, A, bool> predicate, A arg) { foreach (var item in builder) { if (!predicate(item, arg)) { return false; } } return true; } /// <summary> /// Maps an array builder to immutable array. /// </summary> /// <typeparam name="TItem"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="items">The array to map</param> /// <param name="map">The mapping delegate</param> /// <returns>If the items's length is 0, this will return an empty immutable array</returns> public static ImmutableArray<TResult> SelectAsArray<TItem, TResult>(this ArrayBuilder<TItem> items, Func<TItem, TResult> map) { switch (items.Count) { case 0: return ImmutableArray<TResult>.Empty; case 1: return ImmutableArray.Create(map(items[0])); case 2: return ImmutableArray.Create(map(items[0]), map(items[1])); case 3: return ImmutableArray.Create(map(items[0]), map(items[1]), map(items[2])); case 4: return ImmutableArray.Create(map(items[0]), map(items[1]), map(items[2]), map(items[3])); default: var builder = ArrayBuilder<TResult>.GetInstance(items.Count); foreach (var item in items) { builder.Add(map(item)); } return builder.ToImmutableAndFree(); } } /// <summary> /// Maps an array builder to immutable array. /// </summary> /// <typeparam name="TItem"></typeparam> /// <typeparam name="TArg"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="items">The sequence to map</param> /// <param name="map">The mapping delegate</param> /// <param name="arg">The extra input used by mapping delegate</param> /// <returns>If the items's length is 0, this will return an empty immutable array.</returns> public static ImmutableArray<TResult> SelectAsArray<TItem, TArg, TResult>(this ArrayBuilder<TItem> items, Func<TItem, TArg, TResult> map, TArg arg) { switch (items.Count) { case 0: return ImmutableArray<TResult>.Empty; case 1: return ImmutableArray.Create(map(items[0], arg)); case 2: return ImmutableArray.Create(map(items[0], arg), map(items[1], arg)); case 3: return ImmutableArray.Create(map(items[0], arg), map(items[1], arg), map(items[2], arg)); case 4: return ImmutableArray.Create(map(items[0], arg), map(items[1], arg), map(items[2], arg), map(items[3], arg)); default: var builder = ArrayBuilder<TResult>.GetInstance(items.Count); foreach (var item in items) { builder.Add(map(item, arg)); } return builder.ToImmutableAndFree(); } } /// <summary> /// Maps an array builder to immutable array. /// </summary> /// <typeparam name="TItem"></typeparam> /// <typeparam name="TArg"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="items">The sequence to map</param> /// <param name="map">The mapping delegate</param> /// <param name="arg">The extra input used by mapping delegate</param> /// <returns>If the items's length is 0, this will return an empty immutable array.</returns> public static ImmutableArray<TResult> SelectAsArrayWithIndex<TItem, TArg, TResult>(this ArrayBuilder<TItem> items, Func<TItem, int, TArg, TResult> map, TArg arg) { switch (items.Count) { case 0: return ImmutableArray<TResult>.Empty; case 1: return ImmutableArray.Create(map(items[0], 0, arg)); case 2: return ImmutableArray.Create(map(items[0], 0, arg), map(items[1], 1, arg)); case 3: return ImmutableArray.Create(map(items[0], 0, arg), map(items[1], 1, arg), map(items[2], 2, arg)); case 4: return ImmutableArray.Create(map(items[0], 0, arg), map(items[1], 1, arg), map(items[2], 2, arg), map(items[3], 3, arg)); default: var builder = ArrayBuilder<TResult>.GetInstance(items.Count); foreach (var item in items) { builder.Add(map(item, builder.Count, arg)); } return builder.ToImmutableAndFree(); } } public static void AddOptional<T>(this ArrayBuilder<T> builder, T? item) where T : class { if (item != null) { builder.Add(item); } } // The following extension methods allow an ArrayBuilder to be used as a stack. // Note that the order of an IEnumerable from a List is from bottom to top of stack. An IEnumerable // from the framework Stack is from top to bottom. public static void Push<T>(this ArrayBuilder<T> builder, T e) { builder.Add(e); } public static T Pop<T>(this ArrayBuilder<T> builder) { var e = builder.Peek(); builder.RemoveAt(builder.Count - 1); return e; } public static bool TryPop<T>(this ArrayBuilder<T> builder, [MaybeNullWhen(false)] out T result) { if (builder.Count > 0) { result = builder.Pop(); return true; } result = default; return false; } public static T Peek<T>(this ArrayBuilder<T> builder) { return builder[builder.Count - 1]; } public static ImmutableArray<T> ToImmutableOrEmptyAndFree<T>(this ArrayBuilder<T>? builder) { return builder?.ToImmutableAndFree() ?? ImmutableArray<T>.Empty; } public static void AddIfNotNull<T>(this ArrayBuilder<T> builder, T? value) where T : struct { if (value != null) { builder.Add(value.Value); } } public static void AddIfNotNull<T>(this ArrayBuilder<T> builder, T? value) where T : class { if (value != null) { builder.Add(value); } } #nullable disable public static void FreeAll<T>(this ArrayBuilder<T> builder, Func<T, ArrayBuilder<T>> getNested) { foreach (var item in builder) { getNested(item)?.FreeAll(getNested); } builder.Free(); } #nullable enable } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.DelegateTemplateSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { internal sealed class AnonymousDelegateTemplateSymbol : AnonymousTypeOrDelegateTemplateSymbol { private readonly ImmutableArray<Symbol> _members; /// <summary> /// True if any of the delegate parameter types or return type are /// fixed types rather than type parameters. /// </summary> internal readonly bool HasFixedTypes; /// <summary> /// A delegate type where the parameter types and return type /// of the delegate signature are type parameters. /// </summary> internal AnonymousDelegateTemplateSymbol( AnonymousTypeManager manager, string name, TypeSymbol objectType, TypeSymbol intPtrType, TypeSymbol? voidReturnTypeOpt, int parameterCount, RefKindVector refKinds) : base(manager, Location.None) // Location is not needed since NameAndIndex is set explicitly below. { Debug.Assert(refKinds.IsNull || parameterCount == refKinds.Capacity - (voidReturnTypeOpt is { } ? 0 : 1)); HasFixedTypes = false; TypeParameters = createTypeParameters(this, parameterCount, returnsVoid: voidReturnTypeOpt is { }); NameAndIndex = new NameAndIndex(name, index: 0); var constructor = new SynthesizedDelegateConstructor(this, objectType, intPtrType); // https://github.com/dotnet/roslyn/issues/56808: Synthesized delegates should include BeginInvoke() and EndInvoke(). var invokeMethod = createInvokeMethod(this, refKinds, voidReturnTypeOpt); _members = ImmutableArray.Create<Symbol>(constructor, invokeMethod); static SynthesizedDelegateInvokeMethod createInvokeMethod(AnonymousDelegateTemplateSymbol containingType, RefKindVector refKinds, TypeSymbol? voidReturnTypeOpt) { var typeParams = containingType.TypeParameters; int parameterCount = typeParams.Length - (voidReturnTypeOpt is null ? 1 : 0); var parameters = ArrayBuilder<(TypeWithAnnotations, RefKind, DeclarationScope)>.GetInstance(parameterCount); for (int i = 0; i < parameterCount; i++) { parameters.Add((TypeWithAnnotations.Create(typeParams[i]), refKinds.IsNull ? RefKind.None : refKinds[i], DeclarationScope.Unscoped)); } // if we are given Void type the method returns Void, otherwise its return type is the last type parameter of the delegate: var returnType = TypeWithAnnotations.Create(voidReturnTypeOpt ?? typeParams[parameterCount]); var returnRefKind = (refKinds.IsNull || voidReturnTypeOpt is { }) ? RefKind.None : refKinds[parameterCount]; var method = new SynthesizedDelegateInvokeMethod(containingType, parameters, returnType, returnRefKind); parameters.Free(); return method; } static ImmutableArray<TypeParameterSymbol> createTypeParameters(AnonymousDelegateTemplateSymbol containingType, int parameterCount, bool returnsVoid) { var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(parameterCount + (returnsVoid ? 0 : 1)); for (int i = 0; i < parameterCount; i++) { typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(containingType, i, "T" + (i + 1))); } if (!returnsVoid) { typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(containingType, parameterCount, "TResult")); } return typeParameters.ToImmutableAndFree(); } } /// <summary> /// A delegate type where at least one of the parameter types or return type /// of the delegate signature is a fixed type not a type parameter. /// </summary> internal AnonymousDelegateTemplateSymbol(AnonymousTypeManager manager, AnonymousTypeDescriptor typeDescr, ImmutableArray<TypeParameterSymbol> typeParametersToSubstitute) : base(manager, typeDescr.Location) { // AnonymousTypeOrDelegateComparer requires an actual location. Debug.Assert(SmallestLocation != null); Debug.Assert(SmallestLocation != Location.None); HasFixedTypes = true; TypeMap typeMap; int typeParameterCount = typeParametersToSubstitute.Length; if (typeParameterCount == 0) { TypeParameters = ImmutableArray<TypeParameterSymbol>.Empty; typeMap = TypeMap.Empty; } else { var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(typeParameterCount); for (int i = 0; i < typeParameterCount; i++) { typeParameters.Add(new AnonymousTypeParameterSymbol(this, i, "T" + (i + 1))); } TypeParameters = typeParameters.ToImmutableAndFree(); typeMap = new TypeMap(typeParametersToSubstitute, TypeParameters, allowAlpha: true); } var constructor = new SynthesizedDelegateConstructor(this, manager.System_Object, manager.System_IntPtr); // https://github.com/dotnet/roslyn/issues/56808: Synthesized delegates should include BeginInvoke() and EndInvoke(). var invokeMethod = createInvokeMethod(this, typeDescr.Fields, typeMap); _members = ImmutableArray.Create<Symbol>(constructor, invokeMethod); static SynthesizedDelegateInvokeMethod createInvokeMethod( AnonymousDelegateTemplateSymbol containingType, ImmutableArray<AnonymousTypeField> fields, TypeMap typeMap) { var parameterCount = fields.Length - 1; var parameters = ArrayBuilder<(TypeWithAnnotations, RefKind, DeclarationScope)>.GetInstance(parameterCount); for (int i = 0; i < parameterCount; i++) { var field = fields[i]; parameters.Add((typeMap.SubstituteType(field.Type), field.RefKind, field.Scope)); } var returnParameter = fields[^1]; var returnType = typeMap.SubstituteType(returnParameter.Type); var returnRefKind = returnParameter.RefKind; var method = new SynthesizedDelegateInvokeMethod(containingType, parameters, returnType, returnRefKind); parameters.Free(); return method; } } // AnonymousTypeOrDelegateComparer should not be calling this property for delegate // types since AnonymousTypeOrDelegateComparer is only used during emit and we // should only be emitting delegate types inferred from distinct locations in source. internal override string TypeDescriptorKey => throw new System.NotImplementedException(); public override TypeKind TypeKind => TypeKind.Delegate; public override IEnumerable<string> MemberNames => GetMembers().SelectAsArray(member => member.Name); internal override bool HasDeclaredRequiredMembers => false; public override ImmutableArray<Symbol> GetMembers() => _members; public override ImmutableArray<Symbol> GetMembers(string name) => GetMembers().WhereAsArray((member, name) => member.Name == name, name); internal override IEnumerable<FieldSymbol> GetFieldsToEmit() => SpecializedCollections.EmptyEnumerable<FieldSymbol>(); internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() => ImmutableArray<NamedTypeSymbol>.Empty; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol>? basesBeingResolved = null) => ImmutableArray<NamedTypeSymbol>.Empty; internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => Manager.System_MulticastDelegate; public override ImmutableArray<TypeParameterSymbol> TypeParameters { get; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = ContainingSymbol.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { internal sealed class AnonymousDelegateTemplateSymbol : AnonymousTypeOrDelegateTemplateSymbol { private readonly ImmutableArray<Symbol> _members; /// <summary> /// True if any of the delegate parameter types or return type are /// fixed types rather than type parameters. /// </summary> internal readonly bool HasFixedTypes; /// <summary> /// A delegate type where the parameter types and return type /// of the delegate signature are type parameters. /// </summary> internal AnonymousDelegateTemplateSymbol( AnonymousTypeManager manager, string name, TypeSymbol objectType, TypeSymbol intPtrType, TypeSymbol? voidReturnTypeOpt, int parameterCount, RefKindVector refKinds) : base(manager, Location.None) // Location is not needed since NameAndIndex is set explicitly below. { Debug.Assert(refKinds.IsNull || parameterCount == refKinds.Capacity - (voidReturnTypeOpt is { } ? 0 : 1)); HasFixedTypes = false; TypeParameters = createTypeParameters(this, parameterCount, returnsVoid: voidReturnTypeOpt is { }); NameAndIndex = new NameAndIndex(name, index: 0); var constructor = new SynthesizedDelegateConstructor(this, objectType, intPtrType); // https://github.com/dotnet/roslyn/issues/56808: Synthesized delegates should include BeginInvoke() and EndInvoke(). var invokeMethod = createInvokeMethod(this, refKinds, voidReturnTypeOpt); _members = ImmutableArray.Create<Symbol>(constructor, invokeMethod); static SynthesizedDelegateInvokeMethod createInvokeMethod(AnonymousDelegateTemplateSymbol containingType, RefKindVector refKinds, TypeSymbol? voidReturnTypeOpt) { var typeParams = containingType.TypeParameters; int parameterCount = typeParams.Length - (voidReturnTypeOpt is null ? 1 : 0); var parameters = ArrayBuilder<(TypeWithAnnotations, RefKind, DeclarationScope)>.GetInstance(parameterCount); for (int i = 0; i < parameterCount; i++) { parameters.Add((TypeWithAnnotations.Create(typeParams[i]), refKinds.IsNull ? RefKind.None : refKinds[i], DeclarationScope.Unscoped)); } // if we are given Void type the method returns Void, otherwise its return type is the last type parameter of the delegate: var returnType = TypeWithAnnotations.Create(voidReturnTypeOpt ?? typeParams[parameterCount]); var returnRefKind = (refKinds.IsNull || voidReturnTypeOpt is { }) ? RefKind.None : refKinds[parameterCount]; var method = new SynthesizedDelegateInvokeMethod(containingType, parameters, returnType, returnRefKind); parameters.Free(); return method; } static ImmutableArray<TypeParameterSymbol> createTypeParameters(AnonymousDelegateTemplateSymbol containingType, int parameterCount, bool returnsVoid) { var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(parameterCount + (returnsVoid ? 0 : 1)); for (int i = 0; i < parameterCount; i++) { typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(containingType, i, "T" + (i + 1))); } if (!returnsVoid) { typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(containingType, parameterCount, "TResult")); } return typeParameters.ToImmutableAndFree(); } } /// <summary> /// A delegate type where at least one of the parameter types or return type /// of the delegate signature is a fixed type not a type parameter. /// </summary> internal AnonymousDelegateTemplateSymbol(AnonymousTypeManager manager, AnonymousTypeDescriptor typeDescr, ImmutableArray<TypeParameterSymbol> typeParametersToSubstitute) : base(manager, typeDescr.Location) { // AnonymousTypeOrDelegateComparer requires an actual location. Debug.Assert(SmallestLocation != null); Debug.Assert(SmallestLocation != Location.None); HasFixedTypes = true; TypeMap typeMap; int typeParameterCount = typeParametersToSubstitute.Length; if (typeParameterCount == 0) { TypeParameters = ImmutableArray<TypeParameterSymbol>.Empty; typeMap = TypeMap.Empty; } else { var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(typeParameterCount); for (int i = 0; i < typeParameterCount; i++) { typeParameters.Add(new AnonymousTypeParameterSymbol(this, i, "T" + (i + 1))); } TypeParameters = typeParameters.ToImmutableAndFree(); typeMap = new TypeMap(typeParametersToSubstitute, TypeParameters, allowAlpha: true); } var constructor = new SynthesizedDelegateConstructor(this, manager.System_Object, manager.System_IntPtr); // https://github.com/dotnet/roslyn/issues/56808: Synthesized delegates should include BeginInvoke() and EndInvoke(). var invokeMethod = createInvokeMethod(this, typeDescr.Fields, typeMap); _members = ImmutableArray.Create<Symbol>(constructor, invokeMethod); static SynthesizedDelegateInvokeMethod createInvokeMethod( AnonymousDelegateTemplateSymbol containingType, ImmutableArray<AnonymousTypeField> fields, TypeMap typeMap) { var parameterCount = fields.Length - 1; var parameters = ArrayBuilder<(TypeWithAnnotations, RefKind, DeclarationScope)>.GetInstance(parameterCount); for (int i = 0; i < parameterCount; i++) { var field = fields[i]; parameters.Add((typeMap.SubstituteType(field.Type), field.RefKind, field.Scope)); } var returnParameter = fields[^1]; var returnType = typeMap.SubstituteType(returnParameter.Type); var returnRefKind = returnParameter.RefKind; var method = new SynthesizedDelegateInvokeMethod(containingType, parameters, returnType, returnRefKind); parameters.Free(); return method; } } // AnonymousTypeOrDelegateComparer should not be calling this property for delegate // types since AnonymousTypeOrDelegateComparer is only used during emit and we // should only be emitting delegate types inferred from distinct locations in source. internal override string TypeDescriptorKey => throw new System.NotImplementedException(); public override TypeKind TypeKind => TypeKind.Delegate; public override IEnumerable<string> MemberNames => GetMembers().SelectAsArray(member => member.Name); internal override bool HasDeclaredRequiredMembers => false; public override ImmutableArray<Symbol> GetMembers() => _members; public override ImmutableArray<Symbol> GetMembers(string name) => GetMembers().WhereAsArray((member, name) => member.Name == name, name); internal override IEnumerable<FieldSymbol> GetFieldsToEmit() => SpecializedCollections.EmptyEnumerable<FieldSymbol>(); internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() => ImmutableArray<NamedTypeSymbol>.Empty; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol>? basesBeingResolved = null) => ImmutableArray<NamedTypeSymbol>.Empty; internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => Manager.System_MulticastDelegate; public override ImmutableArray<TypeParameterSymbol> TypeParameters { get; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = ContainingSymbol.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/ExternalAccess/LegacyCodeAnalysis/Api/ILegacyCodeAnalysisVisualStudioDiagnosticListSuppressionStateServiceAccessor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.LegacyCodeAnalysis.Api { internal interface ILegacyCodeAnalysisVisualStudioDiagnosticListSuppressionStateServiceAccessor { bool CanSuppressSelectedEntries { get; } bool CanSuppressSelectedEntriesInSource { get; } bool CanSuppressSelectedEntriesInSuppressionFiles { get; } bool CanRemoveSuppressionsSelectedEntries { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.LegacyCodeAnalysis.Api { internal interface ILegacyCodeAnalysisVisualStudioDiagnosticListSuppressionStateServiceAccessor { bool CanSuppressSelectedEntries { get; } bool CanSuppressSelectedEntriesInSource { get; } bool CanSuppressSelectedEntriesInSuppressionFiles { get; } bool CanRemoveSuppressionsSelectedEntries { get; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/Core/Portable/EditAndContinue/ActiveStatementId.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.EditAndContinue { internal readonly struct ActiveStatementId { public readonly DocumentId DocumentId; public readonly int Ordinal; public ActiveStatementId(DocumentId documentId, int ordinal) { DocumentId = documentId; Ordinal = ordinal; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.EditAndContinue { internal readonly struct ActiveStatementId { public readonly DocumentId DocumentId; public readonly int Ordinal; public ActiveStatementId(DocumentId documentId, int ordinal) { DocumentId = documentId; Ordinal = ordinal; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/Test/Emit/Emit/DynamicAnalysis/DynamicAnalysisResourceTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Reflection.PortableExecutable Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.DynamicAnalysis.UnitTests Public Class DynamicAnalysisResourceTests Inherits BasicTestBase ReadOnly InstrumentationHelperSource As XElement = <file name="a.vb"> <![CDATA[ Namespace Microsoft.CodeAnalysis.Runtime Public Class Instrumentation Public Shared Function CreatePayload(mvid As System.Guid, methodToken As Integer, fileIndex As Integer, ByRef payload As Boolean(), payloadLength As Integer) As Boolean() Return payload End Function Public Shared Function CreatePayload(mvid As System.Guid, methodToken As Integer, fileIndices As Integer(), ByRef payload As Boolean(), payloadLength As Integer) As Boolean() Return payload End Function Public Shared Sub FlushPayload() End Sub End Class End Namespace ]]> </file> ReadOnly ExampleSource As XElement = <file name="c.vb"> <![CDATA[ Imports System Public Class C Public Shared Sub Main() Console.WriteLine(123) Console.WriteLine(123) End Sub Public Shared Function Fred As Integer Return 3 End Function Public Shared Function Barney(x As Integer) Return x End Function Public Shared Property Wilma As Integer Get Return 12 End Get Set End Set End Property Public Shared ReadOnly Property Betty As Integer End Class ]]> </file> <Fact> Public Sub TestSpansPresentInResource() Dim source As XElement = <compilation></compilation> source.Add(ExampleSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") VerifyDocuments(reader, reader.Documents, "'c.vb' 1A-10-00-3A-D1-71-8C-BD-53-CC-9D-9C-5D-53-5D-7F-8C-70-89-0F (SHA1)", "'a.vb' C2-D0-74-6D-08-69-59-85-2E-64-93-75-AE-DD-55-73-C3-C1-48-3A (SHA1)") Assert.Equal(12, reader.Methods.Length) Dim sourceLines As String() = ExampleSource.ToString().Split(vbLf(0)) VerifySpans(reader, reader.Methods(1), sourceLines, ' Main New SpanResult(3, 4, 6, 11, "Public Shared Sub Main()"), New SpanResult(4, 8, 4, 30, "Console.WriteLine(123)"), New SpanResult(5, 8, 5, 30, "Console.WriteLine(123)")) VerifySpans(reader, reader.Methods(2), sourceLines, ' Fred get New SpanResult(8, 4, 10, 16, "Public Shared Function Fred As Integer"), New SpanResult(9, 8, 9, 16, "Return 3")) VerifySpans(reader, reader.Methods(3), sourceLines, ' Barney New SpanResult(12, 4, 14, 16, "Public Shared Function Barney(x As Integer)"), New SpanResult(13, 8, 13, 16, "Return x")) VerifySpans(reader, reader.Methods(4), sourceLines, ' Wilma get New SpanResult(17, 8, 19, 15, "Get"), New SpanResult(18, 12, 18, 21, "Return 12")) VerifySpans(reader, reader.Methods(5), sourceLines, ' Wilma set New SpanResult(20, 8, 21, 15, "Set")) VerifySpans(reader, reader.Methods(6)) ' Betty get -- VB does not supply a valid syntax node for the body. VerifySpans(reader, reader.Methods(7)) End Sub <Fact> Public Sub TestLoopSpans() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Function TestIf(a As Boolean, b As Boolean) As Integer Dim x As Integer = 0 If a Then x += 1 Else x += 10 If a Then x += 1 ElseIf a AndAlso b Then x += 10 Else x += 100 End If If b Then x += 1 End If If a AndAlso b Then x += 10 End If Return x End Function Function TestDoLoops() As Integer Dim x As Integer = 100 While x < 150 x += 1 End While While x < 150 x += 1 End While Do While x < 200 x += 1 Loop Do Until x = 200 x += 1 Loop Do x += 1 Loop While x < 200 Do x += 1 Loop Until x = 202 Do Return x Loop End Function Sub TestForLoops() Dim x As Integer = 0 Dim y As Integer = 10 Dim z As Integer = 3 For a As Integer = x To y Step z z += 1 Next For b As Integer = 1 To 10 z += 1 Next For Each c As Integer In {x, y, z} z += 1 Next End Sub Public Sub Main(args As String()) TestIf(False, False) TestIf(True, False) TestDoLoops() TestForLoops() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") VerifyDocuments(reader, reader.Documents, "'c.vb' 55-FA-D1-46-BA-6F-EC-77-0E-02-1A-A6-BC-62-21-F7-E3-31-4F-2C (SHA1)", "'a.vb' C2-D0-74-6D-08-69-59-85-2E-64-93-75-AE-DD-55-73-C3-C1-48-3A (SHA1)") Dim sourceLines As String() = testSource.ToString().Split(vbLf(0)) VerifySpans(reader, reader.Methods(0), sourceLines, ' TestIf New SpanResult(1, 4, 18, 16, "Function TestIf(a As Boolean, b As Boolean) As Integer"), New SpanResult(2, 27, 2, 28, "0"), New SpanResult(3, 18, 3, 24, "x += 1"), New SpanResult(3, 30, 3, 37, "x += 10"), New SpanResult(3, 11, 3, 12, "a"), New SpanResult(5, 12, 5, 18, "x += 1"), New SpanResult(7, 12, 7, 19, "x += 10"), New SpanResult(9, 12, 9, 20, "x += 100"), New SpanResult(6, 15, 6, 26, "a AndAlso b"), New SpanResult(4, 11, 4, 12, "a"), New SpanResult(12, 12, 12, 18, "x += 1"), New SpanResult(11, 11, 11, 12, "b"), New SpanResult(15, 12, 15, 19, "x += 10"), New SpanResult(14, 11, 14, 22, "a AndAlso b"), New SpanResult(17, 8, 17, 16, "Return x")) VerifySpans(reader, reader.Methods(1), sourceLines, ' TestDoLoops New SpanResult(20, 4, 43, 16, "Function TestDoLoops() As Integer"), New SpanResult(21, 27, 21, 30, "100"), New SpanResult(23, 12, 23, 18, "x += 1"), New SpanResult(22, 14, 22, 21, "x < 150"), New SpanResult(26, 12, 26, 18, "x += 1"), New SpanResult(25, 14, 25, 21, "x < 150"), New SpanResult(29, 12, 29, 18, "x += 1"), New SpanResult(28, 17, 28, 24, "x < 200"), New SpanResult(32, 12, 32, 18, "x += 1"), New SpanResult(31, 17, 31, 24, "x = 200"), New SpanResult(35, 12, 35, 18, "x += 1"), New SpanResult(36, 19, 36, 26, "x < 200"), New SpanResult(38, 12, 38, 18, "x += 1"), New SpanResult(39, 19, 39, 26, "x = 202"), New SpanResult(41, 12, 41, 20, "Return x")) VerifySpans(reader, reader.Methods(2), sourceLines, ' TestForLoops New SpanResult(45, 4, 58, 11, "Sub TestForLoops()"), New SpanResult(46, 27, 46, 28, "0"), New SpanResult(47, 27, 47, 29, "10"), New SpanResult(48, 27, 48, 28, "3"), New SpanResult(49, 27, 49, 28, "x"), New SpanResult(50, 12, 50, 18, "z += 1"), New SpanResult(52, 27, 52, 28, "1"), New SpanResult(53, 12, 53, 18, "z += 1"), New SpanResult(55, 33, 55, 42, "{x, y, z}"), New SpanResult(56, 12, 56, 18, "z += 1")) End Sub <Fact> Public Sub TestTryAndSelect() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TryAndSelect() Dim y As Integer = 0 Try Try For x As Integer = 0 To 10 Select Case x Case 0 y += 1 Case 1 Throw New System.Exception() Case >= 2 y += 1 Case Else y += 1 End Select Next Catch e As System.Exception y += 1 End Try Finally y += 1 End Try End Sub Public Sub Main(args As String()) TryAndSelect() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") VerifyDocuments(reader, reader.Documents, "'c.vb' 36-B0-C2-29-F1-DC-B1-63-93-45-31-11-58-6C-5A-46-89-A1-42-34 (SHA1)", "'a.vb' C2-D0-74-6D-08-69-59-85-2E-64-93-75-AE-DD-55-73-C3-C1-48-3A (SHA1)") Dim sourceLines As String() = testSource.ToString().Split(vbLf(0)) VerifySpans(reader, reader.Methods(0), sourceLines, ' TryAndSelect New SpanResult(1, 4, 23, 11, "Sub TryAndSelect()"), New SpanResult(2, 27, 2, 28, "0"), New SpanResult(5, 35, 5, 36, "0"), New SpanResult(6, 32, 6, 33, "x"), New SpanResult(8, 28, 8, 34, "y += 1"), New SpanResult(10, 28, 10, 56, "Throw New System.Exception()"), New SpanResult(12, 28, 12, 34, "y += 1"), New SpanResult(14, 28, 14, 34, "y += 1"), New SpanResult(18, 16, 18, 22, "y += 1"), New SpanResult(21, 12, 21, 18, "y += 1")) End Sub <Fact> Public Sub TestBranches() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub Branches() Dim y As Integer = 0 MyLabel: Do Exit Do y += 1 Loop For x As Integer = 1 To 10 Exit For y += 1 Next Try Exit Try y += 1 Catch ex As System.Exception End Try Select Case y Case 0 Exit Select y += 0 End Select If y = 0 Then Exit Sub End If GoTo MyLabel End Sub Public Sub Main(args As String()) Branches() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") VerifyDocuments(reader, reader.Documents, "'c.vb' 1B-06-B9-C5-D5-D3-AD-EE-8A-D3-31-8F-48-EC-20-BE-AF-7D-2C-27 (SHA1)", "'a.vb' C2-D0-74-6D-08-69-59-85-2E-64-93-75-AE-DD-55-73-C3-C1-48-3A (SHA1)") Dim sourceLines As String() = testSource.ToString().Split(vbLf(0)) VerifySpans(reader, reader.Methods(0), sourceLines, ' Branches New SpanResult(1, 4, 26, 11, "Sub Branches()"), New SpanResult(2, 27, 2, 28, "0"), New SpanResult(5, 12, 5, 19, "Exit Do"), New SpanResult(6, 12, 6, 18, "y += 1"), New SpanResult(8, 27, 8, 28, "1"), New SpanResult(9, 12, 9, 20, "Exit For"), New SpanResult(10, 12, 10, 18, "y += 1"), New SpanResult(13, 12, 13, 20, "Exit Try"), New SpanResult(14, 12, 14, 18, "y += 1"), New SpanResult(17, 20, 17, 21, "y"), New SpanResult(19, 16, 19, 27, "Exit Select"), New SpanResult(20, 16, 20, 22, "y += 0"), New SpanResult(23, 12, 23, 20, "Exit Sub"), New SpanResult(22, 11, 22, 16, "y = 0"), New SpanResult(25, 8, 25, 20, "GoTo MyLabel")) End Sub <Fact> Public Sub TestMethodSpansWithAttributes() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 0 Fred() End Sub <System.Obsolete()> Sub Fred() ' Method 1 End Sub Sub New() ' Method 2 x = 12 End Sub End Module Class c <System.Security.SecurityCritical> Public Sub New(x As Integer) ' Method 3 End Sub <System.Security.SecurityCritical> Sub New() ' Method 4 End Sub <System.Obsolete> Public Sub Fred() ' Method 5 Return End Sub <System.Obsolete> Function Barney() As Integer ' Method 6 Return 12 End Function <System.Obsolete> Shared Sub New() ' Method 7 End Sub <System.Obsolete> Public Shared Operator +(a As c, b As c) As c ' Method 8 Return a End Operator Property P1 As Integer <System.Security.SecurityCritical> Get ' Method 9 Return 10 End Get <System.Security.SecurityCritical> Set(value As Integer) ' Method 10 End Set End Property End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") VerifyDocuments(reader, reader.Documents, "'c.vb' 49-14-6E-73-25-48-FF-97-B3-56-26-54-65-D2-2B-00-B2-1A-FA-F5 (SHA1)", "'a.vb' C2-D0-74-6D-08-69-59-85-2E-64-93-75-AE-DD-55-73-C3-C1-48-3A (SHA1)") Dim sourceLines As String() = testSource.ToString().Split(vbLf(0)) VerifySpans(reader, reader.Methods(0), sourceLines, New SpanResult(3, 4, 5, 11, "Public Sub Main()"), New SpanResult(4, 8, 4, 14, "Fred()")) VerifySpans(reader, reader.Methods(1), sourceLines, New SpanResult(8, 4, 9, 11, "Sub Fred()")) VerifySpans(reader, reader.Methods(2), sourceLines, New SpanResult(11, 4, 13, 11, "Sub New()"), New SpanResult(12, 8, 12, 14, "x = 12")) VerifySpans(reader, reader.Methods(3), sourceLines, New SpanResult(18, 4, 19, 11, "Public Sub New(x As Integer) ")) VerifySpans(reader, reader.Methods(4), sourceLines, New SpanResult(22, 4, 23, 11, "Sub New()")) VerifySpans(reader, reader.Methods(5), sourceLines, New SpanResult(26, 4, 28, 11, "Public Sub Fred()"), New SpanResult(27, 8, 27, 14, "Return")) VerifySpans(reader, reader.Methods(6), sourceLines, New SpanResult(31, 4, 33, 16, "Function Barney() As Integer"), New SpanResult(32, 8, 32, 17, "Return 12")) VerifySpans(reader, reader.Methods(7), sourceLines, New SpanResult(36, 4, 37, 11, "Shared Sub New()")) VerifySpans(reader, reader.Methods(8), sourceLines, New SpanResult(40, 4, 42, 16, "Public Shared Operator +(a As c, b As c) As c"), New SpanResult(41, 8, 41, 16, "Return a")) VerifySpans(reader, reader.Methods(9), sourceLines, New SpanResult(46, 8, 48, 15, "Get"), New SpanResult(47, 12, 47, 21, "Return 10")) VerifySpans(reader, reader.Methods(10), sourceLines, New SpanResult(50, 8, 51, 15, "Set(value As Integer)")) End Sub <Fact> Public Sub TestFieldInitializerSpans() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 0 TestMain() End Sub Sub TestMain() ' Method 1 Dim local As New C() : local = New C(1, 2) End Sub End Module Class C Shared Function Init() As Integer ' Method 2 Return 33 End Function Sub New() ' Method 3 _z = 12 End Sub Shared Sub New() ' Method 4 s_z = 123 End Sub Private _x As Integer = Init() Private _y As Integer = Init() + 12 Private _z As Integer Private Shared s_x As Integer = Init() Private Shared s_y As Integer = Init() + 153 Private Shared s_z As Integer Sub New(x As Integer) ' Method 5 _z = x End Sub Sub New(a As Integer, b As Integer) ' Method 6 _z = a + b End Sub Property A As Integer = 1234 Shared Property B As Integer = 5678 End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") VerifyDocuments(reader, reader.Documents, "'c.vb' 13-52-6F-4D-3B-A7-8B-F7-A3-50-EE-1C-3B-0A-57-AB-B7-E5-33-0C (SHA1)", "'a.vb' C2-D0-74-6D-08-69-59-85-2E-64-93-75-AE-DD-55-73-C3-C1-48-3A (SHA1)") Dim sourceLines As String() = testSource.ToString().Split(vbLf(0)) VerifySpans(reader, reader.Methods(0), sourceLines, New SpanResult(3, 4, 5, 11, "Public Sub Main()"), New SpanResult(4, 8, 4, 18, "TestMain()")) VerifySpans(reader, reader.Methods(1), sourceLines, New SpanResult(7, 4, 9, 11, "Sub TestMain()"), New SpanResult(8, 21, 8, 28, "New C()"), New SpanResult(8, 31, 8, 50, "local = New C(1, 2)")) VerifySpans(reader, reader.Methods(2), sourceLines, New SpanResult(13, 4, 15, 16, "Shared Function Init() As Integer"), New SpanResult(14, 8, 14, 17, "Return 33")) VerifySpans(reader, reader.Methods(3), sourceLines, New SpanResult(17, 4, 19, 11, "Sub New()"), New SpanResult(25, 28, 25, 34, "Init()"), New SpanResult(26, 28, 26, 39, "Init() + 12"), New SpanResult(40, 28, 40, 32, "1234"), New SpanResult(18, 8, 18, 15, "_z = 12")) VerifySpans(reader, reader.Methods(4), sourceLines, New SpanResult(21, 4, 23, 11, "Shared Sub New()"), New SpanResult(28, 36, 28, 42, "Init()"), New SpanResult(29, 36, 29, 48, "Init() + 153"), New SpanResult(41, 35, 41, 39, "5678"), New SpanResult(22, 8, 22, 17, "s_z = 123")) VerifySpans(reader, reader.Methods(5), sourceLines, New SpanResult(32, 4, 34, 11, "Sub New(x As Integer)"), New SpanResult(25, 28, 25, 34, "Init()"), New SpanResult(26, 28, 26, 39, "Init() + 12"), New SpanResult(40, 28, 40, 32, "1234"), New SpanResult(33, 8, 33, 14, "_z = x")) VerifySpans(reader, reader.Methods(6), sourceLines, New SpanResult(36, 4, 38, 11, "Sub New(a As Integer, b As Integer)"), New SpanResult(25, 28, 25, 34, "Init()"), New SpanResult(26, 28, 26, 39, "Init() + 12"), New SpanResult(40, 28, 40, 32, "1234"), New SpanResult(37, 8, 37, 18, "_z = a + b")) End Sub <Fact> Public Sub TestImplicitConstructorSpans() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 0 TestMain() End Sub Sub TestMain() ' Method 1 Dim local As New C() End Sub End Module Class C Shared Function Init() As Integer ' Method 4 Return 33 End Function Private _x As Integer = Init() Private _y As Integer = Init() + 12 Private Shared s_x As Integer = Init() Private Shared s_y As Integer = Init() + 153 Private Shared s_z As Integer = 144 Property A As Integer = 1234 Shared Property B As Integer = 5678 End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") VerifyDocuments(reader, reader.Documents, "'c.vb' 7D-27-1F-B0-ED-E6-00-8D-6C-FF-13-69-26-40-2D-4B-AB-06-0D-2E (SHA1)", "'a.vb' C2-D0-74-6D-08-69-59-85-2E-64-93-75-AE-DD-55-73-C3-C1-48-3A (SHA1)") Dim sourceLines As String() = testSource.ToString().Split(vbLf(0)) VerifySpans(reader, reader.Methods(0), sourceLines, New SpanResult(3, 4, 5, 11, "Public Sub Main()"), New SpanResult(4, 8, 4, 18, "TestMain()")) VerifySpans(reader, reader.Methods(1), sourceLines, New SpanResult(7, 4, 9, 11, "Sub TestMain()"), New SpanResult(8, 21, 8, 28, "New C()")) VerifySpans(reader, reader.Methods(4), sourceLines, New SpanResult(13, 4, 15, 16, "Shared Function Init() As Integer"), New SpanResult(14, 8, 14, 17, "Return 33")) VerifySpans(reader, reader.Methods(2), sourceLines, ' implicit shared constructor New SpanResult(19, 36, 19, 42, "Init()"), New SpanResult(20, 36, 20, 48, "Init() + 153"), New SpanResult(21, 36, 21, 39, "144"), New SpanResult(24, 35, 24, 39, "5678")) VerifySpans(reader, reader.Methods(3), sourceLines, ' implicit instance constructor New SpanResult(17, 28, 17, 34, "Init()"), New SpanResult(18, 28, 18, 39, "Init() + 12"), New SpanResult(23, 28, 23, 32, "1234")) End Sub <Fact> Public Sub TestImplicitConstructorsWithLambdasSpans() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 0 TestMain() End Sub Sub TestMain() ' Method 1 Dim y As Integer = C.s_c._function() Dim dd As New D() Dim z As Integer = dd._c._function() Dim zz As Integer = D.s_c._function() Dim zzz As Integer = dd._c1._function() End Sub End Module Class C Public Sub New(f As System.Func(Of Integer)) ' Method 3 _function = f End Sub Shared Public s_c As New C(Function () 15) Public _function as System.Func(Of Integer) End Class Class D Public _c As C = New C(Function() 120) Public Shared s_c As C = New C(Function() 144) Public _c1 As New C(Function() Return 130 End Function) Public Shared s_c1 As New C(Function() Return 156 End Function) End Class Partial Structure E End Structure Partial Structure E Public Shared s_c As C = New C(Function() 1444) Public Shared s_c1 As New C(Function() Return 1567 End Function) End Structure Module F Public s_c As New C(Function() Return 333 End Function) End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") VerifyDocuments(reader, reader.Documents, "'c.vb' 71-DD-56-A9-0E-56-57-E0-2B-53-EC-DA-0E-60-47-5E-CD-D1-D9-16 (SHA1)", "'a.vb' C2-D0-74-6D-08-69-59-85-2E-64-93-75-AE-DD-55-73-C3-C1-48-3A (SHA1)") Dim sourceLines As String() = testSource.ToString().Split(vbLf(0)) VerifySpans(reader, reader.Methods(0), sourceLines, New SpanResult(3, 4, 5, 11, "Public Sub Main()"), New SpanResult(4, 8, 4, 18, "TestMain()")) VerifySpans(reader, reader.Methods(1), sourceLines, New SpanResult(7, 4, 13, 11, "Sub TestMain()"), New SpanResult(8, 27, 8, 44, "C.s_c._function()"), New SpanResult(9, 18, 9, 25, "New D()"), New SpanResult(10, 27, 10, 44, "dd._c._function()"), New SpanResult(11, 28, 11, 45, "D.s_c._function()"), New SpanResult(12, 29, 12, 47, "dd._c1._function()")) VerifySpans(reader, reader.Methods(2), sourceLines, ' Synthesized shared constructor for C New SpanResult(21, 43, 21, 45, "15"), New SpanResult(21, 25, 21, 46, "New C(Function () 15)")) VerifySpans(reader, reader.Methods(3), sourceLines, New SpanResult(17, 4, 19, 11, "Public Sub New(f As System.Func(Of Integer))"), New SpanResult(18, 8, 18, 21, "_function = f")) VerifySpans(reader, reader.Methods(4), sourceLines, ' Synthesized shared constructor for D New SpanResult(27, 46, 27, 49, "144"), New SpanResult(27, 29, 27, 50, "New C(Function() 144)"), New SpanResult(32, 36, 32, 46, "Return 156"), New SpanResult(31, 26, 33, 45, "New C(Function()")) VerifySpans(reader, reader.Methods(5), sourceLines, ' Synthesized instance constructor for D New SpanResult(26, 38, 26, 41, "120"), New SpanResult(26, 21, 26, 42, "New C(Function() 120)"), New SpanResult(29, 28, 29, 38, "Return 130"), New SpanResult(28, 18, 30, 37, "New C(Function()")) VerifySpans(reader, reader.Methods(6), sourceLines, ' Synthesized shared constructor for E New SpanResult(40, 46, 40, 50, "1444"), New SpanResult(40, 29, 40, 51, "New C(Function() 1444)"), New SpanResult(42, 36, 42, 47, "Return 1567"), New SpanResult(41, 26, 43, 45, "New C(Function()")) VerifySpans(reader, reader.Methods(7), sourceLines, ' Synthesized shared constructor for F New SpanResult(48, 28, 48, 38, "Return 333"), New SpanResult(47, 18, 49, 37, "New C(Function()")) End Sub <Fact> Public Sub TestDynamicAnalysisResourceMissingWhenInstrumentationFlagIsDisabled() Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(ExampleSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") Assert.Null(reader) End Sub Private Class SpanResult Public ReadOnly Property StartLine As Integer Public ReadOnly Property StartColumn As Integer Public ReadOnly Property EndLine As Integer Public ReadOnly Property EndColumn As Integer Public ReadOnly Property TextStart As String Public Sub New(startLine As Integer, startColumn As Integer, endLine As Integer, endColumn As Integer, textStart As String) Me.StartLine = startLine Me.StartColumn = startColumn Me.EndLine = endLine Me.EndColumn = endColumn Me.TextStart = textStart End Sub End Class Private Shared Sub VerifySpans(reader As DynamicAnalysisDataReader, methodData As DynamicAnalysisMethod, sourceLines As String(), ParamArray expected As SpanResult()) Dim expectedSpanSpellings As ArrayBuilder(Of String) = ArrayBuilder(Of String).GetInstance(expected.Length) For Each expectedSpanResult As SpanResult In expected Assert.True(sourceLines(expectedSpanResult.StartLine + 1).Substring(expectedSpanResult.StartColumn).StartsWith(expectedSpanResult.TextStart)) expectedSpanSpellings.Add(String.Format("({0},{1})-({2},{3})", expectedSpanResult.StartLine, expectedSpanResult.StartColumn, expectedSpanResult.EndLine, expectedSpanResult.EndColumn)) Next VerifySpans(reader, methodData, expectedSpanSpellings.ToArrayAndFree()) End Sub Private Shared Sub VerifySpans(reader As DynamicAnalysisDataReader, methodData As DynamicAnalysisMethod, ParamArray expected As String()) AssertEx.Equal(expected, reader.GetSpans(methodData.Blob).Select(Function(s) $"({s.StartLine},{s.StartColumn})-({s.EndLine},{s.EndColumn})")) End Sub Private Sub VerifyDocuments(reader As DynamicAnalysisDataReader, documents As ImmutableArray(Of DynamicAnalysisDocument), ParamArray expected As String()) Dim sha1 = New Guid("ff1816ec-aa5e-4d10-87F7-6F4963833460") Dim actual = From d In documents Let name = reader.GetDocumentName(d.Name) Let hash = If(d.Hash.IsNil, "", " " + BitConverter.ToString(reader.GetBytes(d.Hash))) Let hashAlgGuid = reader.GetGuid(d.HashAlgorithm) Let hashAlg = If(hashAlgGuid = sha1, " (SHA1)", If(hashAlgGuid = New Guid, "", " " + hashAlgGuid.ToString())) Select $"'{name}'{hash}{hashAlg}" AssertEx.Equal(expected, actual) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Reflection.PortableExecutable Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.DynamicAnalysis.UnitTests Public Class DynamicAnalysisResourceTests Inherits BasicTestBase ReadOnly InstrumentationHelperSource As XElement = <file name="a.vb"> <![CDATA[ Namespace Microsoft.CodeAnalysis.Runtime Public Class Instrumentation Public Shared Function CreatePayload(mvid As System.Guid, methodToken As Integer, fileIndex As Integer, ByRef payload As Boolean(), payloadLength As Integer) As Boolean() Return payload End Function Public Shared Function CreatePayload(mvid As System.Guid, methodToken As Integer, fileIndices As Integer(), ByRef payload As Boolean(), payloadLength As Integer) As Boolean() Return payload End Function Public Shared Sub FlushPayload() End Sub End Class End Namespace ]]> </file> ReadOnly ExampleSource As XElement = <file name="c.vb"> <![CDATA[ Imports System Public Class C Public Shared Sub Main() Console.WriteLine(123) Console.WriteLine(123) End Sub Public Shared Function Fred As Integer Return 3 End Function Public Shared Function Barney(x As Integer) Return x End Function Public Shared Property Wilma As Integer Get Return 12 End Get Set End Set End Property Public Shared ReadOnly Property Betty As Integer End Class ]]> </file> <Fact> Public Sub TestSpansPresentInResource() Dim source As XElement = <compilation></compilation> source.Add(ExampleSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") VerifyDocuments(reader, reader.Documents, "'c.vb' 1A-10-00-3A-D1-71-8C-BD-53-CC-9D-9C-5D-53-5D-7F-8C-70-89-0F (SHA1)", "'a.vb' C2-D0-74-6D-08-69-59-85-2E-64-93-75-AE-DD-55-73-C3-C1-48-3A (SHA1)") Assert.Equal(12, reader.Methods.Length) Dim sourceLines As String() = ExampleSource.ToString().Split(vbLf(0)) VerifySpans(reader, reader.Methods(1), sourceLines, ' Main New SpanResult(3, 4, 6, 11, "Public Shared Sub Main()"), New SpanResult(4, 8, 4, 30, "Console.WriteLine(123)"), New SpanResult(5, 8, 5, 30, "Console.WriteLine(123)")) VerifySpans(reader, reader.Methods(2), sourceLines, ' Fred get New SpanResult(8, 4, 10, 16, "Public Shared Function Fred As Integer"), New SpanResult(9, 8, 9, 16, "Return 3")) VerifySpans(reader, reader.Methods(3), sourceLines, ' Barney New SpanResult(12, 4, 14, 16, "Public Shared Function Barney(x As Integer)"), New SpanResult(13, 8, 13, 16, "Return x")) VerifySpans(reader, reader.Methods(4), sourceLines, ' Wilma get New SpanResult(17, 8, 19, 15, "Get"), New SpanResult(18, 12, 18, 21, "Return 12")) VerifySpans(reader, reader.Methods(5), sourceLines, ' Wilma set New SpanResult(20, 8, 21, 15, "Set")) VerifySpans(reader, reader.Methods(6)) ' Betty get -- VB does not supply a valid syntax node for the body. VerifySpans(reader, reader.Methods(7)) End Sub <Fact> Public Sub TestLoopSpans() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Function TestIf(a As Boolean, b As Boolean) As Integer Dim x As Integer = 0 If a Then x += 1 Else x += 10 If a Then x += 1 ElseIf a AndAlso b Then x += 10 Else x += 100 End If If b Then x += 1 End If If a AndAlso b Then x += 10 End If Return x End Function Function TestDoLoops() As Integer Dim x As Integer = 100 While x < 150 x += 1 End While While x < 150 x += 1 End While Do While x < 200 x += 1 Loop Do Until x = 200 x += 1 Loop Do x += 1 Loop While x < 200 Do x += 1 Loop Until x = 202 Do Return x Loop End Function Sub TestForLoops() Dim x As Integer = 0 Dim y As Integer = 10 Dim z As Integer = 3 For a As Integer = x To y Step z z += 1 Next For b As Integer = 1 To 10 z += 1 Next For Each c As Integer In {x, y, z} z += 1 Next End Sub Public Sub Main(args As String()) TestIf(False, False) TestIf(True, False) TestDoLoops() TestForLoops() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") VerifyDocuments(reader, reader.Documents, "'c.vb' 55-FA-D1-46-BA-6F-EC-77-0E-02-1A-A6-BC-62-21-F7-E3-31-4F-2C (SHA1)", "'a.vb' C2-D0-74-6D-08-69-59-85-2E-64-93-75-AE-DD-55-73-C3-C1-48-3A (SHA1)") Dim sourceLines As String() = testSource.ToString().Split(vbLf(0)) VerifySpans(reader, reader.Methods(0), sourceLines, ' TestIf New SpanResult(1, 4, 18, 16, "Function TestIf(a As Boolean, b As Boolean) As Integer"), New SpanResult(2, 27, 2, 28, "0"), New SpanResult(3, 18, 3, 24, "x += 1"), New SpanResult(3, 30, 3, 37, "x += 10"), New SpanResult(3, 11, 3, 12, "a"), New SpanResult(5, 12, 5, 18, "x += 1"), New SpanResult(7, 12, 7, 19, "x += 10"), New SpanResult(9, 12, 9, 20, "x += 100"), New SpanResult(6, 15, 6, 26, "a AndAlso b"), New SpanResult(4, 11, 4, 12, "a"), New SpanResult(12, 12, 12, 18, "x += 1"), New SpanResult(11, 11, 11, 12, "b"), New SpanResult(15, 12, 15, 19, "x += 10"), New SpanResult(14, 11, 14, 22, "a AndAlso b"), New SpanResult(17, 8, 17, 16, "Return x")) VerifySpans(reader, reader.Methods(1), sourceLines, ' TestDoLoops New SpanResult(20, 4, 43, 16, "Function TestDoLoops() As Integer"), New SpanResult(21, 27, 21, 30, "100"), New SpanResult(23, 12, 23, 18, "x += 1"), New SpanResult(22, 14, 22, 21, "x < 150"), New SpanResult(26, 12, 26, 18, "x += 1"), New SpanResult(25, 14, 25, 21, "x < 150"), New SpanResult(29, 12, 29, 18, "x += 1"), New SpanResult(28, 17, 28, 24, "x < 200"), New SpanResult(32, 12, 32, 18, "x += 1"), New SpanResult(31, 17, 31, 24, "x = 200"), New SpanResult(35, 12, 35, 18, "x += 1"), New SpanResult(36, 19, 36, 26, "x < 200"), New SpanResult(38, 12, 38, 18, "x += 1"), New SpanResult(39, 19, 39, 26, "x = 202"), New SpanResult(41, 12, 41, 20, "Return x")) VerifySpans(reader, reader.Methods(2), sourceLines, ' TestForLoops New SpanResult(45, 4, 58, 11, "Sub TestForLoops()"), New SpanResult(46, 27, 46, 28, "0"), New SpanResult(47, 27, 47, 29, "10"), New SpanResult(48, 27, 48, 28, "3"), New SpanResult(49, 27, 49, 28, "x"), New SpanResult(50, 12, 50, 18, "z += 1"), New SpanResult(52, 27, 52, 28, "1"), New SpanResult(53, 12, 53, 18, "z += 1"), New SpanResult(55, 33, 55, 42, "{x, y, z}"), New SpanResult(56, 12, 56, 18, "z += 1")) End Sub <Fact> Public Sub TestTryAndSelect() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub TryAndSelect() Dim y As Integer = 0 Try Try For x As Integer = 0 To 10 Select Case x Case 0 y += 1 Case 1 Throw New System.Exception() Case >= 2 y += 1 Case Else y += 1 End Select Next Catch e As System.Exception y += 1 End Try Finally y += 1 End Try End Sub Public Sub Main(args As String()) TryAndSelect() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") VerifyDocuments(reader, reader.Documents, "'c.vb' 36-B0-C2-29-F1-DC-B1-63-93-45-31-11-58-6C-5A-46-89-A1-42-34 (SHA1)", "'a.vb' C2-D0-74-6D-08-69-59-85-2E-64-93-75-AE-DD-55-73-C3-C1-48-3A (SHA1)") Dim sourceLines As String() = testSource.ToString().Split(vbLf(0)) VerifySpans(reader, reader.Methods(0), sourceLines, ' TryAndSelect New SpanResult(1, 4, 23, 11, "Sub TryAndSelect()"), New SpanResult(2, 27, 2, 28, "0"), New SpanResult(5, 35, 5, 36, "0"), New SpanResult(6, 32, 6, 33, "x"), New SpanResult(8, 28, 8, 34, "y += 1"), New SpanResult(10, 28, 10, 56, "Throw New System.Exception()"), New SpanResult(12, 28, 12, 34, "y += 1"), New SpanResult(14, 28, 14, 34, "y += 1"), New SpanResult(18, 16, 18, 22, "y += 1"), New SpanResult(21, 12, 21, 18, "y += 1")) End Sub <Fact> Public Sub TestBranches() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Sub Branches() Dim y As Integer = 0 MyLabel: Do Exit Do y += 1 Loop For x As Integer = 1 To 10 Exit For y += 1 Next Try Exit Try y += 1 Catch ex As System.Exception End Try Select Case y Case 0 Exit Select y += 0 End Select If y = 0 Then Exit Sub End If GoTo MyLabel End Sub Public Sub Main(args As String()) Branches() Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload() End Sub End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") VerifyDocuments(reader, reader.Documents, "'c.vb' 1B-06-B9-C5-D5-D3-AD-EE-8A-D3-31-8F-48-EC-20-BE-AF-7D-2C-27 (SHA1)", "'a.vb' C2-D0-74-6D-08-69-59-85-2E-64-93-75-AE-DD-55-73-C3-C1-48-3A (SHA1)") Dim sourceLines As String() = testSource.ToString().Split(vbLf(0)) VerifySpans(reader, reader.Methods(0), sourceLines, ' Branches New SpanResult(1, 4, 26, 11, "Sub Branches()"), New SpanResult(2, 27, 2, 28, "0"), New SpanResult(5, 12, 5, 19, "Exit Do"), New SpanResult(6, 12, 6, 18, "y += 1"), New SpanResult(8, 27, 8, 28, "1"), New SpanResult(9, 12, 9, 20, "Exit For"), New SpanResult(10, 12, 10, 18, "y += 1"), New SpanResult(13, 12, 13, 20, "Exit Try"), New SpanResult(14, 12, 14, 18, "y += 1"), New SpanResult(17, 20, 17, 21, "y"), New SpanResult(19, 16, 19, 27, "Exit Select"), New SpanResult(20, 16, 20, 22, "y += 0"), New SpanResult(23, 12, 23, 20, "Exit Sub"), New SpanResult(22, 11, 22, 16, "y = 0"), New SpanResult(25, 8, 25, 20, "GoTo MyLabel")) End Sub <Fact> Public Sub TestMethodSpansWithAttributes() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 0 Fred() End Sub <System.Obsolete()> Sub Fred() ' Method 1 End Sub Sub New() ' Method 2 x = 12 End Sub End Module Class c <System.Security.SecurityCritical> Public Sub New(x As Integer) ' Method 3 End Sub <System.Security.SecurityCritical> Sub New() ' Method 4 End Sub <System.Obsolete> Public Sub Fred() ' Method 5 Return End Sub <System.Obsolete> Function Barney() As Integer ' Method 6 Return 12 End Function <System.Obsolete> Shared Sub New() ' Method 7 End Sub <System.Obsolete> Public Shared Operator +(a As c, b As c) As c ' Method 8 Return a End Operator Property P1 As Integer <System.Security.SecurityCritical> Get ' Method 9 Return 10 End Get <System.Security.SecurityCritical> Set(value As Integer) ' Method 10 End Set End Property End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") VerifyDocuments(reader, reader.Documents, "'c.vb' 49-14-6E-73-25-48-FF-97-B3-56-26-54-65-D2-2B-00-B2-1A-FA-F5 (SHA1)", "'a.vb' C2-D0-74-6D-08-69-59-85-2E-64-93-75-AE-DD-55-73-C3-C1-48-3A (SHA1)") Dim sourceLines As String() = testSource.ToString().Split(vbLf(0)) VerifySpans(reader, reader.Methods(0), sourceLines, New SpanResult(3, 4, 5, 11, "Public Sub Main()"), New SpanResult(4, 8, 4, 14, "Fred()")) VerifySpans(reader, reader.Methods(1), sourceLines, New SpanResult(8, 4, 9, 11, "Sub Fred()")) VerifySpans(reader, reader.Methods(2), sourceLines, New SpanResult(11, 4, 13, 11, "Sub New()"), New SpanResult(12, 8, 12, 14, "x = 12")) VerifySpans(reader, reader.Methods(3), sourceLines, New SpanResult(18, 4, 19, 11, "Public Sub New(x As Integer) ")) VerifySpans(reader, reader.Methods(4), sourceLines, New SpanResult(22, 4, 23, 11, "Sub New()")) VerifySpans(reader, reader.Methods(5), sourceLines, New SpanResult(26, 4, 28, 11, "Public Sub Fred()"), New SpanResult(27, 8, 27, 14, "Return")) VerifySpans(reader, reader.Methods(6), sourceLines, New SpanResult(31, 4, 33, 16, "Function Barney() As Integer"), New SpanResult(32, 8, 32, 17, "Return 12")) VerifySpans(reader, reader.Methods(7), sourceLines, New SpanResult(36, 4, 37, 11, "Shared Sub New()")) VerifySpans(reader, reader.Methods(8), sourceLines, New SpanResult(40, 4, 42, 16, "Public Shared Operator +(a As c, b As c) As c"), New SpanResult(41, 8, 41, 16, "Return a")) VerifySpans(reader, reader.Methods(9), sourceLines, New SpanResult(46, 8, 48, 15, "Get"), New SpanResult(47, 12, 47, 21, "Return 10")) VerifySpans(reader, reader.Methods(10), sourceLines, New SpanResult(50, 8, 51, 15, "Set(value As Integer)")) End Sub <Fact> Public Sub TestFieldInitializerSpans() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 0 TestMain() End Sub Sub TestMain() ' Method 1 Dim local As New C() : local = New C(1, 2) End Sub End Module Class C Shared Function Init() As Integer ' Method 2 Return 33 End Function Sub New() ' Method 3 _z = 12 End Sub Shared Sub New() ' Method 4 s_z = 123 End Sub Private _x As Integer = Init() Private _y As Integer = Init() + 12 Private _z As Integer Private Shared s_x As Integer = Init() Private Shared s_y As Integer = Init() + 153 Private Shared s_z As Integer Sub New(x As Integer) ' Method 5 _z = x End Sub Sub New(a As Integer, b As Integer) ' Method 6 _z = a + b End Sub Property A As Integer = 1234 Shared Property B As Integer = 5678 End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") VerifyDocuments(reader, reader.Documents, "'c.vb' 13-52-6F-4D-3B-A7-8B-F7-A3-50-EE-1C-3B-0A-57-AB-B7-E5-33-0C (SHA1)", "'a.vb' C2-D0-74-6D-08-69-59-85-2E-64-93-75-AE-DD-55-73-C3-C1-48-3A (SHA1)") Dim sourceLines As String() = testSource.ToString().Split(vbLf(0)) VerifySpans(reader, reader.Methods(0), sourceLines, New SpanResult(3, 4, 5, 11, "Public Sub Main()"), New SpanResult(4, 8, 4, 18, "TestMain()")) VerifySpans(reader, reader.Methods(1), sourceLines, New SpanResult(7, 4, 9, 11, "Sub TestMain()"), New SpanResult(8, 21, 8, 28, "New C()"), New SpanResult(8, 31, 8, 50, "local = New C(1, 2)")) VerifySpans(reader, reader.Methods(2), sourceLines, New SpanResult(13, 4, 15, 16, "Shared Function Init() As Integer"), New SpanResult(14, 8, 14, 17, "Return 33")) VerifySpans(reader, reader.Methods(3), sourceLines, New SpanResult(17, 4, 19, 11, "Sub New()"), New SpanResult(25, 28, 25, 34, "Init()"), New SpanResult(26, 28, 26, 39, "Init() + 12"), New SpanResult(40, 28, 40, 32, "1234"), New SpanResult(18, 8, 18, 15, "_z = 12")) VerifySpans(reader, reader.Methods(4), sourceLines, New SpanResult(21, 4, 23, 11, "Shared Sub New()"), New SpanResult(28, 36, 28, 42, "Init()"), New SpanResult(29, 36, 29, 48, "Init() + 153"), New SpanResult(41, 35, 41, 39, "5678"), New SpanResult(22, 8, 22, 17, "s_z = 123")) VerifySpans(reader, reader.Methods(5), sourceLines, New SpanResult(32, 4, 34, 11, "Sub New(x As Integer)"), New SpanResult(25, 28, 25, 34, "Init()"), New SpanResult(26, 28, 26, 39, "Init() + 12"), New SpanResult(40, 28, 40, 32, "1234"), New SpanResult(33, 8, 33, 14, "_z = x")) VerifySpans(reader, reader.Methods(6), sourceLines, New SpanResult(36, 4, 38, 11, "Sub New(a As Integer, b As Integer)"), New SpanResult(25, 28, 25, 34, "Init()"), New SpanResult(26, 28, 26, 39, "Init() + 12"), New SpanResult(40, 28, 40, 32, "1234"), New SpanResult(37, 8, 37, 18, "_z = a + b")) End Sub <Fact> Public Sub TestImplicitConstructorSpans() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 0 TestMain() End Sub Sub TestMain() ' Method 1 Dim local As New C() End Sub End Module Class C Shared Function Init() As Integer ' Method 4 Return 33 End Function Private _x As Integer = Init() Private _y As Integer = Init() + 12 Private Shared s_x As Integer = Init() Private Shared s_y As Integer = Init() + 153 Private Shared s_z As Integer = 144 Property A As Integer = 1234 Shared Property B As Integer = 5678 End Class ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") VerifyDocuments(reader, reader.Documents, "'c.vb' 7D-27-1F-B0-ED-E6-00-8D-6C-FF-13-69-26-40-2D-4B-AB-06-0D-2E (SHA1)", "'a.vb' C2-D0-74-6D-08-69-59-85-2E-64-93-75-AE-DD-55-73-C3-C1-48-3A (SHA1)") Dim sourceLines As String() = testSource.ToString().Split(vbLf(0)) VerifySpans(reader, reader.Methods(0), sourceLines, New SpanResult(3, 4, 5, 11, "Public Sub Main()"), New SpanResult(4, 8, 4, 18, "TestMain()")) VerifySpans(reader, reader.Methods(1), sourceLines, New SpanResult(7, 4, 9, 11, "Sub TestMain()"), New SpanResult(8, 21, 8, 28, "New C()")) VerifySpans(reader, reader.Methods(4), sourceLines, New SpanResult(13, 4, 15, 16, "Shared Function Init() As Integer"), New SpanResult(14, 8, 14, 17, "Return 33")) VerifySpans(reader, reader.Methods(2), sourceLines, ' implicit shared constructor New SpanResult(19, 36, 19, 42, "Init()"), New SpanResult(20, 36, 20, 48, "Init() + 153"), New SpanResult(21, 36, 21, 39, "144"), New SpanResult(24, 35, 24, 39, "5678")) VerifySpans(reader, reader.Methods(3), sourceLines, ' implicit instance constructor New SpanResult(17, 28, 17, 34, "Init()"), New SpanResult(18, 28, 18, 39, "Init() + 12"), New SpanResult(23, 28, 23, 32, "1234")) End Sub <Fact> Public Sub TestImplicitConstructorsWithLambdasSpans() Dim testSource As XElement = <file name="c.vb"> <![CDATA[ Module Program Private x As Integer Public Sub Main() ' Method 0 TestMain() End Sub Sub TestMain() ' Method 1 Dim y As Integer = C.s_c._function() Dim dd As New D() Dim z As Integer = dd._c._function() Dim zz As Integer = D.s_c._function() Dim zzz As Integer = dd._c1._function() End Sub End Module Class C Public Sub New(f As System.Func(Of Integer)) ' Method 3 _function = f End Sub Shared Public s_c As New C(Function () 15) Public _function as System.Func(Of Integer) End Class Class D Public _c As C = New C(Function() 120) Public Shared s_c As C = New C(Function() 144) Public _c1 As New C(Function() Return 130 End Function) Public Shared s_c1 As New C(Function() Return 156 End Function) End Class Partial Structure E End Structure Partial Structure E Public Shared s_c As C = New C(Function() 1444) Public Shared s_c1 As New C(Function() Return 1567 End Function) End Structure Module F Public s_c As New C(Function() Return 333 End Function) End Module ]]> </file> Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(testSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") VerifyDocuments(reader, reader.Documents, "'c.vb' 71-DD-56-A9-0E-56-57-E0-2B-53-EC-DA-0E-60-47-5E-CD-D1-D9-16 (SHA1)", "'a.vb' C2-D0-74-6D-08-69-59-85-2E-64-93-75-AE-DD-55-73-C3-C1-48-3A (SHA1)") Dim sourceLines As String() = testSource.ToString().Split(vbLf(0)) VerifySpans(reader, reader.Methods(0), sourceLines, New SpanResult(3, 4, 5, 11, "Public Sub Main()"), New SpanResult(4, 8, 4, 18, "TestMain()")) VerifySpans(reader, reader.Methods(1), sourceLines, New SpanResult(7, 4, 13, 11, "Sub TestMain()"), New SpanResult(8, 27, 8, 44, "C.s_c._function()"), New SpanResult(9, 18, 9, 25, "New D()"), New SpanResult(10, 27, 10, 44, "dd._c._function()"), New SpanResult(11, 28, 11, 45, "D.s_c._function()"), New SpanResult(12, 29, 12, 47, "dd._c1._function()")) VerifySpans(reader, reader.Methods(2), sourceLines, ' Synthesized shared constructor for C New SpanResult(21, 43, 21, 45, "15"), New SpanResult(21, 25, 21, 46, "New C(Function () 15)")) VerifySpans(reader, reader.Methods(3), sourceLines, New SpanResult(17, 4, 19, 11, "Public Sub New(f As System.Func(Of Integer))"), New SpanResult(18, 8, 18, 21, "_function = f")) VerifySpans(reader, reader.Methods(4), sourceLines, ' Synthesized shared constructor for D New SpanResult(27, 46, 27, 49, "144"), New SpanResult(27, 29, 27, 50, "New C(Function() 144)"), New SpanResult(32, 36, 32, 46, "Return 156"), New SpanResult(31, 26, 33, 45, "New C(Function()")) VerifySpans(reader, reader.Methods(5), sourceLines, ' Synthesized instance constructor for D New SpanResult(26, 38, 26, 41, "120"), New SpanResult(26, 21, 26, 42, "New C(Function() 120)"), New SpanResult(29, 28, 29, 38, "Return 130"), New SpanResult(28, 18, 30, 37, "New C(Function()")) VerifySpans(reader, reader.Methods(6), sourceLines, ' Synthesized shared constructor for E New SpanResult(40, 46, 40, 50, "1444"), New SpanResult(40, 29, 40, 51, "New C(Function() 1444)"), New SpanResult(42, 36, 42, 47, "Return 1567"), New SpanResult(41, 26, 43, 45, "New C(Function()")) VerifySpans(reader, reader.Methods(7), sourceLines, ' Synthesized shared constructor for F New SpanResult(48, 28, 48, 38, "Return 333"), New SpanResult(47, 18, 49, 37, "New C(Function()")) End Sub <Fact> Public Sub TestDynamicAnalysisResourceMissingWhenInstrumentationFlagIsDisabled() Dim source As Xml.Linq.XElement = <compilation></compilation> source.Add(ExampleSource) source.Add(InstrumentationHelperSource) Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Dim peImage = c.EmitToArray(EmitOptions.Default) Dim PEReader As New PEReader(peImage) Dim reader = DynamicAnalysisDataReader.TryCreateFromPE(PEReader, "<DynamicAnalysisData>") Assert.Null(reader) End Sub Private Class SpanResult Public ReadOnly Property StartLine As Integer Public ReadOnly Property StartColumn As Integer Public ReadOnly Property EndLine As Integer Public ReadOnly Property EndColumn As Integer Public ReadOnly Property TextStart As String Public Sub New(startLine As Integer, startColumn As Integer, endLine As Integer, endColumn As Integer, textStart As String) Me.StartLine = startLine Me.StartColumn = startColumn Me.EndLine = endLine Me.EndColumn = endColumn Me.TextStart = textStart End Sub End Class Private Shared Sub VerifySpans(reader As DynamicAnalysisDataReader, methodData As DynamicAnalysisMethod, sourceLines As String(), ParamArray expected As SpanResult()) Dim expectedSpanSpellings As ArrayBuilder(Of String) = ArrayBuilder(Of String).GetInstance(expected.Length) For Each expectedSpanResult As SpanResult In expected Assert.True(sourceLines(expectedSpanResult.StartLine + 1).Substring(expectedSpanResult.StartColumn).StartsWith(expectedSpanResult.TextStart)) expectedSpanSpellings.Add(String.Format("({0},{1})-({2},{3})", expectedSpanResult.StartLine, expectedSpanResult.StartColumn, expectedSpanResult.EndLine, expectedSpanResult.EndColumn)) Next VerifySpans(reader, methodData, expectedSpanSpellings.ToArrayAndFree()) End Sub Private Shared Sub VerifySpans(reader As DynamicAnalysisDataReader, methodData As DynamicAnalysisMethod, ParamArray expected As String()) AssertEx.Equal(expected, reader.GetSpans(methodData.Blob).Select(Function(s) $"({s.StartLine},{s.StartColumn})-({s.EndLine},{s.EndColumn})")) End Sub Private Sub VerifyDocuments(reader As DynamicAnalysisDataReader, documents As ImmutableArray(Of DynamicAnalysisDocument), ParamArray expected As String()) Dim sha1 = New Guid("ff1816ec-aa5e-4d10-87F7-6F4963833460") Dim actual = From d In documents Let name = reader.GetDocumentName(d.Name) Let hash = If(d.Hash.IsNil, "", " " + BitConverter.ToString(reader.GetBytes(d.Hash))) Let hashAlgGuid = reader.GetGuid(d.HashAlgorithm) Let hashAlg = If(hashAlgGuid = sha1, " (SHA1)", If(hashAlgGuid = New Guid, "", " " + hashAlgGuid.ToString())) Select $"'{name}'{hash}{hashAlg}" AssertEx.Equal(expected, actual) End Sub End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenOverridingAndHiding.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenOverridingAndHiding Inherits BasicTestBase <WorkItem(540852, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540852")> <Fact> Public Sub TestSimpleMustOverride() Dim source = <compilation> <file name="a.vb"> Imports System MustInherit Class A Public MustOverride Function F As Integer() Protected MustOverride Sub Meth() Protected Friend MustOverride Property Prop As Integer() End Class </file> </compilation> Dim verifier = CompileAndVerify(source, expectedSignatures:= { Signature("A", "F", ".method public newslot strict abstract virtual instance System.Int32[] F() cil managed"), Signature("A", "Meth", ".method family newslot strict abstract virtual instance System.Void Meth() cil managed"), Signature("A", "get_Prop", ".method famorassem newslot strict specialname abstract virtual instance System.Int32[] get_Prop() cil managed"), Signature("A", "set_Prop", ".method famorassem newslot strict specialname abstract virtual instance System.Void set_Prop(System.Int32[] Value) cil managed"), Signature("A", "Prop", ".property readwrite System.Int32[] Prop") }) End Sub <WorkItem(528311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528311")> <WorkItem(540865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540865")> <Fact> Public Sub TestSimpleOverrides() Dim source = <compilation> <file name="a.vb"> MustInherit Class A Public MustOverride Sub F() End Class Class B Inherits A Public Overrides Sub F() End Sub End Class </file> </compilation> Dim verifier = CompileAndVerify(source, expectedSignatures:= { Signature("B", "F", ".method public hidebysig strict virtual instance System.Void F() cil managed"), Signature("A", "F", ".method public newslot strict abstract virtual instance System.Void F() cil managed") }) verifier.VerifyDiagnostics() End Sub <WorkItem(540884, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540884")> <Fact> Public Sub TestMustOverrideOverrides() Dim source = <compilation> <file name="a.vb"> Imports System Class A Public Overridable Sub G() Console.WriteLine("A.G") End Sub End Class MustInherit Class B Inherits A Public MustOverride Overrides Sub G() End Class </file> </compilation> Dim verifier = CompileAndVerify(source, expectedSignatures:= { Signature("B", "G", ".method public hidebysig strict abstract virtual instance System.Void G() cil managed"), Signature("A", "G", ".method public newslot strict virtual instance System.Void G() cil managed") }) verifier.VerifyDiagnostics() End Sub <WorkItem(542576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542576")> <Fact> Public Sub TestDontMergePartials() Dim source = <compilation> <file name="a.vb"> MustInherit Class A MustOverride Function F() As Integer Overridable Sub G() End Sub End Class Partial Class B Inherits A 'This would normally be an error if this partial part for class B 'had the NotInheritable modifier (i.e. NotOverridable and NotInheritable 'can't be combined). Strangely Dev10 doesn't report the same error 'when the NotInheritable modifier appears on a different partial part. NotOverridable Overrides Function F() As Integer Return 1 End Function 'This would normally be an error if this partial part for class B 'had the NotInheritable modifier (i.e. NotOverridable and NotInheritable 'can't be combined). Strangely Dev10 doesn't report the same error 'when the NotInheritable modifier appears on a different partial part. NotOverridable Overrides Sub G() End Sub End Class</file> <file name="b.vb"> NotInheritable Class B Inherits A End Class </file> </compilation> CompileAndVerify(source, expectedSignatures:= { Signature("B", "F", ".method public hidebysig strict virtual final instance System.Int32 F() cil managed"), Signature("A", "F", ".method public newslot strict abstract virtual instance System.Int32 F() cil managed"), Signature("B", "G", ".method public hidebysig strict virtual final instance System.Void G() cil managed"), Signature("A", "G", ".method public newslot strict virtual instance System.Void G() cil managed") }). VerifyDiagnostics() End Sub <WorkItem(543751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543751")> <Fact(), WorkItem(543751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543751")> Public Sub TestMustOverloadWithOptional() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Const str As String = "" Sub Main(args As String()) End Sub Function fun() test(temp:=Nothing, x:=1) Return Nothing End Function Function test(ByRef x As Integer, temp As Object, Optional y As String = str, Optional z As Object = Nothing) Return Nothing End Function Function test(ByRef x As Integer, Optional temp As Object = Nothing) Return Nothing End Function End Module </file> </compilation>). VerifyDiagnostics() End Sub <Fact()> Public Sub CrossLanguageCase1() 'Note: For this case Dev10 produces errors (see below) while Roslyn works fine. We believe this 'is a bug in Dev10 that we fixed in Roslyn - the change is non-breaking. Dim vb1Compilation = CreateVisualBasicCompilation("VB1", <![CDATA[Public MustInherit Class C1 MustOverride Sub goo() End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim vb1Verifier = CompileAndVerify(vb1Compilation) vb1Verifier.VerifyDiagnostics() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[using System; public abstract class C2 : C1 { new internal virtual void goo() { Console.WriteLine("C2"); } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation}) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[Imports System Public Class C3 : Inherits C2 Public Overrides Sub goo Console.WriteLine("C3") End Sub End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation, cs1Compilation}) Dim vb2Verifier = CompileAndVerify(vb2Compilation) vb2Verifier.VerifyDiagnostics() 'Dev10 reports an error for the below compilation - Roslyn on the other hand allows this code to compile without errors. 'VB3.vb(2) : error BC30610: Class 'C4' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): 'C1 : Public MustOverride Sub goo(). 'Public Class C4 : Inherits C3 ' ~~ Dim vb3Compilation = CreateVisualBasicCompilation("VB3", <![CDATA[ Imports System Public Class C4 : Inherits C3 End Class Public Class C5 : Inherits C2 ' Corresponding case in C# results in PEVerify errors - See test 'CrossLanguageCase1' in CodeGenOverridingAndHiding.cs Public Overrides Sub goo() Console.WriteLine("C5") End Sub End Class Public Module Program Sub Main() Dim x As C1 = New C4 x.goo() Dim y As C2 = New C5 y.Goo() End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation}) Dim vb3Verifier = CompileAndVerify(vb3Compilation, expectedOutput:=<![CDATA[C3 C5]]>) vb3Verifier.VerifyDiagnostics() End Sub <Fact()> Public Sub CrossLanguageCase2() 'Note: For this case Dev10 produces errors (see below) while Roslyn works fine. We believe this 'is a bug in Dev10 that we fixed in Roslyn - the change is non-breaking. Dim vb1Compilation = CreateVisualBasicCompilation("VB1", <![CDATA[Public MustInherit Class C1 MustOverride Sub goo() End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim vb1Verifier = CompileAndVerify(vb1Compilation) vb1Verifier.VerifyDiagnostics() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[using System; [assembly:System.Runtime.CompilerServices.InternalsVisibleTo("VB3")] public abstract class C2 : C1 { new internal virtual void goo() { Console.WriteLine("C2"); } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation}) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[Imports System Public Class C3 : Inherits C2 Public Overrides Sub goo Console.WriteLine("C3") End Sub End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation, cs1Compilation}) Dim vb2Verifier = CompileAndVerify(vb2Compilation) vb2Verifier.VerifyDiagnostics() 'Dev10 reports an error for the below compilation - Roslyn on the other hand allows this code to compile without errors. 'VB3.vb(2) : error BC30610: Class 'C4' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): 'C1 : Public MustOverride Sub goo(). 'Public Class C4 : Inherits C3 ' ~~ Dim vb3Compilation = CreateVisualBasicCompilation("VB3", <![CDATA[Imports System Public Class C4 : Inherits C3 Public Overrides Sub goo Console.WriteLine("C4") End Sub End Class Public Module Program Sub Main() Dim x As C1 = New C4 x.goo Dim y As C2 = New C4 y.goo End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation}) Dim vb3Verifier = CompileAndVerify(vb3Compilation, expectedOutput:=<![CDATA[C4 C2]]>) vb3Verifier.VerifyDiagnostics() End Sub <Fact()> Public Sub CrossLanguageCase3() 'Note: Dev10 and Roslyn produce identical errors for this case. Dim vb1Compilation = CreateVisualBasicCompilation("VB1", <![CDATA[Public MustInherit Class C1 MustOverride Sub goo() End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim vb1Verifier = CompileAndVerify(vb1Compilation) vb1Verifier.VerifyDiagnostics() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("VB3")] public abstract class C2 : C1 { new internal virtual void goo() { } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation}) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[Public Class C3 : Inherits C2 Public Overrides Sub goo End Sub End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation, cs1Compilation}) Dim vb2Verifier = CompileAndVerify(vb2Compilation) vb2Verifier.VerifyDiagnostics() Dim vb3Compilation = CreateVisualBasicCompilation("VB3", <![CDATA[MustInherit Public Class C4 : Inherits C3 Public Overrides Sub goo End Sub End Class Public Class C5 : Inherits C2 Public Overrides Sub goo() End Sub End Class Public Class C6 : Inherits C2 Friend Overrides Sub goo() End Sub End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation}) vb3Compilation.AssertTheseDiagnostics(<expected> BC30610: Class 'C5' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): C1: Public MustOverride Sub goo(). Public Class C5 : Inherits C2 ~~ BC30266: 'Public Overrides Sub goo()' cannot override 'Friend Overridable Overloads Sub goo()' because they have different access levels. Public Overrides Sub goo() ~~~ BC30610: Class 'C6' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): C1: Public MustOverride Sub goo(). Public Class C6 : Inherits C2 ~~ </expected>) End Sub <WorkItem(543794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543794")> <Fact()> Public Sub CrossLanguageTest4() Dim vb1Compilation = CreateVisualBasicCompilation("VB1", <![CDATA[Public MustInherit Class C1 MustOverride Sub goo() End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim vb1Verifier = CompileAndVerify(vb1Compilation) vb1Verifier.VerifyDiagnostics() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("VB2")] public abstract class C2 : C1 { new internal virtual void goo() { } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation}) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[MustInherit Public Class C3 : Inherits C2 Friend Overrides Sub goo() End Sub End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation, cs1Compilation}) CompileAndVerify(vb2Compilation).VerifyDiagnostics() End Sub <Fact(), WorkItem(544536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544536")> Public Sub VBOverrideCsharpOptional() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[ public abstract class Trivia { public abstract void Format(int i, int j = 2); } public class Whitespace : Trivia { public override void Format(int i, int j) {} } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[ MustInherit Class AbstractLineBreakTrivia Inherits Whitespace Public Overrides Sub Format(i As Integer, j As Integer) End Sub End Class Class AfterStatementTerminatorTokenTrivia Inherits AbstractLineBreakTrivia End Class ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={cs1Compilation}) CompileAndVerify(vb2Compilation).VerifyDiagnostics() End Sub <Fact()> Public Sub VBOverrideCsharpOptional2() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[ public abstract class Trivia { public abstract void Format(int i, int j = 2); } public class Whitespace : Trivia { public override void Format(int i, int j) {} } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[ MustInherit Class AbstractLineBreakTrivia Inherits Trivia Public Overrides Sub Format(i As Integer, j As Integer) End Sub End Class Class AfterStatementTerminatorTokenTrivia Inherits AbstractLineBreakTrivia End Class ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={cs1Compilation}) CompilationUtils.AssertTheseDiagnostics(vb2Compilation, <expected> BC30308: 'Public Overrides Sub Format(i As Integer, j As Integer)' cannot override 'Public MustOverride Overloads Sub Format(i As Integer, [j As Integer = 2])' because they differ by optional parameters. Public Overrides Sub Format(i As Integer, j As Integer) ~~~~~~ </expected>) End Sub <Fact()> Public Sub OverloadingBasedOnOptionalParameters() ' NOTE: this matches Dev11 implementation, not Dev10 Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C ' allowed Shared Sub f(ByVal x As Integer) End Sub Shared Sub f(ByVal x As Integer, Optional ByVal y As Integer = 0) End Sub Shared Sub f(ByVal x As Integer, Optional ByVal s As String = "") End Sub End Class Class C2 ' allowed Shared Sub f(ByVal x As Integer, Optional ByVal y As Short = 1) End Sub Shared Sub f(ByVal x As Integer, Optional ByVal y As Integer = 1) End Sub End Class Class C3 ' allowed Shared Sub f() End Sub Shared Sub f(Optional ByVal x As Integer = 0) End Sub End Class Class C4 ' allowed` Shared Sub f(Optional ByVal x As Integer = 0) End Sub Shared Sub f(ByVal ParamArray xx As Integer()) End Sub End Class Class C5 ' disallowed Shared Sub f(Optional ByVal x As Integer = 0) End Sub Shared Sub f(ByVal x As Integer) End Sub End Class Class C6 ' disallowed Shared Sub f(Optional ByVal x As Integer() = Nothing) End Sub Shared Sub f(ByVal ParamArray xx As Integer()) End Sub End Class Class C7 ' disallowed Shared Sub f(Optional ByVal x As Integer = 0) End Sub Shared Sub f(ByRef x As Integer) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30300: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(x As Integer)' cannot overload each other because they differ only by optional parameters. Shared Sub f(Optional ByVal x As Integer = 0) ~ BC30300: 'Public Shared Sub f([x As Integer() = Nothing])' and 'Public Shared Sub f(ParamArray xx As Integer())' cannot overload each other because they differ only by optional parameters. Shared Sub f(Optional ByVal x As Integer() = Nothing) ~ BC30368: 'Public Shared Sub f([x As Integer() = Nothing])' and 'Public Shared Sub f(ParamArray xx As Integer())' cannot overload each other because they differ only by parameters declared 'ParamArray'. Shared Sub f(Optional ByVal x As Integer() = Nothing) ~ BC30300: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(ByRef x As Integer)' cannot overload each other because they differ only by optional parameters. Shared Sub f(Optional ByVal x As Integer = 0) ~ BC30345: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(ByRef x As Integer)' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'. Shared Sub f(Optional ByVal x As Integer = 0) ~ </errors>) End Sub <Fact()> Public Sub HidingBySignatureWithOptionalParameters() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class A Public Overridable Sub f(Optional x As String = "") Console.WriteLine("A::f(Optional x As String = """")") End Sub End Class Class B Inherits A Public Overridable Overloads Sub f() Console.WriteLine("B::f()") End Sub End Class Class C Inherits B Public Sub f(Optional x As String = "") Console.WriteLine("C::f(Optional x As String = """")") End Sub Public Shared Sub Main() Dim c As B = New C c.f() c.f(1) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC40005: sub 'f' shadows an overridable method in the base class 'B'. To override the base method, this method must be declared 'Overrides'. Public Sub f(Optional x As String = "") ~ </errors>) End Sub <Fact()> Public Sub BC31404ForOverloadingBasedOnOptionalParameters() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> MustInherit Class A Public MustOverride Sub f(Optional x As String = "") End Class MustInherit Class B1 Inherits A Public MustOverride Overloads Sub f(Optional x As String = "") End Class MustInherit Class B2 Inherits A Public MustOverride Overloads Sub f(x As String) End Class MustInherit Class B3 Inherits A Public MustOverride Overloads Sub f(x As Integer, Optional y As String = "") End Class MustInherit Class B4 Inherits A Public MustOverride Overloads Sub f() End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC31404: 'Public MustOverride Overloads Sub f([x As String = ""])' cannot shadow a method declared 'MustOverride'. Public MustOverride Overloads Sub f(Optional x As String = "") ~ BC31404: 'Public MustOverride Overloads Sub f(x As String)' cannot shadow a method declared 'MustOverride'. Public MustOverride Overloads Sub f(x As String) ~ </errors>) End Sub <Fact()> Public Sub OverloadingWithNotAccessibleMethods() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class A Public Overridable Sub f(Optional x As String = "") End Sub End Class Class B Inherits A Public Overridable Overloads Sub f() End Sub End Class Class BB Inherits A Private Overloads Sub f() End Sub Private Overloads Sub f(Optional x As String = "") End Sub End Class Class C Inherits BB Public Overloads Overrides Sub f(Optional x As String = "") Console.Write("f(Optional x As String = "");") End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> </errors>) End Sub <Fact()> Public Sub AddressOfWithFunctionOrSub1() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class Clazz Public Shared Sub S(Optional x As Integer = 0) Console.WriteLine("Sub S") End Sub Public Shared Function S() As Boolean Console.WriteLine("Function S") Return True End Function Public Shared Sub Main() Dim a As action = AddressOf S a() End Sub End Class </file> </compilation>, expectedOutput:="Function S") End Sub <Fact, WorkItem(546816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546816")> Public Sub OverrideFinalizeWithoutNewslot() CompileAndVerify( <compilation> <file name="a.vb"> Class SelfDestruct Protected Overrides Sub Finalize() MyBase.Finalize() End Sub End Class </file> </compilation>, {MscorlibRef_v20}).VerifyDiagnostics() 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 Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenOverridingAndHiding Inherits BasicTestBase <WorkItem(540852, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540852")> <Fact> Public Sub TestSimpleMustOverride() Dim source = <compilation> <file name="a.vb"> Imports System MustInherit Class A Public MustOverride Function F As Integer() Protected MustOverride Sub Meth() Protected Friend MustOverride Property Prop As Integer() End Class </file> </compilation> Dim verifier = CompileAndVerify(source, expectedSignatures:= { Signature("A", "F", ".method public newslot strict abstract virtual instance System.Int32[] F() cil managed"), Signature("A", "Meth", ".method family newslot strict abstract virtual instance System.Void Meth() cil managed"), Signature("A", "get_Prop", ".method famorassem newslot strict specialname abstract virtual instance System.Int32[] get_Prop() cil managed"), Signature("A", "set_Prop", ".method famorassem newslot strict specialname abstract virtual instance System.Void set_Prop(System.Int32[] Value) cil managed"), Signature("A", "Prop", ".property readwrite System.Int32[] Prop") }) End Sub <WorkItem(528311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528311")> <WorkItem(540865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540865")> <Fact> Public Sub TestSimpleOverrides() Dim source = <compilation> <file name="a.vb"> MustInherit Class A Public MustOverride Sub F() End Class Class B Inherits A Public Overrides Sub F() End Sub End Class </file> </compilation> Dim verifier = CompileAndVerify(source, expectedSignatures:= { Signature("B", "F", ".method public hidebysig strict virtual instance System.Void F() cil managed"), Signature("A", "F", ".method public newslot strict abstract virtual instance System.Void F() cil managed") }) verifier.VerifyDiagnostics() End Sub <WorkItem(540884, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540884")> <Fact> Public Sub TestMustOverrideOverrides() Dim source = <compilation> <file name="a.vb"> Imports System Class A Public Overridable Sub G() Console.WriteLine("A.G") End Sub End Class MustInherit Class B Inherits A Public MustOverride Overrides Sub G() End Class </file> </compilation> Dim verifier = CompileAndVerify(source, expectedSignatures:= { Signature("B", "G", ".method public hidebysig strict abstract virtual instance System.Void G() cil managed"), Signature("A", "G", ".method public newslot strict virtual instance System.Void G() cil managed") }) verifier.VerifyDiagnostics() End Sub <WorkItem(542576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542576")> <Fact> Public Sub TestDontMergePartials() Dim source = <compilation> <file name="a.vb"> MustInherit Class A MustOverride Function F() As Integer Overridable Sub G() End Sub End Class Partial Class B Inherits A 'This would normally be an error if this partial part for class B 'had the NotInheritable modifier (i.e. NotOverridable and NotInheritable 'can't be combined). Strangely Dev10 doesn't report the same error 'when the NotInheritable modifier appears on a different partial part. NotOverridable Overrides Function F() As Integer Return 1 End Function 'This would normally be an error if this partial part for class B 'had the NotInheritable modifier (i.e. NotOverridable and NotInheritable 'can't be combined). Strangely Dev10 doesn't report the same error 'when the NotInheritable modifier appears on a different partial part. NotOverridable Overrides Sub G() End Sub End Class</file> <file name="b.vb"> NotInheritable Class B Inherits A End Class </file> </compilation> CompileAndVerify(source, expectedSignatures:= { Signature("B", "F", ".method public hidebysig strict virtual final instance System.Int32 F() cil managed"), Signature("A", "F", ".method public newslot strict abstract virtual instance System.Int32 F() cil managed"), Signature("B", "G", ".method public hidebysig strict virtual final instance System.Void G() cil managed"), Signature("A", "G", ".method public newslot strict virtual instance System.Void G() cil managed") }). VerifyDiagnostics() End Sub <WorkItem(543751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543751")> <Fact(), WorkItem(543751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543751")> Public Sub TestMustOverloadWithOptional() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Const str As String = "" Sub Main(args As String()) End Sub Function fun() test(temp:=Nothing, x:=1) Return Nothing End Function Function test(ByRef x As Integer, temp As Object, Optional y As String = str, Optional z As Object = Nothing) Return Nothing End Function Function test(ByRef x As Integer, Optional temp As Object = Nothing) Return Nothing End Function End Module </file> </compilation>). VerifyDiagnostics() End Sub <Fact()> Public Sub CrossLanguageCase1() 'Note: For this case Dev10 produces errors (see below) while Roslyn works fine. We believe this 'is a bug in Dev10 that we fixed in Roslyn - the change is non-breaking. Dim vb1Compilation = CreateVisualBasicCompilation("VB1", <![CDATA[Public MustInherit Class C1 MustOverride Sub goo() End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim vb1Verifier = CompileAndVerify(vb1Compilation) vb1Verifier.VerifyDiagnostics() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[using System; public abstract class C2 : C1 { new internal virtual void goo() { Console.WriteLine("C2"); } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation}) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[Imports System Public Class C3 : Inherits C2 Public Overrides Sub goo Console.WriteLine("C3") End Sub End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation, cs1Compilation}) Dim vb2Verifier = CompileAndVerify(vb2Compilation) vb2Verifier.VerifyDiagnostics() 'Dev10 reports an error for the below compilation - Roslyn on the other hand allows this code to compile without errors. 'VB3.vb(2) : error BC30610: Class 'C4' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): 'C1 : Public MustOverride Sub goo(). 'Public Class C4 : Inherits C3 ' ~~ Dim vb3Compilation = CreateVisualBasicCompilation("VB3", <![CDATA[ Imports System Public Class C4 : Inherits C3 End Class Public Class C5 : Inherits C2 ' Corresponding case in C# results in PEVerify errors - See test 'CrossLanguageCase1' in CodeGenOverridingAndHiding.cs Public Overrides Sub goo() Console.WriteLine("C5") End Sub End Class Public Module Program Sub Main() Dim x As C1 = New C4 x.goo() Dim y As C2 = New C5 y.Goo() End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation}) Dim vb3Verifier = CompileAndVerify(vb3Compilation, expectedOutput:=<![CDATA[C3 C5]]>) vb3Verifier.VerifyDiagnostics() End Sub <Fact()> Public Sub CrossLanguageCase2() 'Note: For this case Dev10 produces errors (see below) while Roslyn works fine. We believe this 'is a bug in Dev10 that we fixed in Roslyn - the change is non-breaking. Dim vb1Compilation = CreateVisualBasicCompilation("VB1", <![CDATA[Public MustInherit Class C1 MustOverride Sub goo() End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim vb1Verifier = CompileAndVerify(vb1Compilation) vb1Verifier.VerifyDiagnostics() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[using System; [assembly:System.Runtime.CompilerServices.InternalsVisibleTo("VB3")] public abstract class C2 : C1 { new internal virtual void goo() { Console.WriteLine("C2"); } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation}) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[Imports System Public Class C3 : Inherits C2 Public Overrides Sub goo Console.WriteLine("C3") End Sub End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation, cs1Compilation}) Dim vb2Verifier = CompileAndVerify(vb2Compilation) vb2Verifier.VerifyDiagnostics() 'Dev10 reports an error for the below compilation - Roslyn on the other hand allows this code to compile without errors. 'VB3.vb(2) : error BC30610: Class 'C4' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): 'C1 : Public MustOverride Sub goo(). 'Public Class C4 : Inherits C3 ' ~~ Dim vb3Compilation = CreateVisualBasicCompilation("VB3", <![CDATA[Imports System Public Class C4 : Inherits C3 Public Overrides Sub goo Console.WriteLine("C4") End Sub End Class Public Module Program Sub Main() Dim x As C1 = New C4 x.goo Dim y As C2 = New C4 y.goo End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation}) Dim vb3Verifier = CompileAndVerify(vb3Compilation, expectedOutput:=<![CDATA[C4 C2]]>) vb3Verifier.VerifyDiagnostics() End Sub <Fact()> Public Sub CrossLanguageCase3() 'Note: Dev10 and Roslyn produce identical errors for this case. Dim vb1Compilation = CreateVisualBasicCompilation("VB1", <![CDATA[Public MustInherit Class C1 MustOverride Sub goo() End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim vb1Verifier = CompileAndVerify(vb1Compilation) vb1Verifier.VerifyDiagnostics() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("VB3")] public abstract class C2 : C1 { new internal virtual void goo() { } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation}) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[Public Class C3 : Inherits C2 Public Overrides Sub goo End Sub End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation, cs1Compilation}) Dim vb2Verifier = CompileAndVerify(vb2Compilation) vb2Verifier.VerifyDiagnostics() Dim vb3Compilation = CreateVisualBasicCompilation("VB3", <![CDATA[MustInherit Public Class C4 : Inherits C3 Public Overrides Sub goo End Sub End Class Public Class C5 : Inherits C2 Public Overrides Sub goo() End Sub End Class Public Class C6 : Inherits C2 Friend Overrides Sub goo() End Sub End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation}) vb3Compilation.AssertTheseDiagnostics(<expected> BC30610: Class 'C5' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): C1: Public MustOverride Sub goo(). Public Class C5 : Inherits C2 ~~ BC30266: 'Public Overrides Sub goo()' cannot override 'Friend Overridable Overloads Sub goo()' because they have different access levels. Public Overrides Sub goo() ~~~ BC30610: Class 'C6' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): C1: Public MustOverride Sub goo(). Public Class C6 : Inherits C2 ~~ </expected>) End Sub <WorkItem(543794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543794")> <Fact()> Public Sub CrossLanguageTest4() Dim vb1Compilation = CreateVisualBasicCompilation("VB1", <![CDATA[Public MustInherit Class C1 MustOverride Sub goo() End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim vb1Verifier = CompileAndVerify(vb1Compilation) vb1Verifier.VerifyDiagnostics() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("VB2")] public abstract class C2 : C1 { new internal virtual void goo() { } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation}) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[MustInherit Public Class C3 : Inherits C2 Friend Overrides Sub goo() End Sub End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={vb1Compilation, cs1Compilation}) CompileAndVerify(vb2Compilation).VerifyDiagnostics() End Sub <Fact(), WorkItem(544536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544536")> Public Sub VBOverrideCsharpOptional() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[ public abstract class Trivia { public abstract void Format(int i, int j = 2); } public class Whitespace : Trivia { public override void Format(int i, int j) {} } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[ MustInherit Class AbstractLineBreakTrivia Inherits Whitespace Public Overrides Sub Format(i As Integer, j As Integer) End Sub End Class Class AfterStatementTerminatorTokenTrivia Inherits AbstractLineBreakTrivia End Class ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={cs1Compilation}) CompileAndVerify(vb2Compilation).VerifyDiagnostics() End Sub <Fact()> Public Sub VBOverrideCsharpOptional2() Dim cs1Compilation = CreateCSharpCompilation("CS1", <![CDATA[ public abstract class Trivia { public abstract void Format(int i, int j = 2); } public class Whitespace : Trivia { public override void Format(int i, int j) {} } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) cs1Compilation.VerifyDiagnostics() Dim vb2Compilation = CreateVisualBasicCompilation("VB2", <![CDATA[ MustInherit Class AbstractLineBreakTrivia Inherits Trivia Public Overrides Sub Format(i As Integer, j As Integer) End Sub End Class Class AfterStatementTerminatorTokenTrivia Inherits AbstractLineBreakTrivia End Class ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations:={cs1Compilation}) CompilationUtils.AssertTheseDiagnostics(vb2Compilation, <expected> BC30308: 'Public Overrides Sub Format(i As Integer, j As Integer)' cannot override 'Public MustOverride Overloads Sub Format(i As Integer, [j As Integer = 2])' because they differ by optional parameters. Public Overrides Sub Format(i As Integer, j As Integer) ~~~~~~ </expected>) End Sub <Fact()> Public Sub OverloadingBasedOnOptionalParameters() ' NOTE: this matches Dev11 implementation, not Dev10 Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C ' allowed Shared Sub f(ByVal x As Integer) End Sub Shared Sub f(ByVal x As Integer, Optional ByVal y As Integer = 0) End Sub Shared Sub f(ByVal x As Integer, Optional ByVal s As String = "") End Sub End Class Class C2 ' allowed Shared Sub f(ByVal x As Integer, Optional ByVal y As Short = 1) End Sub Shared Sub f(ByVal x As Integer, Optional ByVal y As Integer = 1) End Sub End Class Class C3 ' allowed Shared Sub f() End Sub Shared Sub f(Optional ByVal x As Integer = 0) End Sub End Class Class C4 ' allowed` Shared Sub f(Optional ByVal x As Integer = 0) End Sub Shared Sub f(ByVal ParamArray xx As Integer()) End Sub End Class Class C5 ' disallowed Shared Sub f(Optional ByVal x As Integer = 0) End Sub Shared Sub f(ByVal x As Integer) End Sub End Class Class C6 ' disallowed Shared Sub f(Optional ByVal x As Integer() = Nothing) End Sub Shared Sub f(ByVal ParamArray xx As Integer()) End Sub End Class Class C7 ' disallowed Shared Sub f(Optional ByVal x As Integer = 0) End Sub Shared Sub f(ByRef x As Integer) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30300: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(x As Integer)' cannot overload each other because they differ only by optional parameters. Shared Sub f(Optional ByVal x As Integer = 0) ~ BC30300: 'Public Shared Sub f([x As Integer() = Nothing])' and 'Public Shared Sub f(ParamArray xx As Integer())' cannot overload each other because they differ only by optional parameters. Shared Sub f(Optional ByVal x As Integer() = Nothing) ~ BC30368: 'Public Shared Sub f([x As Integer() = Nothing])' and 'Public Shared Sub f(ParamArray xx As Integer())' cannot overload each other because they differ only by parameters declared 'ParamArray'. Shared Sub f(Optional ByVal x As Integer() = Nothing) ~ BC30300: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(ByRef x As Integer)' cannot overload each other because they differ only by optional parameters. Shared Sub f(Optional ByVal x As Integer = 0) ~ BC30345: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(ByRef x As Integer)' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'. Shared Sub f(Optional ByVal x As Integer = 0) ~ </errors>) End Sub <Fact()> Public Sub HidingBySignatureWithOptionalParameters() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class A Public Overridable Sub f(Optional x As String = "") Console.WriteLine("A::f(Optional x As String = """")") End Sub End Class Class B Inherits A Public Overridable Overloads Sub f() Console.WriteLine("B::f()") End Sub End Class Class C Inherits B Public Sub f(Optional x As String = "") Console.WriteLine("C::f(Optional x As String = """")") End Sub Public Shared Sub Main() Dim c As B = New C c.f() c.f(1) End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC40005: sub 'f' shadows an overridable method in the base class 'B'. To override the base method, this method must be declared 'Overrides'. Public Sub f(Optional x As String = "") ~ </errors>) End Sub <Fact()> Public Sub BC31404ForOverloadingBasedOnOptionalParameters() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> MustInherit Class A Public MustOverride Sub f(Optional x As String = "") End Class MustInherit Class B1 Inherits A Public MustOverride Overloads Sub f(Optional x As String = "") End Class MustInherit Class B2 Inherits A Public MustOverride Overloads Sub f(x As String) End Class MustInherit Class B3 Inherits A Public MustOverride Overloads Sub f(x As Integer, Optional y As String = "") End Class MustInherit Class B4 Inherits A Public MustOverride Overloads Sub f() End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC31404: 'Public MustOverride Overloads Sub f([x As String = ""])' cannot shadow a method declared 'MustOverride'. Public MustOverride Overloads Sub f(Optional x As String = "") ~ BC31404: 'Public MustOverride Overloads Sub f(x As String)' cannot shadow a method declared 'MustOverride'. Public MustOverride Overloads Sub f(x As String) ~ </errors>) End Sub <Fact()> Public Sub OverloadingWithNotAccessibleMethods() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class A Public Overridable Sub f(Optional x As String = "") End Sub End Class Class B Inherits A Public Overridable Overloads Sub f() End Sub End Class Class BB Inherits A Private Overloads Sub f() End Sub Private Overloads Sub f(Optional x As String = "") End Sub End Class Class C Inherits BB Public Overloads Overrides Sub f(Optional x As String = "") Console.Write("f(Optional x As String = "");") End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> </errors>) End Sub <Fact()> Public Sub AddressOfWithFunctionOrSub1() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class Clazz Public Shared Sub S(Optional x As Integer = 0) Console.WriteLine("Sub S") End Sub Public Shared Function S() As Boolean Console.WriteLine("Function S") Return True End Function Public Shared Sub Main() Dim a As action = AddressOf S a() End Sub End Class </file> </compilation>, expectedOutput:="Function S") End Sub <Fact, WorkItem(546816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546816")> Public Sub OverrideFinalizeWithoutNewslot() CompileAndVerify( <compilation> <file name="a.vb"> Class SelfDestruct Protected Overrides Sub Finalize() MyBase.Finalize() End Sub End Class </file> </compilation>, {MscorlibRef_v20}).VerifyDiagnostics() End Sub End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.SByteTC.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct SByteTC : INumericTC<sbyte> { sbyte INumericTC<sbyte>.MinValue => sbyte.MinValue; sbyte INumericTC<sbyte>.MaxValue => sbyte.MaxValue; sbyte INumericTC<sbyte>.Zero => 0; bool INumericTC<sbyte>.Related(BinaryOperatorKind relation, sbyte left, sbyte right) { switch (relation) { case Equal: return left == right; case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } sbyte INumericTC<sbyte>.Next(sbyte value) { Debug.Assert(value != sbyte.MaxValue); return (sbyte)(value + 1); } sbyte INumericTC<sbyte>.Prev(sbyte value) { Debug.Assert(value != sbyte.MinValue); return (sbyte)(value - 1); } sbyte INumericTC<sbyte>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? (sbyte)0 : constantValue.SByteValue; public ConstantValue ToConstantValue(sbyte value) => ConstantValue.Create(value); string INumericTC<sbyte>.ToString(sbyte value) => value.ToString(); sbyte INumericTC<sbyte>.Random(Random random) { return (sbyte)random.Next(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct SByteTC : INumericTC<sbyte> { sbyte INumericTC<sbyte>.MinValue => sbyte.MinValue; sbyte INumericTC<sbyte>.MaxValue => sbyte.MaxValue; sbyte INumericTC<sbyte>.Zero => 0; bool INumericTC<sbyte>.Related(BinaryOperatorKind relation, sbyte left, sbyte right) { switch (relation) { case Equal: return left == right; case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } sbyte INumericTC<sbyte>.Next(sbyte value) { Debug.Assert(value != sbyte.MaxValue); return (sbyte)(value + 1); } sbyte INumericTC<sbyte>.Prev(sbyte value) { Debug.Assert(value != sbyte.MinValue); return (sbyte)(value - 1); } sbyte INumericTC<sbyte>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? (sbyte)0 : constantValue.SByteValue; public ConstantValue ToConstantValue(sbyte value) => ConstantValue.Create(value); string INumericTC<sbyte>.ToString(sbyte value) => value.ToString(); sbyte INumericTC<sbyte>.Random(Random random) { return (sbyte)random.Next(); } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeParameter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeParameter2))] public sealed class CodeParameter : AbstractCodeElement, EnvDTE.CodeParameter, EnvDTE80.CodeParameter2, IParameterKind { internal static EnvDTE.CodeParameter Create( CodeModelState state, AbstractCodeMember parent, string name) { var element = new CodeParameter(state, parent, name); return (EnvDTE.CodeParameter)ComAggregate.CreateAggregatedObject(element); } private readonly ParentHandle<AbstractCodeMember> _parentHandle; private readonly string _name; private CodeParameter( CodeModelState state, AbstractCodeMember parent, string name) : base(state, parent.FileCodeModel) { _parentHandle = new ParentHandle<AbstractCodeMember>(parent); _name = name; } private IParameterSymbol ParameterSymbol { get { return (IParameterSymbol)LookupSymbol(); } } private void UpdateNodeAndReacquireParentNodeKey<T>(Action<SyntaxNode, T> parameterUpdater, T value) { void updater(SyntaxNode n, T v) { var parentNode = _parentHandle.Value.LookupNode(); var parentNodePath = new SyntaxPath(parentNode); parameterUpdater(n, v); _parentHandle.Value.ReacquireNodeKey(parentNodePath, CancellationToken.None); } UpdateNode(updater, value); } protected override EnvDTE.CodeElements GetCollection() => GetCollection<CodeParameter>(Parent); protected override string GetName() => _name; protected override string GetFullName() { var node = LookupNode(); if (node == null) { return string.Empty; } return CodeModelService.GetParameterFullName(node); } internal override bool TryLookupNode(out SyntaxNode node) { node = null; var parentNode = _parentHandle.Value.LookupNode(); if (parentNode == null) { return false; } if (!CodeModelService.TryGetParameterNode(parentNode, _name, out var parameterNode)) { return false; } node = parameterNode; return node != null; } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementParameter; } } public override object Parent { get { return _parentHandle.Value; } } EnvDTE.CodeElement EnvDTE.CodeParameter.Parent { get { return (EnvDTE.CodeElement)Parent; } } EnvDTE.CodeElement EnvDTE80.CodeParameter2.Parent { get { return (EnvDTE.CodeElement)Parent; } } public override EnvDTE.CodeElements Children { get { return this.Attributes; } } public EnvDTE.CodeElements Attributes { get { return AttributeCollection.Create(this.State, this); } } public string DocComment { get { return string.Empty; } set { throw Exceptions.ThrowENotImpl(); } } public EnvDTE.CodeTypeRef Type { get { return CodeTypeRef.Create(this.State, this, GetProjectId(), ParameterSymbol.Type); } set { UpdateNodeAndReacquireParentNodeKey(FileCodeModel.UpdateType, value); } } public EnvDTE80.vsCMParameterKind ParameterKind { get { return CodeModelService.GetParameterKind(LookupNode()); } set { UpdateNodeAndReacquireParentNodeKey(FileCodeModel.UpdateParameterKind, value); } } public string DefaultValue { get { return CodeModelService.GetInitExpression(LookupNode()); } set { UpdateNode(FileCodeModel.UpdateInitExpression, value); } } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddAttribute(LookupNode(), name, value, position); }); } void IParameterKind.SetParameterPassingMode(PARAMETER_PASSING_MODE passingMode) => this.ParameterKind = this.CodeModelService.UpdateParameterKind(ParameterKind, passingMode); void IParameterKind.SetParameterArrayDimensions(int dimensions) { var type = this.ParameterSymbol.Type; var compilation = this.FileCodeModel.GetCompilation(); var elementType = type is IArrayTypeSymbol ? ((IArrayTypeSymbol)type).ElementType : type; // The original C# implementation had a weird behavior where it wold allow setting array dimensions // to 0 to create an array with a single rank. var rank = Math.Max(dimensions, 1); var newType = compilation.CreateArrayTypeSymbol(elementType, rank); this.Type = CodeTypeRef.Create(this.State, this, GetProjectId(), newType); } int IParameterKind.GetParameterArrayCount() { var arrayType = this.ParameterSymbol.Type as IArrayTypeSymbol; var count = 0; while (arrayType != null) { count++; arrayType = arrayType.ElementType as IArrayTypeSymbol; } return count; } int IParameterKind.GetParameterArrayDimensions(int index) { if (index < 0) { throw Exceptions.ThrowEInvalidArg(); } var arrayType = this.ParameterSymbol.Type as IArrayTypeSymbol; var count = 0; while (count < index && arrayType != null) { count++; arrayType = arrayType.ElementType as IArrayTypeSymbol; } if (arrayType == null) { throw Exceptions.ThrowEInvalidArg(); } return arrayType.Rank; } PARAMETER_PASSING_MODE IParameterKind.GetParameterPassingMode() { var parameterKind = this.ParameterKind; if ((parameterKind & EnvDTE80.vsCMParameterKind.vsCMParameterKindRef) != 0) { return PARAMETER_PASSING_MODE.cmParameterTypeInOut; } else if ((parameterKind & EnvDTE80.vsCMParameterKind.vsCMParameterKindOut) != 0) { return PARAMETER_PASSING_MODE.cmParameterTypeOut; } else { return PARAMETER_PASSING_MODE.cmParameterTypeIn; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeParameter2))] public sealed class CodeParameter : AbstractCodeElement, EnvDTE.CodeParameter, EnvDTE80.CodeParameter2, IParameterKind { internal static EnvDTE.CodeParameter Create( CodeModelState state, AbstractCodeMember parent, string name) { var element = new CodeParameter(state, parent, name); return (EnvDTE.CodeParameter)ComAggregate.CreateAggregatedObject(element); } private readonly ParentHandle<AbstractCodeMember> _parentHandle; private readonly string _name; private CodeParameter( CodeModelState state, AbstractCodeMember parent, string name) : base(state, parent.FileCodeModel) { _parentHandle = new ParentHandle<AbstractCodeMember>(parent); _name = name; } private IParameterSymbol ParameterSymbol { get { return (IParameterSymbol)LookupSymbol(); } } private void UpdateNodeAndReacquireParentNodeKey<T>(Action<SyntaxNode, T> parameterUpdater, T value) { void updater(SyntaxNode n, T v) { var parentNode = _parentHandle.Value.LookupNode(); var parentNodePath = new SyntaxPath(parentNode); parameterUpdater(n, v); _parentHandle.Value.ReacquireNodeKey(parentNodePath, CancellationToken.None); } UpdateNode(updater, value); } protected override EnvDTE.CodeElements GetCollection() => GetCollection<CodeParameter>(Parent); protected override string GetName() => _name; protected override string GetFullName() { var node = LookupNode(); if (node == null) { return string.Empty; } return CodeModelService.GetParameterFullName(node); } internal override bool TryLookupNode(out SyntaxNode node) { node = null; var parentNode = _parentHandle.Value.LookupNode(); if (parentNode == null) { return false; } if (!CodeModelService.TryGetParameterNode(parentNode, _name, out var parameterNode)) { return false; } node = parameterNode; return node != null; } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementParameter; } } public override object Parent { get { return _parentHandle.Value; } } EnvDTE.CodeElement EnvDTE.CodeParameter.Parent { get { return (EnvDTE.CodeElement)Parent; } } EnvDTE.CodeElement EnvDTE80.CodeParameter2.Parent { get { return (EnvDTE.CodeElement)Parent; } } public override EnvDTE.CodeElements Children { get { return this.Attributes; } } public EnvDTE.CodeElements Attributes { get { return AttributeCollection.Create(this.State, this); } } public string DocComment { get { return string.Empty; } set { throw Exceptions.ThrowENotImpl(); } } public EnvDTE.CodeTypeRef Type { get { return CodeTypeRef.Create(this.State, this, GetProjectId(), ParameterSymbol.Type); } set { UpdateNodeAndReacquireParentNodeKey(FileCodeModel.UpdateType, value); } } public EnvDTE80.vsCMParameterKind ParameterKind { get { return CodeModelService.GetParameterKind(LookupNode()); } set { UpdateNodeAndReacquireParentNodeKey(FileCodeModel.UpdateParameterKind, value); } } public string DefaultValue { get { return CodeModelService.GetInitExpression(LookupNode()); } set { UpdateNode(FileCodeModel.UpdateInitExpression, value); } } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddAttribute(LookupNode(), name, value, position); }); } void IParameterKind.SetParameterPassingMode(PARAMETER_PASSING_MODE passingMode) => this.ParameterKind = this.CodeModelService.UpdateParameterKind(ParameterKind, passingMode); void IParameterKind.SetParameterArrayDimensions(int dimensions) { var type = this.ParameterSymbol.Type; var compilation = this.FileCodeModel.GetCompilation(); var elementType = type is IArrayTypeSymbol ? ((IArrayTypeSymbol)type).ElementType : type; // The original C# implementation had a weird behavior where it wold allow setting array dimensions // to 0 to create an array with a single rank. var rank = Math.Max(dimensions, 1); var newType = compilation.CreateArrayTypeSymbol(elementType, rank); this.Type = CodeTypeRef.Create(this.State, this, GetProjectId(), newType); } int IParameterKind.GetParameterArrayCount() { var arrayType = this.ParameterSymbol.Type as IArrayTypeSymbol; var count = 0; while (arrayType != null) { count++; arrayType = arrayType.ElementType as IArrayTypeSymbol; } return count; } int IParameterKind.GetParameterArrayDimensions(int index) { if (index < 0) { throw Exceptions.ThrowEInvalidArg(); } var arrayType = this.ParameterSymbol.Type as IArrayTypeSymbol; var count = 0; while (count < index && arrayType != null) { count++; arrayType = arrayType.ElementType as IArrayTypeSymbol; } if (arrayType == null) { throw Exceptions.ThrowEInvalidArg(); } return arrayType.Rank; } PARAMETER_PASSING_MODE IParameterKind.GetParameterPassingMode() { var parameterKind = this.ParameterKind; if ((parameterKind & EnvDTE80.vsCMParameterKind.vsCMParameterKindRef) != 0) { return PARAMETER_PASSING_MODE.cmParameterTypeInOut; } else if ((parameterKind & EnvDTE80.vsCMParameterKind.vsCMParameterKindOut) != 0) { return PARAMETER_PASSING_MODE.cmParameterTypeOut; } else { return PARAMETER_PASSING_MODE.cmParameterTypeIn; } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Setup/Roslyn.ThirdPartyNotices/ThirdPartyNotices.rtf
{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fswiss\fprq2\fcharset0 Calibri;}{\f1\fmodern\fprq1\fcharset0 Consolas;}{\f2\fnil\fcharset0 Calibri;}} {\colortbl ;\red247\green247\blue247;\red36\green41\blue46;\red255\green255\blue255;\red0\green0\blue255;\red0\green0\blue0;} {\*\generator Riched20 10.0.17134}\viewkind4\uc1 \pard\widctlpar\highlight1\expndtw3\f0\fs22 NOTICES AND INFORMATION\par Do Not Translate or Localize\par \par \pard\nowidctlpar The \cf2\highlight3\expndtw0 .NET Compiler Platform ("Roslyn") \cf0\highlight1\expndtw3 software incorporates material from third parties. Microsoft makes certain open source code available at {{\field{\*\fldinst{HYPERLINK https://3rdpartysource.microsoft.com }}{\fldrslt{https://3rdpartysource.microsoft.com\ul0\cf0}}}}\f0\fs22 , or you may send a check or money order for US $5.00, including the product name, the open source component name, and version number, to:\par \pard\widctlpar\par Source Code Compliance Team\par Microsoft Corporation\par One Microsoft Way\par Redmond, WA 98052\par USA\par \par Notwithstanding any other terms, you may reverse engineer this software to the extent required to debug changes to any libraries licensed under the GNU Lesser General Public License.\par \par \pard\nowidctlpar\highlight0\expndtw0 %% \cf2\highlight3 .NET Compiler Platform \cf0\highlight0 NOTICES AND INFORMATION BEGIN HERE\par =========================================\par \par {{\field{\*\fldinst{HYPERLINK https://github.com/dotnet/roslyn }}{\fldrslt{https://github.com/dotnet/roslyn\ul0\cf0}}}}\f0\fs22\par \par \cf5\highlight3 The MIT License (MIT) \par \par Copyright (c) .NET Foundation and Contributors All rights reserved. \par \par Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: \par \par The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. \par \par THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\highlight0\par \cf0 =========================================\par END OF \cf2\highlight3 .NET Compiler Platform \cf0\highlight0 NOTICES AND INFORMATION\par \par %% .NET Core Libraries (CoreFX) NOTICES AND INFORMATION BEGIN HERE\par =========================================\par \par {{\field{\*\fldinst{HYPERLINK https://github.com/dotnet/corefx }}{\fldrslt{https://github.com/dotnet/corefx\ul0\cf0}}}}\f0\fs22\par \par \cf5\highlight3 The MIT License (MIT) \par \par Copyright (c) .NET Foundation and Contributors All rights reserved. \par \par Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: \par \par The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. \par \par THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\cf0\highlight0\par =========================================\par END OF \cf2\highlight3 .\cf0\highlight0 NET Core Libraries (CoreFX) NOTICES AND INFORMATION\par \par %% DotNetTools NOTICES AND INFORMATION BEGIN HERE\par =========================================\par \par {{\field{\*\fldinst{HYPERLINK https://github.com/aspnet/DotNetTools }}{\fldrslt{https://github.com/aspnet/DotNetTools\ul0\cf0}}}}\f0\fs22\par \par Copyright (c) .NET Foundation and Contributors\par \par All rights reserved.\par \par Licensed under the Apache License, Version 2.0 (the "License"); you may not use\par this file except in compliance with the License. You may obtain a copy of the\par License at\par \par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f0\fs22\par \par Unless required by applicable law or agreed to in writing, software distributed\par under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR\par CONDITIONS OF ANY KIND, either express or implied. See the License for the\par specific language governing permissions and limitations under the License.\par \par =========================================\par END OF DotNetTools NOTICES AND INFORMATION\par \par %% DocFX NOTICES AND INFORMATION BEGIN HERE\par =========================================\par \par {{\field{\*\fldinst{HYPERLINK https://github.com/dotnet/docfx }}{\fldrslt{https://github.com/dotnet/docfx\ul0\cf0}}}}\f0\fs22\par \par \cf5\highlight3 The MIT License (MIT) \par \par Copyright (c) Microsoft Corporation \par \par Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: \par \par The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. \par \par THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\par \cf0\highlight0 =========================================\par END OF DocFX NOTICES AND INFORMATION\par \par %% MSBuild Locator NOTICES AND INFORMATION BEGIN HERE\par =========================================\par \par {{\field{\*\fldinst{HYPERLINK https://github.com/Microsoft/MSBuildLocator }}{\fldrslt{https://github.com/Microsoft/MSBuildLocator\ul0\cf0}}}}\f0\fs22\par \par \cf5\highlight3 MSBuild Locator \par \par MIT License \par \par Copyright (c) Microsoft Corporation. All rights reserved. \par \par Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: \par \par The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. \par \par THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE\cf0\highlight0 \par =========================================\par END OF MSBuild Locator NOTICES AND INFORMATION\par \par %% Humanizer NOTICES AND INFORMATION BEGIN HERE\par =========================================\par The MIT License (MIT)\par \par Copyright (c) 2012-2014 Mehdi Khalili\par \par Permission is hereby granted, free of charge, to any person obtaining a copy\par of this software and associated documentation files (the "Software"), to deal\par in the Software without restriction, including without limitation the rights\par to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\par copies of the Software, and to permit persons to whom the Software is\par furnished to do so, subject to the following conditions:\par \par The above copyright notice and this permission notice shall be included in\par all copies or substantial portions of the Software.\par \par THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\par IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\par FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\par AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\par LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\par OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\par THE SOFTWARE.\par \par ==============================================================================\par \par Inflector ({{\field{\*\fldinst{HYPERLINK https://github.com/srkirkland/Inflector }}{\fldrslt{https://github.com/srkirkland/Inflector\ul0\cf0}}}}\f0\fs22 )\par The MIT License (MIT)\par Copyright (c) 2013 Scott Kirkland\par \par ==============================================================================\par \par ByteSize ({{\field{\*\fldinst{HYPERLINK https://github.com/omar/ByteSize }}{\fldrslt{https://github.com/omar/ByteSize\ul0\cf0}}}}\f0\fs22 )\par The MIT License (MIT)\par Copyright (c) 2013-2014 Omar Khudeira ({{\field{\*\fldinst{HYPERLINK http://omar.io }}{\fldrslt{http://omar.io\ul0\cf0}}}}\f0\fs22 )\par \par ==============================================================================\par =========================================\par END OF Humanizer NOTICES AND INFORMATION\par \par %% ICSharpCode.Decompiler NOTICES AND INFORMATION BEGIN HERE\par =========================================\par SPDX identifier - MIT\par \par MIT License\par \par Copyright 2011-2019 AlphaSierraPapa\par \par Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\par \par The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\par \par THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\par =========================================\par END OF ICSharpCode.Decompiler NOTICES AND INFORMATION\par \par %% SQLitePCLRaw.bundle_green NOTICES AND INFORMATION BEGIN HERE\par =========================================\par \par Apache License\par Version 2.0, January 2004\par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/ }}{\fldrslt{http://www.apache.org/licenses/\ul0\cf0}}}}\f0\fs22\par \par TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\par \par 1. Definitions.\par \par "License" shall mean the terms and conditions for use, reproduction,\par and distribution as defined by Sections 1 through 9 of this document.\par \par "Licensor" shall mean the copyright owner or entity authorized by\par the copyright owner that is granting the License.\par \par "Legal Entity" shall mean the union of the acting entity and all\par other entities that control, are controlled by, or are under common\par control with that entity. For the purposes of this definition,\par "control" means (i) the power, direct or indirect, to cause the\par direction or management of such entity, whether by contract or\par otherwise, or (ii) ownership of fifty percent (50%) or more of the\par outstanding shares, or (iii) beneficial ownership of such entity.\par \par "You" (or "Your") shall mean an individual or Legal Entity\par exercising permissions granted by this License.\par \par "Source" form shall mean the preferred form for making modifications,\par including but not limited to software source code, documentation\par source, and configuration files.\par \par "Object" form shall mean any form resulting from mechanical\par transformation or translation of a Source form, including but\par not limited to compiled object code, generated documentation,\par and conversions to other media types.\par \par "Work" shall mean the work of authorship, whether in Source or\par Object form, made available under the License, as indicated by a\par copyright notice that is included in or attached to the work\par (an example is provided in the Appendix below).\par \par "Derivative Works" shall mean any work, whether in Source or Object\par form, that is based on (or derived from) the Work and for which the\par editorial revisions, annotations, elaborations, or other modifications\par represent, as a whole, an original work of authorship. For the purposes\par of this License, Derivative Works shall not include works that remain\par separable from, or merely link (or bind by name) to the interfaces of,\par the Work and Derivative Works thereof.\par \par "Contribution" shall mean any work of authorship, including\par the original version of the Work and any modifications or additions\par to that Work or Derivative Works thereof, that is intentionally\par submitted to Licensor for inclusion in the Work by the copyright owner\par or by an individual or Legal Entity authorized to submit on behalf of\par the copyright owner. For the purposes of this definition, "submitted"\par means any form of electronic, verbal, or written communication sent\par to the Licensor or its representatives, including but not limited to\par communication on electronic mailing lists, source code control systems,\par and issue tracking systems that are managed by, or on behalf of, the\par Licensor for the purpose of discussing and improving the Work, but\par excluding communication that is conspicuously marked or otherwise\par designated in writing by the copyright owner as "Not a Contribution."\par \par "Contributor" shall mean Licensor and any individual or Legal Entity\par on behalf of whom a Contribution has been received by Licensor and\par subsequently incorporated within the Work.\par \par 2. Grant of Copyright License. Subject to the terms and conditions of\par this License, each Contributor hereby grants to You a perpetual,\par worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par copyright license to reproduce, prepare Derivative Works of,\par publicly display, publicly perform, sublicense, and distribute the\par Work and such Derivative Works in Source or Object form.\par \par 3. Grant of Patent License. Subject to the terms and conditions of\par this License, each Contributor hereby grants to You a perpetual,\par worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par (except as stated in this section) patent license to make, have made,\par use, offer to sell, sell, import, and otherwise transfer the Work,\par where such license applies only to those patent claims licensable\par by such Contributor that are necessarily infringed by their\par Contribution(s) alone or by combination of their Contribution(s)\par with the Work to which such Contribution(s) was submitted. If You\par institute patent litigation against any entity (including a\par cross-claim or counterclaim in a lawsuit) alleging that the Work\par or a Contribution incorporated within the Work constitutes direct\par or contributory patent infringement, then any patent licenses\par granted to You under this License for that Work shall terminate\par as of the date such litigation is filed.\par \par 4. Redistribution. You may reproduce and distribute copies of the\par Work or Derivative Works thereof in any medium, with or without\par modifications, and in Source or Object form, provided that You\par meet the following conditions:\par \par (a) You must give any other recipients of the Work or\par Derivative Works a copy of this License; and\par \par (b) You must cause any modified files to carry prominent notices\par stating that You changed the files; and\par \par (c) You must retain, in the Source form of any Derivative Works\par that You distribute, all copyright, patent, trademark, and\par attribution notices from the Source form of the Work,\par excluding those notices that do not pertain to any part of\par the Derivative Works; and\par \par (d) If the Work includes a "NOTICE" text file as part of its\par distribution, then any Derivative Works that You distribute must\par include a readable copy of the attribution notices contained\par within such NOTICE file, excluding those notices that do not\par pertain to any part of the Derivative Works, in at least one\par of the following places: within a NOTICE text file distributed\par as part of the Derivative Works; within the Source form or\par documentation, if provided along with the Derivative Works; or,\par within a display generated by the Derivative Works, if and\par wherever such third-party notices normally appear. The contents\par of the NOTICE file are for informational purposes only and\par do not modify the License. You may add Your own attribution\par notices within Derivative Works that You distribute, alongside\par or as an addendum to the NOTICE text from the Work, provided\par that such additional attribution notices cannot be construed\par as modifying the License.\par \par You may add Your own copyright statement to Your modifications and\par may provide additional or different license terms and conditions\par for use, reproduction, or distribution of Your modifications, or\par for any such Derivative Works as a whole, provided Your use,\par reproduction, and distribution of the Work otherwise complies with\par the conditions stated in this License.\par \par 5. Submission of Contributions. Unless You explicitly state otherwise,\par any Contribution intentionally submitted for inclusion in the Work\par by You to the Licensor shall be under the terms and conditions of\par this License, without any additional terms or conditions.\par Notwithstanding the above, nothing herein shall supersede or modify\par the terms of any separate license agreement you may have executed\par with Licensor regarding such Contributions.\par \par 6. Trademarks. This License does not grant permission to use the trade\par names, trademarks, service marks, or product names of the Licensor,\par except as required for reasonable and customary use in describing the\par origin of the Work and reproducing the content of the NOTICE file.\par \par 7. Disclaimer of Warranty. Unless required by applicable law or\par agreed to in writing, Licensor provides the Work (and each\par Contributor provides its Contributions) on an "AS IS" BASIS,\par WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\par implied, including, without limitation, any warranties or conditions\par of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\par PARTICULAR PURPOSE. You are solely responsible for determining the\par appropriateness of using or redistributing the Work and assume any\par risks associated with Your exercise of permissions under this License.\par \par 8. Limitation of Liability. In no event and under no legal theory,\par whether in tort (including negligence), contract, or otherwise,\par unless required by applicable law (such as deliberate and grossly\par negligent acts) or agreed to in writing, shall any Contributor be\par liable to You for damages, including any direct, indirect, special,\par incidental, or consequential damages of any character arising as a\par result of this License or out of the use or inability to use the\par Work (including but not limited to damages for loss of goodwill,\par work stoppage, computer failure or malfunction, or any and all\par other commercial damages or losses), even if such Contributor\par has been advised of the possibility of such damages.\par \par 9. Accepting Warranty or Additional Liability. While redistributing\par the Work or Derivative Works thereof, You may choose to offer,\par and charge a fee for, acceptance of support, warranty, indemnity,\par or other liability obligations and/or rights consistent with this\par License. However, in accepting such obligations, You may act only\par on Your own behalf and on Your sole responsibility, not on behalf\par of any other Contributor, and only if You agree to indemnify,\par defend, and hold each Contributor harmless for any liability\par incurred by, or claims asserted against, such Contributor by reason\par of your accepting any such warranty or additional liability.\par \par END OF TERMS AND CONDITIONS\par \par APPENDIX: How to apply the Apache License to your work.\par \par To apply the Apache License to your work, attach the following\par boilerplate notice, with the fields enclosed by brackets "[]"\par replaced with your own identifying information. (Don't include\par the brackets!) The text should be enclosed in the appropriate\par comment syntax for the file format. We also recommend that a\par file or class name and description of purpose be included on the\par same "printed page" as the copyright notice for easier\par identification within third-party archives.\par \par Copyright [yyyy] [name of copyright owner]\par \par Licensed under the Apache License, Version 2.0 (the "License");\par you may not use this file except in compliance with the License.\par You may obtain a copy of the License at\par \par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f0\fs22\par \par Unless required by applicable law or agreed to in writing, software\par distributed under the License is distributed on an "AS IS" BASIS,\par WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\par See the License for the specific language governing permissions and\par limitations under the License.\par \par \pard\widctlpar\tx916\tx1832\tx2748\tx3664\tx4580\tx5496\tx6412\tx7328\tx8244\tx9160\tx10076\tx10992\tx11908\tx12824\tx13740\tx14656\cf5\f1\fs20 ----------------------------------------------------------------\par Copyright on SQLitePCL.raw\par ----------------------------------------------------------------\par \par Version prior to 2.0 were labeled with the copyright owned by\par Zumero. In 2.0, this changed to SourceGear. There is no legal\par distinction, as Zumero is simply a dba name for SourceGear.\par \par And in either case, the open source license remains the same,\par Apache v2.\par \par ----------------------------------------------------------------\par License for SQLite\par ----------------------------------------------------------------\par \par ** The author disclaims copyright to this source code. In place of\par ** a legal notice, here is a blessing:\par **\par ** May you do good and not evil.\par ** May you find forgiveness for yourself and forgive others.\par ** May you share freely, never taking more than you give.\par **\par \par \par ----------------------------------------------------------------\par License for MS Open Tech\par ----------------------------------------------------------------\par \par // Copyright \'a9 Microsoft Open Technologies, Inc.\par // All Rights Reserved\par // Licensed under the Apache License, Version 2.0 (the "License"); you may not\par // use this file except in compliance with the License. You may obtain a copy\par // of the License at \par // {\cf0{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f1\fs20\par // \par // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\par // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY\par // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\par // MERCHANTABLITY OR NON-INFRINGEMENT.\par // \par // See the Apache 2 License for the specific language governing permissions and\par // limitations under the License.\par \par \par ----------------------------------------------------------------\par License for SQLCipher\par ----------------------------------------------------------------\par \par Copyright (c) 2008, ZETETIC LLC\par All rights reserved.\par \par Redistribution and use in source and binary forms, with or without\par modification, are permitted provided that the following conditions are met:\par * Redistributions of source code must retain the above copyright\par notice, this list of conditions and the following disclaimer.\par * Redistributions in binary form must reproduce the above copyright\par notice, this list of conditions and the following disclaimer in the\par documentation and/or other materials provided with the distribution.\par * Neither the name of the ZETETIC LLC nor the\par names of its contributors may be used to endorse or promote products\par derived from this software without specific prior written permission.\par \par THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY\par EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\par WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\par DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY\par DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\par (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\par LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\par ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\par (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\par SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\par \par \par ----------------------------------------------------------------\par License for OpenSSL libcrypto\par ----------------------------------------------------------------\par \par LICENSE ISSUES\par ==============\par \par The OpenSSL toolkit stays under a dual license, i.e. both the conditions of\par the OpenSSL License and the original SSLeay license apply to the toolkit.\par See below for the actual license texts. Actually both licenses are BSD-style\par Open Source licenses. In case of any license issues related to OpenSSL\par please contact [email protected].\par \par OpenSSL License\par ---------------\par \par /* ====================================================================\par * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved.\par *\par * Redistribution and use in source and binary forms, with or without\par * modification, are permitted provided that the following conditions\par * are met:\par *\par * 1. Redistributions of source code must retain the above copyright\par * notice, this list of conditions and the following disclaimer. \par *\par * 2. Redistributions in binary form must reproduce the above copyright\par * notice, this list of conditions and the following disclaimer in\par * the documentation and/or other materials provided with the\par * distribution.\par *\par * 3. All advertising materials mentioning features or use of this\par * software must display the following acknowledgment:\par * "This product includes software developed by the OpenSSL Project\par * for use in the OpenSSL Toolkit. ({\cf0{\field{\*\fldinst{HYPERLINK http://www.openssl.org/ }}{\fldrslt{http://www.openssl.org/\ul0\cf0}}}}\f1\fs20 )"\par *\par * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to\par * endorse or promote products derived from this software without\par * prior written permission. For written permission, please contact\par * [email protected].\par *\par * 5. Products derived from this software may not be called "OpenSSL"\par * nor may "OpenSSL" appear in their names without prior written\par * permission of the OpenSSL Project.\par *\par * 6. Redistributions of any form whatsoever must retain the following\par * acknowledgment:\par * "This product includes software developed by the OpenSSL Project\par * for use in the OpenSSL Toolkit ({\cf0{\field{\*\fldinst{HYPERLINK http://www.openssl.org/ }}{\fldrslt{http://www.openssl.org/\ul0\cf0}}}}\f1\fs20 )"\par *\par * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY\par * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\par * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\par * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR\par * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\par * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\par * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\par * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\par * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\par * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\par * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\par * OF THE POSSIBILITY OF SUCH DAMAGE.\par * ====================================================================\par *\par * This product includes cryptographic software written by Eric Young\par * ([email protected]). This product includes software written by Tim\par * Hudson ([email protected]).\par *\par */\par \par Original SSLeay License\par -----------------------\par \par /* Copyright (C) 1995-1998 Eric Young ([email protected])\par * All rights reserved.\par *\par * This package is an SSL implementation written\par * by Eric Young ([email protected]).\par * The implementation was written so as to conform with Netscapes SSL.\par * \par * This library is free for commercial and non-commercial use as long as\par * the following conditions are aheared to. The following conditions\par * apply to all code found in this distribution, be it the RC4, RSA,\par * lhash, DES, etc., code; not just the SSL code. The SSL documentation\par * included with this distribution is covered by the same copyright terms\par * except that the holder is Tim Hudson ([email protected]).\par * \par * Copyright remains Eric Young's, and as such any Copyright notices in\par * the code are not to be removed.\par * If this package is used in a product, Eric Young should be given attribution\par * as the author of the parts of the library used.\par * This can be in the form of a textual message at program startup or\par * in documentation (online or textual) provided with the package.\par * \par * Redistribution and use in source and binary forms, with or without\par * modification, are permitted provided that the following conditions\par * are met:\par * 1. Redistributions of source code must retain the copyright\par * notice, this list of conditions and the following disclaimer.\par * 2. Redistributions in binary form must reproduce the above copyright\par * notice, this list of conditions and the following disclaimer in the\par * documentation and/or other materials provided with the distribution.\par * 3. All advertising materials mentioning features or use of this software\par * must display the following acknowledgement:\par * "This product includes cryptographic software written by\par * Eric Young ([email protected])"\par * The word 'cryptographic' can be left out if the rouines from the library\par * being used are not cryptographic related :-).\par * 4. If you include any Windows specific code (or a derivative thereof) from \par * the apps directory (application code) you must include an acknowledgement:\par * "This product includes software written by Tim Hudson ([email protected])"\par * \par * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND\par * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\par * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\par * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\par * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\par * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\par * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\par * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\par * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\par * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\par * SUCH DAMAGE.\par * \par * The licence and distribution terms for any publically available version or\par * derivative of this code cannot be changed. i.e. this code cannot simply be\par * copied and put under another distribution licence\par * [including the GNU Public Licence.]\par */\par \pard\nowidctlpar\cf0\f0\fs22\par =========================================\par END OF SQLitePCLRaw.bundle_green NOTICES AND INFORMATION\par \par %% SQLitePCLRaw.core NOTICES AND INFORMATION BEGIN HERE\par =========================================\par Apache License\par Version 2.0, January 2004\par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/ }}{\fldrslt{http://www.apache.org/licenses/\ul0\cf0}}}}\f0\fs22\par \par TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\par \par 1. Definitions.\par \par "License" shall mean the terms and conditions for use, reproduction,\par and distribution as defined by Sections 1 through 9 of this document.\par \par "Licensor" shall mean the copyright owner or entity authorized by\par the copyright owner that is granting the License.\par \par "Legal Entity" shall mean the union of the acting entity and all\par other entities that control, are controlled by, or are under common\par control with that entity. For the purposes of this definition,\par "control" means (i) the power, direct or indirect, to cause the\par direction or management of such entity, whether by contract or\par otherwise, or (ii) ownership of fifty percent (50%) or more of the\par outstanding shares, or (iii) beneficial ownership of such entity.\par \par "You" (or "Your") shall mean an individual or Legal Entity\par exercising permissions granted by this License.\par \par "Source" form shall mean the preferred form for making modifications,\par including but not limited to software source code, documentation\par source, and configuration files.\par \par "Object" form shall mean any form resulting from mechanical\par transformation or translation of a Source form, including but\par not limited to compiled object code, generated documentation,\par and conversions to other media types.\par \par "Work" shall mean the work of authorship, whether in Source or\par Object form, made available under the License, as indicated by a\par copyright notice that is included in or attached to the work\par (an example is provided in the Appendix below).\par \par "Derivative Works" shall mean any work, whether in Source or Object\par form, that is based on (or derived from) the Work and for which the\par editorial revisions, annotations, elaborations, or other modifications\par represent, as a whole, an original work of authorship. For the purposes\par of this License, Derivative Works shall not include works that remain\par separable from, or merely link (or bind by name) to the interfaces of,\par the Work and Derivative Works thereof.\par \par "Contribution" shall mean any work of authorship, including\par the original version of the Work and any modifications or additions\par to that Work or Derivative Works thereof, that is intentionally\par submitted to Licensor for inclusion in the Work by the copyright owner\par or by an individual or Legal Entity authorized to submit on behalf of\par the copyright owner. For the purposes of this definition, "submitted"\par means any form of electronic, verbal, or written communication sent\par to the Licensor or its representatives, including but not limited to\par communication on electronic mailing lists, source code control systems,\par and issue tracking systems that are managed by, or on behalf of, the\par Licensor for the purpose of discussing and improving the Work, but\par excluding communication that is conspicuously marked or otherwise\par designated in writing by the copyright owner as "Not a Contribution."\par \par "Contributor" shall mean Licensor and any individual or Legal Entity\par on behalf of whom a Contribution has been received by Licensor and\par subsequently incorporated within the Work.\par \par 2. Grant of Copyright License. Subject to the terms and conditions of\par this License, each Contributor hereby grants to You a perpetual,\par worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par copyright license to reproduce, prepare Derivative Works of,\par publicly display, publicly perform, sublicense, and distribute the\par Work and such Derivative Works in Source or Object form.\par \par 3. Grant of Patent License. Subject to the terms and conditions of\par this License, each Contributor hereby grants to You a perpetual,\par worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par (except as stated in this section) patent license to make, have made,\par use, offer to sell, sell, import, and otherwise transfer the Work,\par where such license applies only to those patent claims licensable\par by such Contributor that are necessarily infringed by their\par Contribution(s) alone or by combination of their Contribution(s)\par with the Work to which such Contribution(s) was submitted. If You\par institute patent litigation against any entity (including a\par cross-claim or counterclaim in a lawsuit) alleging that the Work\par or a Contribution incorporated within the Work constitutes direct\par or contributory patent infringement, then any patent licenses\par granted to You under this License for that Work shall terminate\par as of the date such litigation is filed.\par \par 4. Redistribution. You may reproduce and distribute copies of the\par Work or Derivative Works thereof in any medium, with or without\par modifications, and in Source or Object form, provided that You\par meet the following conditions:\par \par (a) You must give any other recipients of the Work or\par Derivative Works a copy of this License; and\par \par (b) You must cause any modified files to carry prominent notices\par stating that You changed the files; and\par \par (c) You must retain, in the Source form of any Derivative Works\par that You distribute, all copyright, patent, trademark, and\par attribution notices from the Source form of the Work,\par excluding those notices that do not pertain to any part of\par the Derivative Works; and\par \par (d) If the Work includes a "NOTICE" text file as part of its\par distribution, then any Derivative Works that You distribute must\par include a readable copy of the attribution notices contained\par within such NOTICE file, excluding those notices that do not\par pertain to any part of the Derivative Works, in at least one\par of the following places: within a NOTICE text file distributed\par as part of the Derivative Works; within the Source form or\par documentation, if provided along with the Derivative Works; or,\par within a display generated by the Derivative Works, if and\par wherever such third-party notices normally appear. The contents\par of the NOTICE file are for informational purposes only and\par do not modify the License. You may add Your own attribution\par notices within Derivative Works that You distribute, alongside\par or as an addendum to the NOTICE text from the Work, provided\par that such additional attribution notices cannot be construed\par as modifying the License.\par \par You may add Your own copyright statement to Your modifications and\par may provide additional or different license terms and conditions\par for use, reproduction, or distribution of Your modifications, or\par for any such Derivative Works as a whole, provided Your use,\par reproduction, and distribution of the Work otherwise complies with\par the conditions stated in this License.\par \par 5. Submission of Contributions. Unless You explicitly state otherwise,\par any Contribution intentionally submitted for inclusion in the Work\par by You to the Licensor shall be under the terms and conditions of\par this License, without any additional terms or conditions.\par Notwithstanding the above, nothing herein shall supersede or modify\par the terms of any separate license agreement you may have executed\par with Licensor regarding such Contributions.\par \par 6. Trademarks. This License does not grant permission to use the trade\par names, trademarks, service marks, or product names of the Licensor,\par except as required for reasonable and customary use in describing the\par origin of the Work and reproducing the content of the NOTICE file.\par \par 7. Disclaimer of Warranty. Unless required by applicable law or\par agreed to in writing, Licensor provides the Work (and each\par Contributor provides its Contributions) on an "AS IS" BASIS,\par WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\par implied, including, without limitation, any warranties or conditions\par of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\par PARTICULAR PURPOSE. You are solely responsible for determining the\par appropriateness of using or redistributing the Work and assume any\par risks associated with Your exercise of permissions under this License.\par \par 8. Limitation of Liability. In no event and under no legal theory,\par whether in tort (including negligence), contract, or otherwise,\par unless required by applicable law (such as deliberate and grossly\par negligent acts) or agreed to in writing, shall any Contributor be\par liable to You for damages, including any direct, indirect, special,\par incidental, or consequential damages of any character arising as a\par result of this License or out of the use or inability to use the\par Work (including but not limited to damages for loss of goodwill,\par work stoppage, computer failure or malfunction, or any and all\par other commercial damages or losses), even if such Contributor\par has been advised of the possibility of such damages.\par \par 9. Accepting Warranty or Additional Liability. While redistributing\par the Work or Derivative Works thereof, You may choose to offer,\par and charge a fee for, acceptance of support, warranty, indemnity,\par or other liability obligations and/or rights consistent with this\par License. However, in accepting such obligations, You may act only\par on Your own behalf and on Your sole responsibility, not on behalf\par of any other Contributor, and only if You agree to indemnify,\par defend, and hold each Contributor harmless for any liability\par incurred by, or claims asserted against, such Contributor by reason\par of your accepting any such warranty or additional liability.\par \par END OF TERMS AND CONDITIONS\par \par APPENDIX: How to apply the Apache License to your work.\par \par To apply the Apache License to your work, attach the following\par boilerplate notice, with the fields enclosed by brackets "[]"\par replaced with your own identifying information. (Don't include\par the brackets!) The text should be enclosed in the appropriate\par comment syntax for the file format. We also recommend that a\par file or class name and description of purpose be included on the\par same "printed page" as the copyright notice for easier\par identification within third-party archives.\par \par Copyright [yyyy] [name of copyright owner]\par \par Licensed under the Apache License, Version 2.0 (the "License");\par you may not use this file except in compliance with the License.\par You may obtain a copy of the License at\par \par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f0\fs22\par \par Unless required by applicable law or agreed to in writing, software\par distributed under the License is distributed on an "AS IS" BASIS,\par WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\par See the License for the specific language governing permissions and\par limitations under the License.\par \par \pard\widctlpar\tx916\tx1832\tx2748\tx3664\tx4580\tx5496\tx6412\tx7328\tx8244\tx9160\tx10076\tx10992\tx11908\tx12824\tx13740\tx14656\cf5\f1\fs20 ----------------------------------------------------------------\par Copyright on SQLitePCL.raw\par ----------------------------------------------------------------\par \par Version prior to 2.0 were labeled with the copyright owned by\par Zumero. In 2.0, this changed to SourceGear. There is no legal\par distinction, as Zumero is simply a dba name for SourceGear.\par \par And in either case, the open source license remains the same,\par Apache v2.\par \par ----------------------------------------------------------------\par License for SQLite\par ----------------------------------------------------------------\par \par ** The author disclaims copyright to this source code. In place of\par ** a legal notice, here is a blessing:\par **\par ** May you do good and not evil.\par ** May you find forgiveness for yourself and forgive others.\par ** May you share freely, never taking more than you give.\par **\par \par \par ----------------------------------------------------------------\par License for MS Open Tech\par ----------------------------------------------------------------\par \par // Copyright \'a9 Microsoft Open Technologies, Inc.\par // All Rights Reserved\par // Licensed under the Apache License, Version 2.0 (the "License"); you may not\par // use this file except in compliance with the License. You may obtain a copy\par // of the License at \par // {\cf0{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f1\fs20\par // \par // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\par // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY\par // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\par // MERCHANTABLITY OR NON-INFRINGEMENT.\par // \par // See the Apache 2 License for the specific language governing permissions and\par // limitations under the License.\par \par \par ----------------------------------------------------------------\par License for SQLCipher\par ----------------------------------------------------------------\par \par Copyright (c) 2008, ZETETIC LLC\par All rights reserved.\par \par Redistribution and use in source and binary forms, with or without\par modification, are permitted provided that the following conditions are met:\par * Redistributions of source code must retain the above copyright\par notice, this list of conditions and the following disclaimer.\par * Redistributions in binary form must reproduce the above copyright\par notice, this list of conditions and the following disclaimer in the\par documentation and/or other materials provided with the distribution.\par * Neither the name of the ZETETIC LLC nor the\par names of its contributors may be used to endorse or promote products\par derived from this software without specific prior written permission.\par \par THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY\par EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\par WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\par DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY\par DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\par (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\par LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\par ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\par (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\par SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\par \par \par ----------------------------------------------------------------\par License for OpenSSL libcrypto\par ----------------------------------------------------------------\par \par LICENSE ISSUES\par ==============\par \par The OpenSSL toolkit stays under a dual license, i.e. both the conditions of\par the OpenSSL License and the original SSLeay license apply to the toolkit.\par See below for the actual license texts. Actually both licenses are BSD-style\par Open Source licenses. In case of any license issues related to OpenSSL\par please contact [email protected].\par \par OpenSSL License\par ---------------\par \par /* ====================================================================\par * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved.\par *\par * Redistribution and use in source and binary forms, with or without\par * modification, are permitted provided that the following conditions\par * are met:\par *\par * 1. Redistributions of source code must retain the above copyright\par * notice, this list of conditions and the following disclaimer. \par *\par * 2. Redistributions in binary form must reproduce the above copyright\par * notice, this list of conditions and the following disclaimer in\par * the documentation and/or other materials provided with the\par * distribution.\par *\par * 3. All advertising materials mentioning features or use of this\par * software must display the following acknowledgment:\par * "This product includes software developed by the OpenSSL Project\par * for use in the OpenSSL Toolkit. ({\cf0{\field{\*\fldinst{HYPERLINK http://www.openssl.org/ }}{\fldrslt{http://www.openssl.org/\ul0\cf0}}}}\f1\fs20 )"\par *\par * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to\par * endorse or promote products derived from this software without\par * prior written permission. For written permission, please contact\par * [email protected].\par *\par * 5. Products derived from this software may not be called "OpenSSL"\par * nor may "OpenSSL" appear in their names without prior written\par * permission of the OpenSSL Project.\par *\par * 6. Redistributions of any form whatsoever must retain the following\par * acknowledgment:\par * "This product includes software developed by the OpenSSL Project\par * for use in the OpenSSL Toolkit ({\cf0{\field{\*\fldinst{HYPERLINK http://www.openssl.org/ }}{\fldrslt{http://www.openssl.org/\ul0\cf0}}}}\f1\fs20 )"\par *\par * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY\par * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\par * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\par * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR\par * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\par * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\par * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\par * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\par * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\par * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\par * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\par * OF THE POSSIBILITY OF SUCH DAMAGE.\par * ====================================================================\par *\par * This product includes cryptographic software written by Eric Young\par * ([email protected]). This product includes software written by Tim\par * Hudson ([email protected]).\par *\par */\par \par Original SSLeay License\par -----------------------\par \par /* Copyright (C) 1995-1998 Eric Young ([email protected])\par * All rights reserved.\par *\par * This package is an SSL implementation written\par * by Eric Young ([email protected]).\par * The implementation was written so as to conform with Netscapes SSL.\par * \par * This library is free for commercial and non-commercial use as long as\par * the following conditions are aheared to. The following conditions\par * apply to all code found in this distribution, be it the RC4, RSA,\par * lhash, DES, etc., code; not just the SSL code. The SSL documentation\par * included with this distribution is covered by the same copyright terms\par * except that the holder is Tim Hudson ([email protected]).\par * \par * Copyright remains Eric Young's, and as such any Copyright notices in\par * the code are not to be removed.\par * If this package is used in a product, Eric Young should be given attribution\par * as the author of the parts of the library used.\par * This can be in the form of a textual message at program startup or\par * in documentation (online or textual) provided with the package.\par * \par * Redistribution and use in source and binary forms, with or without\par * modification, are permitted provided that the following conditions\par * are met:\par * 1. Redistributions of source code must retain the copyright\par * notice, this list of conditions and the following disclaimer.\par * 2. Redistributions in binary form must reproduce the above copyright\par * notice, this list of conditions and the following disclaimer in the\par * documentation and/or other materials provided with the distribution.\par * 3. All advertising materials mentioning features or use of this software\par * must display the following acknowledgement:\par * "This product includes cryptographic software written by\par * Eric Young ([email protected])"\par * The word 'cryptographic' can be left out if the rouines from the library\par * being used are not cryptographic related :-).\par * 4. If you include any Windows specific code (or a derivative thereof) from \par * the apps directory (application code) you must include an acknowledgement:\par * "This product includes software written by Tim Hudson ([email protected])"\par * \par * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND\par * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\par * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\par * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\par * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\par * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\par * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\par * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\par * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\par * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\par * SUCH DAMAGE.\par * \par * The licence and distribution terms for any publically available version or\par * derivative of this code cannot be changed. i.e. this code cannot simply be\par * copied and put under another distribution licence\par * [including the GNU Public Licence.]\par */\par \pard\nowidctlpar\cf0\f0\fs22 =========================================\par END OF SQLitePCLRaw.core NOTICES AND INFORMATION\par \par %% SQLitePCLRaw.provider.e_sqlite3.net45 NOTICES AND INFORMATION BEGIN HERE\par =========================================\par Apache License\par Version 2.0, January 2004\par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/ }}{\fldrslt{http://www.apache.org/licenses/\ul0\cf0}}}}\f0\fs22\par \par TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\par \par 1. Definitions.\par \par "License" shall mean the terms and conditions for use, reproduction,\par and distribution as defined by Sections 1 through 9 of this document.\par \par "Licensor" shall mean the copyright owner or entity authorized by\par the copyright owner that is granting the License.\par \par "Legal Entity" shall mean the union of the acting entity and all\par other entities that control, are controlled by, or are under common\par control with that entity. For the purposes of this definition,\par "control" means (i) the power, direct or indirect, to cause the\par direction or management of such entity, whether by contract or\par otherwise, or (ii) ownership of fifty percent (50%) or more of the\par outstanding shares, or (iii) beneficial ownership of such entity.\par \par "You" (or "Your") shall mean an individual or Legal Entity\par exercising permissions granted by this License.\par \par "Source" form shall mean the preferred form for making modifications,\par including but not limited to software source code, documentation\par source, and configuration files.\par \par "Object" form shall mean any form resulting from mechanical\par transformation or translation of a Source form, including but\par not limited to compiled object code, generated documentation,\par and conversions to other media types.\par \par "Work" shall mean the work of authorship, whether in Source or\par Object form, made available under the License, as indicated by a\par copyright notice that is included in or attached to the work\par (an example is provided in the Appendix below).\par \par "Derivative Works" shall mean any work, whether in Source or Object\par form, that is based on (or derived from) the Work and for which the\par editorial revisions, annotations, elaborations, or other modifications\par represent, as a whole, an original work of authorship. For the purposes\par of this License, Derivative Works shall not include works that remain\par separable from, or merely link (or bind by name) to the interfaces of,\par the Work and Derivative Works thereof.\par \par "Contribution" shall mean any work of authorship, including\par the original version of the Work and any modifications or additions\par to that Work or Derivative Works thereof, that is intentionally\par submitted to Licensor for inclusion in the Work by the copyright owner\par or by an individual or Legal Entity authorized to submit on behalf of\par the copyright owner. For the purposes of this definition, "submitted"\par means any form of electronic, verbal, or written communication sent\par to the Licensor or its representatives, including but not limited to\par communication on electronic mailing lists, source code control systems,\par and issue tracking systems that are managed by, or on behalf of, the\par Licensor for the purpose of discussing and improving the Work, but\par excluding communication that is conspicuously marked or otherwise\par designated in writing by the copyright owner as "Not a Contribution."\par \par "Contributor" shall mean Licensor and any individual or Legal Entity\par on behalf of whom a Contribution has been received by Licensor and\par subsequently incorporated within the Work.\par \par 2. Grant of Copyright License. Subject to the terms and conditions of\par this License, each Contributor hereby grants to You a perpetual,\par worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par copyright license to reproduce, prepare Derivative Works of,\par publicly display, publicly perform, sublicense, and distribute the\par Work and such Derivative Works in Source or Object form.\par \par 3. Grant of Patent License. Subject to the terms and conditions of\par this License, each Contributor hereby grants to You a perpetual,\par worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par (except as stated in this section) patent license to make, have made,\par use, offer to sell, sell, import, and otherwise transfer the Work,\par where such license applies only to those patent claims licensable\par by such Contributor that are necessarily infringed by their\par Contribution(s) alone or by combination of their Contribution(s)\par with the Work to which such Contribution(s) was submitted. If You\par institute patent litigation against any entity (including a\par cross-claim or counterclaim in a lawsuit) alleging that the Work\par or a Contribution incorporated within the Work constitutes direct\par or contributory patent infringement, then any patent licenses\par granted to You under this License for that Work shall terminate\par as of the date such litigation is filed.\par \par 4. Redistribution. You may reproduce and distribute copies of the\par Work or Derivative Works thereof in any medium, with or without\par modifications, and in Source or Object form, provided that You\par meet the following conditions:\par \par (a) You must give any other recipients of the Work or\par Derivative Works a copy of this License; and\par \par (b) You must cause any modified files to carry prominent notices\par stating that You changed the files; and\par \par (c) You must retain, in the Source form of any Derivative Works\par that You distribute, all copyright, patent, trademark, and\par attribution notices from the Source form of the Work,\par excluding those notices that do not pertain to any part of\par the Derivative Works; and\par \par (d) If the Work includes a "NOTICE" text file as part of its\par distribution, then any Derivative Works that You distribute must\par include a readable copy of the attribution notices contained\par within such NOTICE file, excluding those notices that do not\par pertain to any part of the Derivative Works, in at least one\par of the following places: within a NOTICE text file distributed\par as part of the Derivative Works; within the Source form or\par documentation, if provided along with the Derivative Works; or,\par within a display generated by the Derivative Works, if and\par wherever such third-party notices normally appear. The contents\par of the NOTICE file are for informational purposes only and\par do not modify the License. You may add Your own attribution\par notices within Derivative Works that You distribute, alongside\par or as an addendum to the NOTICE text from the Work, provided\par that such additional attribution notices cannot be construed\par as modifying the License.\par \par You may add Your own copyright statement to Your modifications and\par may provide additional or different license terms and conditions\par for use, reproduction, or distribution of Your modifications, or\par for any such Derivative Works as a whole, provided Your use,\par reproduction, and distribution of the Work otherwise complies with\par the conditions stated in this License.\par \par 5. Submission of Contributions. Unless You explicitly state otherwise,\par any Contribution intentionally submitted for inclusion in the Work\par by You to the Licensor shall be under the terms and conditions of\par this License, without any additional terms or conditions.\par Notwithstanding the above, nothing herein shall supersede or modify\par the terms of any separate license agreement you may have executed\par with Licensor regarding such Contributions.\par \par 6. Trademarks. This License does not grant permission to use the trade\par names, trademarks, service marks, or product names of the Licensor,\par except as required for reasonable and customary use in describing the\par origin of the Work and reproducing the content of the NOTICE file.\par \par 7. Disclaimer of Warranty. Unless required by applicable law or\par agreed to in writing, Licensor provides the Work (and each\par Contributor provides its Contributions) on an "AS IS" BASIS,\par WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\par implied, including, without limitation, any warranties or conditions\par of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\par PARTICULAR PURPOSE. You are solely responsible for determining the\par appropriateness of using or redistributing the Work and assume any\par risks associated with Your exercise of permissions under this License.\par \par 8. Limitation of Liability. In no event and under no legal theory,\par whether in tort (including negligence), contract, or otherwise,\par unless required by applicable law (such as deliberate and grossly\par negligent acts) or agreed to in writing, shall any Contributor be\par liable to You for damages, including any direct, indirect, special,\par incidental, or consequential damages of any character arising as a\par result of this License or out of the use or inability to use the\par Work (including but not limited to damages for loss of goodwill,\par work stoppage, computer failure or malfunction, or any and all\par other commercial damages or losses), even if such Contributor\par has been advised of the possibility of such damages.\par \par 9. Accepting Warranty or Additional Liability. While redistributing\par the Work or Derivative Works thereof, You may choose to offer,\par and charge a fee for, acceptance of support, warranty, indemnity,\par or other liability obligations and/or rights consistent with this\par License. However, in accepting such obligations, You may act only\par on Your own behalf and on Your sole responsibility, not on behalf\par of any other Contributor, and only if You agree to indemnify,\par defend, and hold each Contributor harmless for any liability\par incurred by, or claims asserted against, such Contributor by reason\par of your accepting any such warranty or additional liability.\par \par END OF TERMS AND CONDITIONS\par \par APPENDIX: How to apply the Apache License to your work.\par \par To apply the Apache License to your work, attach the following\par boilerplate notice, with the fields enclosed by brackets "[]"\par replaced with your own identifying information. (Don't include\par the brackets!) The text should be enclosed in the appropriate\par comment syntax for the file format. We also recommend that a\par file or class name and description of purpose be included on the\par same "printed page" as the copyright notice for easier\par identification within third-party archives.\par \par Copyright [yyyy] [name of copyright owner]\par \par Licensed under the Apache License, Version 2.0 (the "License");\par you may not use this file except in compliance with the License.\par You may obtain a copy of the License at\par \par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f0\fs22\par \par Unless required by applicable law or agreed to in writing, software\par distributed under the License is distributed on an "AS IS" BASIS,\par WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\par See the License for the specific language governing permissions and\par limitations under the License.\par \par \pard\widctlpar\tx916\tx1832\tx2748\tx3664\tx4580\tx5496\tx6412\tx7328\tx8244\tx9160\tx10076\tx10992\tx11908\tx12824\tx13740\tx14656\cf5\f1\fs20 ----------------------------------------------------------------\par Copyright on SQLitePCL.raw\par ----------------------------------------------------------------\par \par Version prior to 2.0 were labeled with the copyright owned by\par Zumero. In 2.0, this changed to SourceGear. There is no legal\par distinction, as Zumero is simply a dba name for SourceGear.\par \par And in either case, the open source license remains the same,\par Apache v2.\par \par ----------------------------------------------------------------\par License for SQLite\par ----------------------------------------------------------------\par \par ** The author disclaims copyright to this source code. In place of\par ** a legal notice, here is a blessing:\par **\par ** May you do good and not evil.\par ** May you find forgiveness for yourself and forgive others.\par ** May you share freely, never taking more than you give.\par **\par \par \par ----------------------------------------------------------------\par License for MS Open Tech\par ----------------------------------------------------------------\par \par // Copyright \'a9 Microsoft Open Technologies, Inc.\par // All Rights Reserved\par // Licensed under the Apache License, Version 2.0 (the "License"); you may not\par // use this file except in compliance with the License. You may obtain a copy\par // of the License at \par // {\cf0{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f1\fs20\par // \par // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\par // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY\par // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\par // MERCHANTABLITY OR NON-INFRINGEMENT.\par // \par // See the Apache 2 License for the specific language governing permissions and\par // limitations under the License.\par \par \par ----------------------------------------------------------------\par License for SQLCipher\par ----------------------------------------------------------------\par \par Copyright (c) 2008, ZETETIC LLC\par All rights reserved.\par \par Redistribution and use in source and binary forms, with or without\par modification, are permitted provided that the following conditions are met:\par * Redistributions of source code must retain the above copyright\par notice, this list of conditions and the following disclaimer.\par * Redistributions in binary form must reproduce the above copyright\par notice, this list of conditions and the following disclaimer in the\par documentation and/or other materials provided with the distribution.\par * Neither the name of the ZETETIC LLC nor the\par names of its contributors may be used to endorse or promote products\par derived from this software without specific prior written permission.\par \par THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY\par EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\par WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\par DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY\par DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\par (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\par LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\par ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\par (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\par SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\par \par \par ----------------------------------------------------------------\par License for OpenSSL libcrypto\par ----------------------------------------------------------------\par \par LICENSE ISSUES\par ==============\par \par The OpenSSL toolkit stays under a dual license, i.e. both the conditions of\par the OpenSSL License and the original SSLeay license apply to the toolkit.\par See below for the actual license texts. Actually both licenses are BSD-style\par Open Source licenses. In case of any license issues related to OpenSSL\par please contact [email protected].\par \par OpenSSL License\par ---------------\par \par /* ====================================================================\par * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved.\par *\par * Redistribution and use in source and binary forms, with or without\par * modification, are permitted provided that the following conditions\par * are met:\par *\par * 1. Redistributions of source code must retain the above copyright\par * notice, this list of conditions and the following disclaimer. \par *\par * 2. Redistributions in binary form must reproduce the above copyright\par * notice, this list of conditions and the following disclaimer in\par * the documentation and/or other materials provided with the\par * distribution.\par *\par * 3. All advertising materials mentioning features or use of this\par * software must display the following acknowledgment:\par * "This product includes software developed by the OpenSSL Project\par * for use in the OpenSSL Toolkit. ({\cf0{\field{\*\fldinst{HYPERLINK http://www.openssl.org/ }}{\fldrslt{http://www.openssl.org/\ul0\cf0}}}}\f1\fs20 )"\par *\par * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to\par * endorse or promote products derived from this software without\par * prior written permission. For written permission, please contact\par * [email protected].\par *\par * 5. Products derived from this software may not be called "OpenSSL"\par * nor may "OpenSSL" appear in their names without prior written\par * permission of the OpenSSL Project.\par *\par * 6. Redistributions of any form whatsoever must retain the following\par * acknowledgment:\par * "This product includes software developed by the OpenSSL Project\par * for use in the OpenSSL Toolkit ({\cf0{\field{\*\fldinst{HYPERLINK http://www.openssl.org/ }}{\fldrslt{http://www.openssl.org/\ul0\cf0}}}}\f1\fs20 )"\par *\par * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY\par * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\par * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\par * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR\par * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\par * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\par * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\par * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\par * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\par * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\par * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\par * OF THE POSSIBILITY OF SUCH DAMAGE.\par * ====================================================================\par *\par * This product includes cryptographic software written by Eric Young\par * ([email protected]). This product includes software written by Tim\par * Hudson ([email protected]).\par *\par */\par \par Original SSLeay License\par -----------------------\par \par /* Copyright (C) 1995-1998 Eric Young ([email protected])\par * All rights reserved.\par *\par * This package is an SSL implementation written\par * by Eric Young ([email protected]).\par * The implementation was written so as to conform with Netscapes SSL.\par * \par * This library is free for commercial and non-commercial use as long as\par * the following conditions are aheared to. The following conditions\par * apply to all code found in this distribution, be it the RC4, RSA,\par * lhash, DES, etc., code; not just the SSL code. The SSL documentation\par * included with this distribution is covered by the same copyright terms\par * except that the holder is Tim Hudson ([email protected]).\par * \par * Copyright remains Eric Young's, and as such any Copyright notices in\par * the code are not to be removed.\par * If this package is used in a product, Eric Young should be given attribution\par * as the author of the parts of the library used.\par * This can be in the form of a textual message at program startup or\par * in documentation (online or textual) provided with the package.\par * \par * Redistribution and use in source and binary forms, with or without\par * modification, are permitted provided that the following conditions\par * are met:\par * 1. Redistributions of source code must retain the copyright\par * notice, this list of conditions and the following disclaimer.\par * 2. Redistributions in binary form must reproduce the above copyright\par * notice, this list of conditions and the following disclaimer in the\par * documentation and/or other materials provided with the distribution.\par * 3. All advertising materials mentioning features or use of this software\par * must display the following acknowledgement:\par * "This product includes cryptographic software written by\par * Eric Young ([email protected])"\par * The word 'cryptographic' can be left out if the rouines from the library\par * being used are not cryptographic related :-).\par * 4. If you include any Windows specific code (or a derivative thereof) from \par * the apps directory (application code) you must include an acknowledgement:\par * "This product includes software written by Tim Hudson ([email protected])"\par * \par * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND\par * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\par * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\par * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\par * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\par * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\par * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\par * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\par * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\par * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\par * SUCH DAMAGE.\par * \par * The licence and distribution terms for any publically available version or\par * derivative of this code cannot be changed. i.e. this code cannot simply be\par * copied and put under another distribution licence\par * [including the GNU Public Licence.]\par */\par \pard\nowidctlpar\cf0\f0\fs22 =========================================\par END OF SQLitePCLRaw.provider.e_sqlite3.net45 NOTICES AND INFORMATION\par \par %% SQLitePCLRaw.lib.e_sqlite3.v110_xp NOTICES AND INFORMATION BEGIN HERE\par =========================================\par Apache License\par Version 2.0, January 2004\par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/ }}{\fldrslt{http://www.apache.org/licenses/\ul0\cf0}}}}\f0\fs22\par \par TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\par \par 1. Definitions.\par \par "License" shall mean the terms and conditions for use, reproduction,\par and distribution as defined by Sections 1 through 9 of this document.\par \par "Licensor" shall mean the copyright owner or entity authorized by\par the copyright owner that is granting the License.\par \par "Legal Entity" shall mean the union of the acting entity and all\par other entities that control, are controlled by, or are under common\par control with that entity. For the purposes of this definition,\par "control" means (i) the power, direct or indirect, to cause the\par direction or management of such entity, whether by contract or\par otherwise, or (ii) ownership of fifty percent (50%) or more of the\par outstanding shares, or (iii) beneficial ownership of such entity.\par \par "You" (or "Your") shall mean an individual or Legal Entity\par exercising permissions granted by this License.\par \par "Source" form shall mean the preferred form for making modifications,\par including but not limited to software source code, documentation\par source, and configuration files.\par \par "Object" form shall mean any form resulting from mechanical\par transformation or translation of a Source form, including but\par not limited to compiled object code, generated documentation,\par and conversions to other media types.\par \par "Work" shall mean the work of authorship, whether in Source or\par Object form, made available under the License, as indicated by a\par copyright notice that is included in or attached to the work\par (an example is provided in the Appendix below).\par \par "Derivative Works" shall mean any work, whether in Source or Object\par form, that is based on (or derived from) the Work and for which the\par editorial revisions, annotations, elaborations, or other modifications\par represent, as a whole, an original work of authorship. For the purposes\par of this License, Derivative Works shall not include works that remain\par separable from, or merely link (or bind by name) to the interfaces of,\par the Work and Derivative Works thereof.\par \par "Contribution" shall mean any work of authorship, including\par the original version of the Work and any modifications or additions\par to that Work or Derivative Works thereof, that is intentionally\par submitted to Licensor for inclusion in the Work by the copyright owner\par or by an individual or Legal Entity authorized to submit on behalf of\par the copyright owner. For the purposes of this definition, "submitted"\par means any form of electronic, verbal, or written communication sent\par to the Licensor or its representatives, including but not limited to\par communication on electronic mailing lists, source code control systems,\par and issue tracking systems that are managed by, or on behalf of, the\par Licensor for the purpose of discussing and improving the Work, but\par excluding communication that is conspicuously marked or otherwise\par designated in writing by the copyright owner as "Not a Contribution."\par \par "Contributor" shall mean Licensor and any individual or Legal Entity\par on behalf of whom a Contribution has been received by Licensor and\par subsequently incorporated within the Work.\par \par 2. Grant of Copyright License. Subject to the terms and conditions of\par this License, each Contributor hereby grants to You a perpetual,\par worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par copyright license to reproduce, prepare Derivative Works of,\par publicly display, publicly perform, sublicense, and distribute the\par Work and such Derivative Works in Source or Object form.\par \par 3. Grant of Patent License. Subject to the terms and conditions of\par this License, each Contributor hereby grants to You a perpetual,\par worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par (except as stated in this section) patent license to make, have made,\par use, offer to sell, sell, import, and otherwise transfer the Work,\par where such license applies only to those patent claims licensable\par by such Contributor that are necessarily infringed by their\par Contribution(s) alone or by combination of their Contribution(s)\par with the Work to which such Contribution(s) was submitted. If You\par institute patent litigation against any entity (including a\par cross-claim or counterclaim in a lawsuit) alleging that the Work\par or a Contribution incorporated within the Work constitutes direct\par or contributory patent infringement, then any patent licenses\par granted to You under this License for that Work shall terminate\par as of the date such litigation is filed.\par \par 4. Redistribution. You may reproduce and distribute copies of the\par Work or Derivative Works thereof in any medium, with or without\par modifications, and in Source or Object form, provided that You\par meet the following conditions:\par \par (a) You must give any other recipients of the Work or\par Derivative Works a copy of this License; and\par \par (b) You must cause any modified files to carry prominent notices\par stating that You changed the files; and\par \par (c) You must retain, in the Source form of any Derivative Works\par that You distribute, all copyright, patent, trademark, and\par attribution notices from the Source form of the Work,\par excluding those notices that do not pertain to any part of\par the Derivative Works; and\par \par (d) If the Work includes a "NOTICE" text file as part of its\par distribution, then any Derivative Works that You distribute must\par include a readable copy of the attribution notices contained\par within such NOTICE file, excluding those notices that do not\par pertain to any part of the Derivative Works, in at least one\par of the following places: within a NOTICE text file distributed\par as part of the Derivative Works; within the Source form or\par documentation, if provided along with the Derivative Works; or,\par within a display generated by the Derivative Works, if and\par wherever such third-party notices normally appear. The contents\par of the NOTICE file are for informational purposes only and\par do not modify the License. You may add Your own attribution\par notices within Derivative Works that You distribute, alongside\par or as an addendum to the NOTICE text from the Work, provided\par that such additional attribution notices cannot be construed\par as modifying the License.\par \par You may add Your own copyright statement to Your modifications and\par may provide additional or different license terms and conditions\par for use, reproduction, or distribution of Your modifications, or\par for any such Derivative Works as a whole, provided Your use,\par reproduction, and distribution of the Work otherwise complies with\par the conditions stated in this License.\par \par 5. Submission of Contributions. Unless You explicitly state otherwise,\par any Contribution intentionally submitted for inclusion in the Work\par by You to the Licensor shall be under the terms and conditions of\par this License, without any additional terms or conditions.\par Notwithstanding the above, nothing herein shall supersede or modify\par the terms of any separate license agreement you may have executed\par with Licensor regarding such Contributions.\par \par 6. Trademarks. This License does not grant permission to use the trade\par names, trademarks, service marks, or product names of the Licensor,\par except as required for reasonable and customary use in describing the\par origin of the Work and reproducing the content of the NOTICE file.\par \par 7. Disclaimer of Warranty. Unless required by applicable law or\par agreed to in writing, Licensor provides the Work (and each\par Contributor provides its Contributions) on an "AS IS" BASIS,\par WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\par implied, including, without limitation, any warranties or conditions\par of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\par PARTICULAR PURPOSE. You are solely responsible for determining the\par appropriateness of using or redistributing the Work and assume any\par risks associated with Your exercise of permissions under this License.\par \par 8. Limitation of Liability. In no event and under no legal theory,\par whether in tort (including negligence), contract, or otherwise,\par unless required by applicable law (such as deliberate and grossly\par negligent acts) or agreed to in writing, shall any Contributor be\par liable to You for damages, including any direct, indirect, special,\par incidental, or consequential damages of any character arising as a\par result of this License or out of the use or inability to use the\par Work (including but not limited to damages for loss of goodwill,\par work stoppage, computer failure or malfunction, or any and all\par other commercial damages or losses), even if such Contributor\par has been advised of the possibility of such damages.\par \par 9. Accepting Warranty or Additional Liability. While redistributing\par the Work or Derivative Works thereof, You may choose to offer,\par and charge a fee for, acceptance of support, warranty, indemnity,\par or other liability obligations and/or rights consistent with this\par License. However, in accepting such obligations, You may act only\par on Your own behalf and on Your sole responsibility, not on behalf\par of any other Contributor, and only if You agree to indemnify,\par defend, and hold each Contributor harmless for any liability\par incurred by, or claims asserted against, such Contributor by reason\par of your accepting any such warranty or additional liability.\par \par END OF TERMS AND CONDITIONS\par \par APPENDIX: How to apply the Apache License to your work.\par \par To apply the Apache License to your work, attach the following\par boilerplate notice, with the fields enclosed by brackets "[]"\par replaced with your own identifying information. (Don't include\par the brackets!) The text should be enclosed in the appropriate\par comment syntax for the file format. We also recommend that a\par file or class name and description of purpose be included on the\par same "printed page" as the copyright notice for easier\par identification within third-party archives.\par \par Copyright [yyyy] [name of copyright owner]\par \par Licensed under the Apache License, Version 2.0 (the "License");\par you may not use this file except in compliance with the License.\par You may obtain a copy of the License at\par \par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f0\fs22\par \par Unless required by applicable law or agreed to in writing, software\par distributed under the License is distributed on an "AS IS" BASIS,\par WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\par See the License for the specific language governing permissions and\par limitations under the License.\par \par \pard\widctlpar\tx916\tx1832\tx2748\tx3664\tx4580\tx5496\tx6412\tx7328\tx8244\tx9160\tx10076\tx10992\tx11908\tx12824\tx13740\tx14656\cf5\f1\fs20 ----------------------------------------------------------------\par Copyright on SQLitePCL.raw\par ----------------------------------------------------------------\par \par Version prior to 2.0 were labeled with the copyright owned by\par Zumero. In 2.0, this changed to SourceGear. There is no legal\par distinction, as Zumero is simply a dba name for SourceGear.\par \par And in either case, the open source license remains the same,\par Apache v2.\par \par ----------------------------------------------------------------\par License for SQLite\par ----------------------------------------------------------------\par \par ** The author disclaims copyright to this source code. In place of\par ** a legal notice, here is a blessing:\par **\par ** May you do good and not evil.\par ** May you find forgiveness for yourself and forgive others.\par ** May you share freely, never taking more than you give.\par **\par \par \par ----------------------------------------------------------------\par License for MS Open Tech\par ----------------------------------------------------------------\par \par // Copyright \'a9 Microsoft Open Technologies, Inc.\par // All Rights Reserved\par // Licensed under the Apache License, Version 2.0 (the "License"); you may not\par // use this file except in compliance with the License. You may obtain a copy\par // of the License at \par // {\cf0{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f1\fs20\par // \par // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\par // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY\par // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\par // MERCHANTABLITY OR NON-INFRINGEMENT.\par // \par // See the Apache 2 License for the specific language governing permissions and\par // limitations under the License.\par \par \par ----------------------------------------------------------------\par License for SQLCipher\par ----------------------------------------------------------------\par \par Copyright (c) 2008, ZETETIC LLC\par All rights reserved.\par \par Redistribution and use in source and binary forms, with or without\par modification, are permitted provided that the following conditions are met:\par * Redistributions of source code must retain the above copyright\par notice, this list of conditions and the following disclaimer.\par * Redistributions in binary form must reproduce the above copyright\par notice, this list of conditions and the following disclaimer in the\par documentation and/or other materials provided with the distribution.\par * Neither the name of the ZETETIC LLC nor the\par names of its contributors may be used to endorse or promote products\par derived from this software without specific prior written permission.\par \par THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY\par EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\par WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\par DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY\par DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\par (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\par LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\par ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\par (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\par SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\par \par \par ----------------------------------------------------------------\par License for OpenSSL libcrypto\par ----------------------------------------------------------------\par \par LICENSE ISSUES\par ==============\par \par The OpenSSL toolkit stays under a dual license, i.e. both the conditions of\par the OpenSSL License and the original SSLeay license apply to the toolkit.\par See below for the actual license texts. Actually both licenses are BSD-style\par Open Source licenses. In case of any license issues related to OpenSSL\par please contact [email protected].\par \par OpenSSL License\par ---------------\par \par /* ====================================================================\par * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved.\par *\par * Redistribution and use in source and binary forms, with or without\par * modification, are permitted provided that the following conditions\par * are met:\par *\par * 1. Redistributions of source code must retain the above copyright\par * notice, this list of conditions and the following disclaimer. \par *\par * 2. Redistributions in binary form must reproduce the above copyright\par * notice, this list of conditions and the following disclaimer in\par * the documentation and/or other materials provided with the\par * distribution.\par *\par * 3. All advertising materials mentioning features or use of this\par * software must display the following acknowledgment:\par * "This product includes software developed by the OpenSSL Project\par * for use in the OpenSSL Toolkit. ({\cf0{\field{\*\fldinst{HYPERLINK http://www.openssl.org/ }}{\fldrslt{http://www.openssl.org/\ul0\cf0}}}}\f1\fs20 )"\par *\par * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to\par * endorse or promote products derived from this software without\par * prior written permission. For written permission, please contact\par * [email protected].\par *\par * 5. Products derived from this software may not be called "OpenSSL"\par * nor may "OpenSSL" appear in their names without prior written\par * permission of the OpenSSL Project.\par *\par * 6. Redistributions of any form whatsoever must retain the following\par * acknowledgment:\par * "This product includes software developed by the OpenSSL Project\par * for use in the OpenSSL Toolkit ({\cf0{\field{\*\fldinst{HYPERLINK http://www.openssl.org/ }}{\fldrslt{http://www.openssl.org/\ul0\cf0}}}}\f1\fs20 )"\par *\par * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY\par * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\par * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\par * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR\par * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\par * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\par * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\par * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\par * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\par * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\par * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\par * OF THE POSSIBILITY OF SUCH DAMAGE.\par * ====================================================================\par *\par * This product includes cryptographic software written by Eric Young\par * ([email protected]). This product includes software written by Tim\par * Hudson ([email protected]).\par *\par */\par \par Original SSLeay License\par -----------------------\par \par /* Copyright (C) 1995-1998 Eric Young ([email protected])\par * All rights reserved.\par *\par * This package is an SSL implementation written\par * by Eric Young ([email protected]).\par * The implementation was written so as to conform with Netscapes SSL.\par * \par * This library is free for commercial and non-commercial use as long as\par * the following conditions are aheared to. The following conditions\par * apply to all code found in this distribution, be it the RC4, RSA,\par * lhash, DES, etc., code; not just the SSL code. The SSL documentation\par * included with this distribution is covered by the same copyright terms\par * except that the holder is Tim Hudson ([email protected]).\par * \par * Copyright remains Eric Young's, and as such any Copyright notices in\par * the code are not to be removed.\par * If this package is used in a product, Eric Young should be given attribution\par * as the author of the parts of the library used.\par * This can be in the form of a textual message at program startup or\par * in documentation (online or textual) provided with the package.\par * \par * Redistribution and use in source and binary forms, with or without\par * modification, are permitted provided that the following conditions\par * are met:\par * 1. Redistributions of source code must retain the copyright\par * notice, this list of conditions and the following disclaimer.\par * 2. Redistributions in binary form must reproduce the above copyright\par * notice, this list of conditions and the following disclaimer in the\par * documentation and/or other materials provided with the distribution.\par * 3. All advertising materials mentioning features or use of this software\par * must display the following acknowledgement:\par * "This product includes cryptographic software written by\par * Eric Young ([email protected])"\par * The word 'cryptographic' can be left out if the rouines from the library\par * being used are not cryptographic related :-).\par * 4. If you include any Windows specific code (or a derivative thereof) from \par * the apps directory (application code) you must include an acknowledgement:\par * "This product includes software written by Tim Hudson ([email protected])"\par * \par * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND\par * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\par * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\par * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\par * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\par * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\par * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\par * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\par * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\par * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\par * SUCH DAMAGE.\par * \par * The licence and distribution terms for any publically available version or\par * derivative of this code cannot be changed. i.e. this code cannot simply be\par * copied and put under another distribution licence\par * [including the GNU Public Licence.]\par */\par \pard\nowidctlpar\cf0\f0\fs22 =========================================\par END OF SQLitePCLRaw.lib.e_sqlite3.v110_xp NOTICES AND INFORMATION\par \pard\sa200\sl276\slmult1\f2\lang9\par }
{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fswiss\fprq2\fcharset0 Calibri;}{\f1\fmodern\fprq1\fcharset0 Consolas;}{\f2\fnil\fcharset0 Calibri;}} {\colortbl ;\red247\green247\blue247;\red36\green41\blue46;\red255\green255\blue255;\red0\green0\blue255;\red0\green0\blue0;} {\*\generator Riched20 10.0.17134}\viewkind4\uc1 \pard\widctlpar\highlight1\expndtw3\f0\fs22 NOTICES AND INFORMATION\par Do Not Translate or Localize\par \par \pard\nowidctlpar The \cf2\highlight3\expndtw0 .NET Compiler Platform ("Roslyn") \cf0\highlight1\expndtw3 software incorporates material from third parties. Microsoft makes certain open source code available at {{\field{\*\fldinst{HYPERLINK https://3rdpartysource.microsoft.com }}{\fldrslt{https://3rdpartysource.microsoft.com\ul0\cf0}}}}\f0\fs22 , or you may send a check or money order for US $5.00, including the product name, the open source component name, and version number, to:\par \pard\widctlpar\par Source Code Compliance Team\par Microsoft Corporation\par One Microsoft Way\par Redmond, WA 98052\par USA\par \par Notwithstanding any other terms, you may reverse engineer this software to the extent required to debug changes to any libraries licensed under the GNU Lesser General Public License.\par \par \pard\nowidctlpar\highlight0\expndtw0 %% \cf2\highlight3 .NET Compiler Platform \cf0\highlight0 NOTICES AND INFORMATION BEGIN HERE\par =========================================\par \par {{\field{\*\fldinst{HYPERLINK https://github.com/dotnet/roslyn }}{\fldrslt{https://github.com/dotnet/roslyn\ul0\cf0}}}}\f0\fs22\par \par \cf5\highlight3 The MIT License (MIT) \par \par Copyright (c) .NET Foundation and Contributors All rights reserved. \par \par Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: \par \par The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. \par \par THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\highlight0\par \cf0 =========================================\par END OF \cf2\highlight3 .NET Compiler Platform \cf0\highlight0 NOTICES AND INFORMATION\par \par %% .NET Core Libraries (CoreFX) NOTICES AND INFORMATION BEGIN HERE\par =========================================\par \par {{\field{\*\fldinst{HYPERLINK https://github.com/dotnet/corefx }}{\fldrslt{https://github.com/dotnet/corefx\ul0\cf0}}}}\f0\fs22\par \par \cf5\highlight3 The MIT License (MIT) \par \par Copyright (c) .NET Foundation and Contributors All rights reserved. \par \par Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: \par \par The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. \par \par THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\cf0\highlight0\par =========================================\par END OF \cf2\highlight3 .\cf0\highlight0 NET Core Libraries (CoreFX) NOTICES AND INFORMATION\par \par %% DotNetTools NOTICES AND INFORMATION BEGIN HERE\par =========================================\par \par {{\field{\*\fldinst{HYPERLINK https://github.com/aspnet/DotNetTools }}{\fldrslt{https://github.com/aspnet/DotNetTools\ul0\cf0}}}}\f0\fs22\par \par Copyright (c) .NET Foundation and Contributors\par \par All rights reserved.\par \par Licensed under the Apache License, Version 2.0 (the "License"); you may not use\par this file except in compliance with the License. You may obtain a copy of the\par License at\par \par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f0\fs22\par \par Unless required by applicable law or agreed to in writing, software distributed\par under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR\par CONDITIONS OF ANY KIND, either express or implied. See the License for the\par specific language governing permissions and limitations under the License.\par \par =========================================\par END OF DotNetTools NOTICES AND INFORMATION\par \par %% DocFX NOTICES AND INFORMATION BEGIN HERE\par =========================================\par \par {{\field{\*\fldinst{HYPERLINK https://github.com/dotnet/docfx }}{\fldrslt{https://github.com/dotnet/docfx\ul0\cf0}}}}\f0\fs22\par \par \cf5\highlight3 The MIT License (MIT) \par \par Copyright (c) Microsoft Corporation \par \par Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: \par \par The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. \par \par THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\par \cf0\highlight0 =========================================\par END OF DocFX NOTICES AND INFORMATION\par \par %% MSBuild Locator NOTICES AND INFORMATION BEGIN HERE\par =========================================\par \par {{\field{\*\fldinst{HYPERLINK https://github.com/Microsoft/MSBuildLocator }}{\fldrslt{https://github.com/Microsoft/MSBuildLocator\ul0\cf0}}}}\f0\fs22\par \par \cf5\highlight3 MSBuild Locator \par \par MIT License \par \par Copyright (c) Microsoft Corporation. All rights reserved. \par \par Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: \par \par The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. \par \par THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE\cf0\highlight0 \par =========================================\par END OF MSBuild Locator NOTICES AND INFORMATION\par \par %% Humanizer NOTICES AND INFORMATION BEGIN HERE\par =========================================\par The MIT License (MIT)\par \par Copyright (c) 2012-2014 Mehdi Khalili\par \par Permission is hereby granted, free of charge, to any person obtaining a copy\par of this software and associated documentation files (the "Software"), to deal\par in the Software without restriction, including without limitation the rights\par to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\par copies of the Software, and to permit persons to whom the Software is\par furnished to do so, subject to the following conditions:\par \par The above copyright notice and this permission notice shall be included in\par all copies or substantial portions of the Software.\par \par THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\par IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\par FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\par AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\par LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\par OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\par THE SOFTWARE.\par \par ==============================================================================\par \par Inflector ({{\field{\*\fldinst{HYPERLINK https://github.com/srkirkland/Inflector }}{\fldrslt{https://github.com/srkirkland/Inflector\ul0\cf0}}}}\f0\fs22 )\par The MIT License (MIT)\par Copyright (c) 2013 Scott Kirkland\par \par ==============================================================================\par \par ByteSize ({{\field{\*\fldinst{HYPERLINK https://github.com/omar/ByteSize }}{\fldrslt{https://github.com/omar/ByteSize\ul0\cf0}}}}\f0\fs22 )\par The MIT License (MIT)\par Copyright (c) 2013-2014 Omar Khudeira ({{\field{\*\fldinst{HYPERLINK http://omar.io }}{\fldrslt{http://omar.io\ul0\cf0}}}}\f0\fs22 )\par \par ==============================================================================\par =========================================\par END OF Humanizer NOTICES AND INFORMATION\par \par %% ICSharpCode.Decompiler NOTICES AND INFORMATION BEGIN HERE\par =========================================\par SPDX identifier - MIT\par \par MIT License\par \par Copyright 2011-2019 AlphaSierraPapa\par \par Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\par \par The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\par \par THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\par =========================================\par END OF ICSharpCode.Decompiler NOTICES AND INFORMATION\par \par %% SQLitePCLRaw.bundle_green NOTICES AND INFORMATION BEGIN HERE\par =========================================\par \par Apache License\par Version 2.0, January 2004\par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/ }}{\fldrslt{http://www.apache.org/licenses/\ul0\cf0}}}}\f0\fs22\par \par TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\par \par 1. Definitions.\par \par "License" shall mean the terms and conditions for use, reproduction,\par and distribution as defined by Sections 1 through 9 of this document.\par \par "Licensor" shall mean the copyright owner or entity authorized by\par the copyright owner that is granting the License.\par \par "Legal Entity" shall mean the union of the acting entity and all\par other entities that control, are controlled by, or are under common\par control with that entity. For the purposes of this definition,\par "control" means (i) the power, direct or indirect, to cause the\par direction or management of such entity, whether by contract or\par otherwise, or (ii) ownership of fifty percent (50%) or more of the\par outstanding shares, or (iii) beneficial ownership of such entity.\par \par "You" (or "Your") shall mean an individual or Legal Entity\par exercising permissions granted by this License.\par \par "Source" form shall mean the preferred form for making modifications,\par including but not limited to software source code, documentation\par source, and configuration files.\par \par "Object" form shall mean any form resulting from mechanical\par transformation or translation of a Source form, including but\par not limited to compiled object code, generated documentation,\par and conversions to other media types.\par \par "Work" shall mean the work of authorship, whether in Source or\par Object form, made available under the License, as indicated by a\par copyright notice that is included in or attached to the work\par (an example is provided in the Appendix below).\par \par "Derivative Works" shall mean any work, whether in Source or Object\par form, that is based on (or derived from) the Work and for which the\par editorial revisions, annotations, elaborations, or other modifications\par represent, as a whole, an original work of authorship. For the purposes\par of this License, Derivative Works shall not include works that remain\par separable from, or merely link (or bind by name) to the interfaces of,\par the Work and Derivative Works thereof.\par \par "Contribution" shall mean any work of authorship, including\par the original version of the Work and any modifications or additions\par to that Work or Derivative Works thereof, that is intentionally\par submitted to Licensor for inclusion in the Work by the copyright owner\par or by an individual or Legal Entity authorized to submit on behalf of\par the copyright owner. For the purposes of this definition, "submitted"\par means any form of electronic, verbal, or written communication sent\par to the Licensor or its representatives, including but not limited to\par communication on electronic mailing lists, source code control systems,\par and issue tracking systems that are managed by, or on behalf of, the\par Licensor for the purpose of discussing and improving the Work, but\par excluding communication that is conspicuously marked or otherwise\par designated in writing by the copyright owner as "Not a Contribution."\par \par "Contributor" shall mean Licensor and any individual or Legal Entity\par on behalf of whom a Contribution has been received by Licensor and\par subsequently incorporated within the Work.\par \par 2. Grant of Copyright License. Subject to the terms and conditions of\par this License, each Contributor hereby grants to You a perpetual,\par worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par copyright license to reproduce, prepare Derivative Works of,\par publicly display, publicly perform, sublicense, and distribute the\par Work and such Derivative Works in Source or Object form.\par \par 3. Grant of Patent License. Subject to the terms and conditions of\par this License, each Contributor hereby grants to You a perpetual,\par worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par (except as stated in this section) patent license to make, have made,\par use, offer to sell, sell, import, and otherwise transfer the Work,\par where such license applies only to those patent claims licensable\par by such Contributor that are necessarily infringed by their\par Contribution(s) alone or by combination of their Contribution(s)\par with the Work to which such Contribution(s) was submitted. If You\par institute patent litigation against any entity (including a\par cross-claim or counterclaim in a lawsuit) alleging that the Work\par or a Contribution incorporated within the Work constitutes direct\par or contributory patent infringement, then any patent licenses\par granted to You under this License for that Work shall terminate\par as of the date such litigation is filed.\par \par 4. Redistribution. You may reproduce and distribute copies of the\par Work or Derivative Works thereof in any medium, with or without\par modifications, and in Source or Object form, provided that You\par meet the following conditions:\par \par (a) You must give any other recipients of the Work or\par Derivative Works a copy of this License; and\par \par (b) You must cause any modified files to carry prominent notices\par stating that You changed the files; and\par \par (c) You must retain, in the Source form of any Derivative Works\par that You distribute, all copyright, patent, trademark, and\par attribution notices from the Source form of the Work,\par excluding those notices that do not pertain to any part of\par the Derivative Works; and\par \par (d) If the Work includes a "NOTICE" text file as part of its\par distribution, then any Derivative Works that You distribute must\par include a readable copy of the attribution notices contained\par within such NOTICE file, excluding those notices that do not\par pertain to any part of the Derivative Works, in at least one\par of the following places: within a NOTICE text file distributed\par as part of the Derivative Works; within the Source form or\par documentation, if provided along with the Derivative Works; or,\par within a display generated by the Derivative Works, if and\par wherever such third-party notices normally appear. The contents\par of the NOTICE file are for informational purposes only and\par do not modify the License. You may add Your own attribution\par notices within Derivative Works that You distribute, alongside\par or as an addendum to the NOTICE text from the Work, provided\par that such additional attribution notices cannot be construed\par as modifying the License.\par \par You may add Your own copyright statement to Your modifications and\par may provide additional or different license terms and conditions\par for use, reproduction, or distribution of Your modifications, or\par for any such Derivative Works as a whole, provided Your use,\par reproduction, and distribution of the Work otherwise complies with\par the conditions stated in this License.\par \par 5. Submission of Contributions. Unless You explicitly state otherwise,\par any Contribution intentionally submitted for inclusion in the Work\par by You to the Licensor shall be under the terms and conditions of\par this License, without any additional terms or conditions.\par Notwithstanding the above, nothing herein shall supersede or modify\par the terms of any separate license agreement you may have executed\par with Licensor regarding such Contributions.\par \par 6. Trademarks. This License does not grant permission to use the trade\par names, trademarks, service marks, or product names of the Licensor,\par except as required for reasonable and customary use in describing the\par origin of the Work and reproducing the content of the NOTICE file.\par \par 7. Disclaimer of Warranty. Unless required by applicable law or\par agreed to in writing, Licensor provides the Work (and each\par Contributor provides its Contributions) on an "AS IS" BASIS,\par WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\par implied, including, without limitation, any warranties or conditions\par of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\par PARTICULAR PURPOSE. You are solely responsible for determining the\par appropriateness of using or redistributing the Work and assume any\par risks associated with Your exercise of permissions under this License.\par \par 8. Limitation of Liability. In no event and under no legal theory,\par whether in tort (including negligence), contract, or otherwise,\par unless required by applicable law (such as deliberate and grossly\par negligent acts) or agreed to in writing, shall any Contributor be\par liable to You for damages, including any direct, indirect, special,\par incidental, or consequential damages of any character arising as a\par result of this License or out of the use or inability to use the\par Work (including but not limited to damages for loss of goodwill,\par work stoppage, computer failure or malfunction, or any and all\par other commercial damages or losses), even if such Contributor\par has been advised of the possibility of such damages.\par \par 9. Accepting Warranty or Additional Liability. While redistributing\par the Work or Derivative Works thereof, You may choose to offer,\par and charge a fee for, acceptance of support, warranty, indemnity,\par or other liability obligations and/or rights consistent with this\par License. However, in accepting such obligations, You may act only\par on Your own behalf and on Your sole responsibility, not on behalf\par of any other Contributor, and only if You agree to indemnify,\par defend, and hold each Contributor harmless for any liability\par incurred by, or claims asserted against, such Contributor by reason\par of your accepting any such warranty or additional liability.\par \par END OF TERMS AND CONDITIONS\par \par APPENDIX: How to apply the Apache License to your work.\par \par To apply the Apache License to your work, attach the following\par boilerplate notice, with the fields enclosed by brackets "[]"\par replaced with your own identifying information. (Don't include\par the brackets!) The text should be enclosed in the appropriate\par comment syntax for the file format. We also recommend that a\par file or class name and description of purpose be included on the\par same "printed page" as the copyright notice for easier\par identification within third-party archives.\par \par Copyright [yyyy] [name of copyright owner]\par \par Licensed under the Apache License, Version 2.0 (the "License");\par you may not use this file except in compliance with the License.\par You may obtain a copy of the License at\par \par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f0\fs22\par \par Unless required by applicable law or agreed to in writing, software\par distributed under the License is distributed on an "AS IS" BASIS,\par WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\par See the License for the specific language governing permissions and\par limitations under the License.\par \par \pard\widctlpar\tx916\tx1832\tx2748\tx3664\tx4580\tx5496\tx6412\tx7328\tx8244\tx9160\tx10076\tx10992\tx11908\tx12824\tx13740\tx14656\cf5\f1\fs20 ----------------------------------------------------------------\par Copyright on SQLitePCL.raw\par ----------------------------------------------------------------\par \par Version prior to 2.0 were labeled with the copyright owned by\par Zumero. In 2.0, this changed to SourceGear. There is no legal\par distinction, as Zumero is simply a dba name for SourceGear.\par \par And in either case, the open source license remains the same,\par Apache v2.\par \par ----------------------------------------------------------------\par License for SQLite\par ----------------------------------------------------------------\par \par ** The author disclaims copyright to this source code. In place of\par ** a legal notice, here is a blessing:\par **\par ** May you do good and not evil.\par ** May you find forgiveness for yourself and forgive others.\par ** May you share freely, never taking more than you give.\par **\par \par \par ----------------------------------------------------------------\par License for MS Open Tech\par ----------------------------------------------------------------\par \par // Copyright \'a9 Microsoft Open Technologies, Inc.\par // All Rights Reserved\par // Licensed under the Apache License, Version 2.0 (the "License"); you may not\par // use this file except in compliance with the License. You may obtain a copy\par // of the License at \par // {\cf0{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f1\fs20\par // \par // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\par // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY\par // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\par // MERCHANTABLITY OR NON-INFRINGEMENT.\par // \par // See the Apache 2 License for the specific language governing permissions and\par // limitations under the License.\par \par \par ----------------------------------------------------------------\par License for SQLCipher\par ----------------------------------------------------------------\par \par Copyright (c) 2008, ZETETIC LLC\par All rights reserved.\par \par Redistribution and use in source and binary forms, with or without\par modification, are permitted provided that the following conditions are met:\par * Redistributions of source code must retain the above copyright\par notice, this list of conditions and the following disclaimer.\par * Redistributions in binary form must reproduce the above copyright\par notice, this list of conditions and the following disclaimer in the\par documentation and/or other materials provided with the distribution.\par * Neither the name of the ZETETIC LLC nor the\par names of its contributors may be used to endorse or promote products\par derived from this software without specific prior written permission.\par \par THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY\par EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\par WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\par DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY\par DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\par (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\par LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\par ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\par (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\par SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\par \par \par ----------------------------------------------------------------\par License for OpenSSL libcrypto\par ----------------------------------------------------------------\par \par LICENSE ISSUES\par ==============\par \par The OpenSSL toolkit stays under a dual license, i.e. both the conditions of\par the OpenSSL License and the original SSLeay license apply to the toolkit.\par See below for the actual license texts. Actually both licenses are BSD-style\par Open Source licenses. In case of any license issues related to OpenSSL\par please contact [email protected].\par \par OpenSSL License\par ---------------\par \par /* ====================================================================\par * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved.\par *\par * Redistribution and use in source and binary forms, with or without\par * modification, are permitted provided that the following conditions\par * are met:\par *\par * 1. Redistributions of source code must retain the above copyright\par * notice, this list of conditions and the following disclaimer. \par *\par * 2. Redistributions in binary form must reproduce the above copyright\par * notice, this list of conditions and the following disclaimer in\par * the documentation and/or other materials provided with the\par * distribution.\par *\par * 3. All advertising materials mentioning features or use of this\par * software must display the following acknowledgment:\par * "This product includes software developed by the OpenSSL Project\par * for use in the OpenSSL Toolkit. ({\cf0{\field{\*\fldinst{HYPERLINK http://www.openssl.org/ }}{\fldrslt{http://www.openssl.org/\ul0\cf0}}}}\f1\fs20 )"\par *\par * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to\par * endorse or promote products derived from this software without\par * prior written permission. For written permission, please contact\par * [email protected].\par *\par * 5. Products derived from this software may not be called "OpenSSL"\par * nor may "OpenSSL" appear in their names without prior written\par * permission of the OpenSSL Project.\par *\par * 6. Redistributions of any form whatsoever must retain the following\par * acknowledgment:\par * "This product includes software developed by the OpenSSL Project\par * for use in the OpenSSL Toolkit ({\cf0{\field{\*\fldinst{HYPERLINK http://www.openssl.org/ }}{\fldrslt{http://www.openssl.org/\ul0\cf0}}}}\f1\fs20 )"\par *\par * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY\par * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\par * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\par * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR\par * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\par * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\par * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\par * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\par * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\par * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\par * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\par * OF THE POSSIBILITY OF SUCH DAMAGE.\par * ====================================================================\par *\par * This product includes cryptographic software written by Eric Young\par * ([email protected]). This product includes software written by Tim\par * Hudson ([email protected]).\par *\par */\par \par Original SSLeay License\par -----------------------\par \par /* Copyright (C) 1995-1998 Eric Young ([email protected])\par * All rights reserved.\par *\par * This package is an SSL implementation written\par * by Eric Young ([email protected]).\par * The implementation was written so as to conform with Netscapes SSL.\par * \par * This library is free for commercial and non-commercial use as long as\par * the following conditions are aheared to. The following conditions\par * apply to all code found in this distribution, be it the RC4, RSA,\par * lhash, DES, etc., code; not just the SSL code. The SSL documentation\par * included with this distribution is covered by the same copyright terms\par * except that the holder is Tim Hudson ([email protected]).\par * \par * Copyright remains Eric Young's, and as such any Copyright notices in\par * the code are not to be removed.\par * If this package is used in a product, Eric Young should be given attribution\par * as the author of the parts of the library used.\par * This can be in the form of a textual message at program startup or\par * in documentation (online or textual) provided with the package.\par * \par * Redistribution and use in source and binary forms, with or without\par * modification, are permitted provided that the following conditions\par * are met:\par * 1. Redistributions of source code must retain the copyright\par * notice, this list of conditions and the following disclaimer.\par * 2. Redistributions in binary form must reproduce the above copyright\par * notice, this list of conditions and the following disclaimer in the\par * documentation and/or other materials provided with the distribution.\par * 3. All advertising materials mentioning features or use of this software\par * must display the following acknowledgement:\par * "This product includes cryptographic software written by\par * Eric Young ([email protected])"\par * The word 'cryptographic' can be left out if the rouines from the library\par * being used are not cryptographic related :-).\par * 4. If you include any Windows specific code (or a derivative thereof) from \par * the apps directory (application code) you must include an acknowledgement:\par * "This product includes software written by Tim Hudson ([email protected])"\par * \par * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND\par * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\par * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\par * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\par * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\par * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\par * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\par * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\par * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\par * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\par * SUCH DAMAGE.\par * \par * The licence and distribution terms for any publically available version or\par * derivative of this code cannot be changed. i.e. this code cannot simply be\par * copied and put under another distribution licence\par * [including the GNU Public Licence.]\par */\par \pard\nowidctlpar\cf0\f0\fs22\par =========================================\par END OF SQLitePCLRaw.bundle_green NOTICES AND INFORMATION\par \par %% SQLitePCLRaw.core NOTICES AND INFORMATION BEGIN HERE\par =========================================\par Apache License\par Version 2.0, January 2004\par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/ }}{\fldrslt{http://www.apache.org/licenses/\ul0\cf0}}}}\f0\fs22\par \par TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\par \par 1. Definitions.\par \par "License" shall mean the terms and conditions for use, reproduction,\par and distribution as defined by Sections 1 through 9 of this document.\par \par "Licensor" shall mean the copyright owner or entity authorized by\par the copyright owner that is granting the License.\par \par "Legal Entity" shall mean the union of the acting entity and all\par other entities that control, are controlled by, or are under common\par control with that entity. For the purposes of this definition,\par "control" means (i) the power, direct or indirect, to cause the\par direction or management of such entity, whether by contract or\par otherwise, or (ii) ownership of fifty percent (50%) or more of the\par outstanding shares, or (iii) beneficial ownership of such entity.\par \par "You" (or "Your") shall mean an individual or Legal Entity\par exercising permissions granted by this License.\par \par "Source" form shall mean the preferred form for making modifications,\par including but not limited to software source code, documentation\par source, and configuration files.\par \par "Object" form shall mean any form resulting from mechanical\par transformation or translation of a Source form, including but\par not limited to compiled object code, generated documentation,\par and conversions to other media types.\par \par "Work" shall mean the work of authorship, whether in Source or\par Object form, made available under the License, as indicated by a\par copyright notice that is included in or attached to the work\par (an example is provided in the Appendix below).\par \par "Derivative Works" shall mean any work, whether in Source or Object\par form, that is based on (or derived from) the Work and for which the\par editorial revisions, annotations, elaborations, or other modifications\par represent, as a whole, an original work of authorship. For the purposes\par of this License, Derivative Works shall not include works that remain\par separable from, or merely link (or bind by name) to the interfaces of,\par the Work and Derivative Works thereof.\par \par "Contribution" shall mean any work of authorship, including\par the original version of the Work and any modifications or additions\par to that Work or Derivative Works thereof, that is intentionally\par submitted to Licensor for inclusion in the Work by the copyright owner\par or by an individual or Legal Entity authorized to submit on behalf of\par the copyright owner. For the purposes of this definition, "submitted"\par means any form of electronic, verbal, or written communication sent\par to the Licensor or its representatives, including but not limited to\par communication on electronic mailing lists, source code control systems,\par and issue tracking systems that are managed by, or on behalf of, the\par Licensor for the purpose of discussing and improving the Work, but\par excluding communication that is conspicuously marked or otherwise\par designated in writing by the copyright owner as "Not a Contribution."\par \par "Contributor" shall mean Licensor and any individual or Legal Entity\par on behalf of whom a Contribution has been received by Licensor and\par subsequently incorporated within the Work.\par \par 2. Grant of Copyright License. Subject to the terms and conditions of\par this License, each Contributor hereby grants to You a perpetual,\par worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par copyright license to reproduce, prepare Derivative Works of,\par publicly display, publicly perform, sublicense, and distribute the\par Work and such Derivative Works in Source or Object form.\par \par 3. Grant of Patent License. Subject to the terms and conditions of\par this License, each Contributor hereby grants to You a perpetual,\par worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par (except as stated in this section) patent license to make, have made,\par use, offer to sell, sell, import, and otherwise transfer the Work,\par where such license applies only to those patent claims licensable\par by such Contributor that are necessarily infringed by their\par Contribution(s) alone or by combination of their Contribution(s)\par with the Work to which such Contribution(s) was submitted. If You\par institute patent litigation against any entity (including a\par cross-claim or counterclaim in a lawsuit) alleging that the Work\par or a Contribution incorporated within the Work constitutes direct\par or contributory patent infringement, then any patent licenses\par granted to You under this License for that Work shall terminate\par as of the date such litigation is filed.\par \par 4. Redistribution. You may reproduce and distribute copies of the\par Work or Derivative Works thereof in any medium, with or without\par modifications, and in Source or Object form, provided that You\par meet the following conditions:\par \par (a) You must give any other recipients of the Work or\par Derivative Works a copy of this License; and\par \par (b) You must cause any modified files to carry prominent notices\par stating that You changed the files; and\par \par (c) You must retain, in the Source form of any Derivative Works\par that You distribute, all copyright, patent, trademark, and\par attribution notices from the Source form of the Work,\par excluding those notices that do not pertain to any part of\par the Derivative Works; and\par \par (d) If the Work includes a "NOTICE" text file as part of its\par distribution, then any Derivative Works that You distribute must\par include a readable copy of the attribution notices contained\par within such NOTICE file, excluding those notices that do not\par pertain to any part of the Derivative Works, in at least one\par of the following places: within a NOTICE text file distributed\par as part of the Derivative Works; within the Source form or\par documentation, if provided along with the Derivative Works; or,\par within a display generated by the Derivative Works, if and\par wherever such third-party notices normally appear. The contents\par of the NOTICE file are for informational purposes only and\par do not modify the License. You may add Your own attribution\par notices within Derivative Works that You distribute, alongside\par or as an addendum to the NOTICE text from the Work, provided\par that such additional attribution notices cannot be construed\par as modifying the License.\par \par You may add Your own copyright statement to Your modifications and\par may provide additional or different license terms and conditions\par for use, reproduction, or distribution of Your modifications, or\par for any such Derivative Works as a whole, provided Your use,\par reproduction, and distribution of the Work otherwise complies with\par the conditions stated in this License.\par \par 5. Submission of Contributions. Unless You explicitly state otherwise,\par any Contribution intentionally submitted for inclusion in the Work\par by You to the Licensor shall be under the terms and conditions of\par this License, without any additional terms or conditions.\par Notwithstanding the above, nothing herein shall supersede or modify\par the terms of any separate license agreement you may have executed\par with Licensor regarding such Contributions.\par \par 6. Trademarks. This License does not grant permission to use the trade\par names, trademarks, service marks, or product names of the Licensor,\par except as required for reasonable and customary use in describing the\par origin of the Work and reproducing the content of the NOTICE file.\par \par 7. Disclaimer of Warranty. Unless required by applicable law or\par agreed to in writing, Licensor provides the Work (and each\par Contributor provides its Contributions) on an "AS IS" BASIS,\par WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\par implied, including, without limitation, any warranties or conditions\par of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\par PARTICULAR PURPOSE. You are solely responsible for determining the\par appropriateness of using or redistributing the Work and assume any\par risks associated with Your exercise of permissions under this License.\par \par 8. Limitation of Liability. In no event and under no legal theory,\par whether in tort (including negligence), contract, or otherwise,\par unless required by applicable law (such as deliberate and grossly\par negligent acts) or agreed to in writing, shall any Contributor be\par liable to You for damages, including any direct, indirect, special,\par incidental, or consequential damages of any character arising as a\par result of this License or out of the use or inability to use the\par Work (including but not limited to damages for loss of goodwill,\par work stoppage, computer failure or malfunction, or any and all\par other commercial damages or losses), even if such Contributor\par has been advised of the possibility of such damages.\par \par 9. Accepting Warranty or Additional Liability. While redistributing\par the Work or Derivative Works thereof, You may choose to offer,\par and charge a fee for, acceptance of support, warranty, indemnity,\par or other liability obligations and/or rights consistent with this\par License. However, in accepting such obligations, You may act only\par on Your own behalf and on Your sole responsibility, not on behalf\par of any other Contributor, and only if You agree to indemnify,\par defend, and hold each Contributor harmless for any liability\par incurred by, or claims asserted against, such Contributor by reason\par of your accepting any such warranty or additional liability.\par \par END OF TERMS AND CONDITIONS\par \par APPENDIX: How to apply the Apache License to your work.\par \par To apply the Apache License to your work, attach the following\par boilerplate notice, with the fields enclosed by brackets "[]"\par replaced with your own identifying information. (Don't include\par the brackets!) The text should be enclosed in the appropriate\par comment syntax for the file format. We also recommend that a\par file or class name and description of purpose be included on the\par same "printed page" as the copyright notice for easier\par identification within third-party archives.\par \par Copyright [yyyy] [name of copyright owner]\par \par Licensed under the Apache License, Version 2.0 (the "License");\par you may not use this file except in compliance with the License.\par You may obtain a copy of the License at\par \par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f0\fs22\par \par Unless required by applicable law or agreed to in writing, software\par distributed under the License is distributed on an "AS IS" BASIS,\par WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\par See the License for the specific language governing permissions and\par limitations under the License.\par \par \pard\widctlpar\tx916\tx1832\tx2748\tx3664\tx4580\tx5496\tx6412\tx7328\tx8244\tx9160\tx10076\tx10992\tx11908\tx12824\tx13740\tx14656\cf5\f1\fs20 ----------------------------------------------------------------\par Copyright on SQLitePCL.raw\par ----------------------------------------------------------------\par \par Version prior to 2.0 were labeled with the copyright owned by\par Zumero. In 2.0, this changed to SourceGear. There is no legal\par distinction, as Zumero is simply a dba name for SourceGear.\par \par And in either case, the open source license remains the same,\par Apache v2.\par \par ----------------------------------------------------------------\par License for SQLite\par ----------------------------------------------------------------\par \par ** The author disclaims copyright to this source code. In place of\par ** a legal notice, here is a blessing:\par **\par ** May you do good and not evil.\par ** May you find forgiveness for yourself and forgive others.\par ** May you share freely, never taking more than you give.\par **\par \par \par ----------------------------------------------------------------\par License for MS Open Tech\par ----------------------------------------------------------------\par \par // Copyright \'a9 Microsoft Open Technologies, Inc.\par // All Rights Reserved\par // Licensed under the Apache License, Version 2.0 (the "License"); you may not\par // use this file except in compliance with the License. You may obtain a copy\par // of the License at \par // {\cf0{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f1\fs20\par // \par // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\par // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY\par // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\par // MERCHANTABLITY OR NON-INFRINGEMENT.\par // \par // See the Apache 2 License for the specific language governing permissions and\par // limitations under the License.\par \par \par ----------------------------------------------------------------\par License for SQLCipher\par ----------------------------------------------------------------\par \par Copyright (c) 2008, ZETETIC LLC\par All rights reserved.\par \par Redistribution and use in source and binary forms, with or without\par modification, are permitted provided that the following conditions are met:\par * Redistributions of source code must retain the above copyright\par notice, this list of conditions and the following disclaimer.\par * Redistributions in binary form must reproduce the above copyright\par notice, this list of conditions and the following disclaimer in the\par documentation and/or other materials provided with the distribution.\par * Neither the name of the ZETETIC LLC nor the\par names of its contributors may be used to endorse or promote products\par derived from this software without specific prior written permission.\par \par THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY\par EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\par WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\par DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY\par DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\par (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\par LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\par ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\par (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\par SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\par \par \par ----------------------------------------------------------------\par License for OpenSSL libcrypto\par ----------------------------------------------------------------\par \par LICENSE ISSUES\par ==============\par \par The OpenSSL toolkit stays under a dual license, i.e. both the conditions of\par the OpenSSL License and the original SSLeay license apply to the toolkit.\par See below for the actual license texts. Actually both licenses are BSD-style\par Open Source licenses. In case of any license issues related to OpenSSL\par please contact [email protected].\par \par OpenSSL License\par ---------------\par \par /* ====================================================================\par * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved.\par *\par * Redistribution and use in source and binary forms, with or without\par * modification, are permitted provided that the following conditions\par * are met:\par *\par * 1. Redistributions of source code must retain the above copyright\par * notice, this list of conditions and the following disclaimer. \par *\par * 2. Redistributions in binary form must reproduce the above copyright\par * notice, this list of conditions and the following disclaimer in\par * the documentation and/or other materials provided with the\par * distribution.\par *\par * 3. All advertising materials mentioning features or use of this\par * software must display the following acknowledgment:\par * "This product includes software developed by the OpenSSL Project\par * for use in the OpenSSL Toolkit. ({\cf0{\field{\*\fldinst{HYPERLINK http://www.openssl.org/ }}{\fldrslt{http://www.openssl.org/\ul0\cf0}}}}\f1\fs20 )"\par *\par * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to\par * endorse or promote products derived from this software without\par * prior written permission. For written permission, please contact\par * [email protected].\par *\par * 5. Products derived from this software may not be called "OpenSSL"\par * nor may "OpenSSL" appear in their names without prior written\par * permission of the OpenSSL Project.\par *\par * 6. Redistributions of any form whatsoever must retain the following\par * acknowledgment:\par * "This product includes software developed by the OpenSSL Project\par * for use in the OpenSSL Toolkit ({\cf0{\field{\*\fldinst{HYPERLINK http://www.openssl.org/ }}{\fldrslt{http://www.openssl.org/\ul0\cf0}}}}\f1\fs20 )"\par *\par * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY\par * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\par * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\par * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR\par * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\par * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\par * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\par * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\par * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\par * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\par * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\par * OF THE POSSIBILITY OF SUCH DAMAGE.\par * ====================================================================\par *\par * This product includes cryptographic software written by Eric Young\par * ([email protected]). This product includes software written by Tim\par * Hudson ([email protected]).\par *\par */\par \par Original SSLeay License\par -----------------------\par \par /* Copyright (C) 1995-1998 Eric Young ([email protected])\par * All rights reserved.\par *\par * This package is an SSL implementation written\par * by Eric Young ([email protected]).\par * The implementation was written so as to conform with Netscapes SSL.\par * \par * This library is free for commercial and non-commercial use as long as\par * the following conditions are aheared to. The following conditions\par * apply to all code found in this distribution, be it the RC4, RSA,\par * lhash, DES, etc., code; not just the SSL code. The SSL documentation\par * included with this distribution is covered by the same copyright terms\par * except that the holder is Tim Hudson ([email protected]).\par * \par * Copyright remains Eric Young's, and as such any Copyright notices in\par * the code are not to be removed.\par * If this package is used in a product, Eric Young should be given attribution\par * as the author of the parts of the library used.\par * This can be in the form of a textual message at program startup or\par * in documentation (online or textual) provided with the package.\par * \par * Redistribution and use in source and binary forms, with or without\par * modification, are permitted provided that the following conditions\par * are met:\par * 1. Redistributions of source code must retain the copyright\par * notice, this list of conditions and the following disclaimer.\par * 2. Redistributions in binary form must reproduce the above copyright\par * notice, this list of conditions and the following disclaimer in the\par * documentation and/or other materials provided with the distribution.\par * 3. All advertising materials mentioning features or use of this software\par * must display the following acknowledgement:\par * "This product includes cryptographic software written by\par * Eric Young ([email protected])"\par * The word 'cryptographic' can be left out if the rouines from the library\par * being used are not cryptographic related :-).\par * 4. If you include any Windows specific code (or a derivative thereof) from \par * the apps directory (application code) you must include an acknowledgement:\par * "This product includes software written by Tim Hudson ([email protected])"\par * \par * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND\par * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\par * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\par * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\par * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\par * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\par * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\par * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\par * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\par * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\par * SUCH DAMAGE.\par * \par * The licence and distribution terms for any publically available version or\par * derivative of this code cannot be changed. i.e. this code cannot simply be\par * copied and put under another distribution licence\par * [including the GNU Public Licence.]\par */\par \pard\nowidctlpar\cf0\f0\fs22 =========================================\par END OF SQLitePCLRaw.core NOTICES AND INFORMATION\par \par %% SQLitePCLRaw.provider.e_sqlite3.net45 NOTICES AND INFORMATION BEGIN HERE\par =========================================\par Apache License\par Version 2.0, January 2004\par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/ }}{\fldrslt{http://www.apache.org/licenses/\ul0\cf0}}}}\f0\fs22\par \par TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\par \par 1. Definitions.\par \par "License" shall mean the terms and conditions for use, reproduction,\par and distribution as defined by Sections 1 through 9 of this document.\par \par "Licensor" shall mean the copyright owner or entity authorized by\par the copyright owner that is granting the License.\par \par "Legal Entity" shall mean the union of the acting entity and all\par other entities that control, are controlled by, or are under common\par control with that entity. For the purposes of this definition,\par "control" means (i) the power, direct or indirect, to cause the\par direction or management of such entity, whether by contract or\par otherwise, or (ii) ownership of fifty percent (50%) or more of the\par outstanding shares, or (iii) beneficial ownership of such entity.\par \par "You" (or "Your") shall mean an individual or Legal Entity\par exercising permissions granted by this License.\par \par "Source" form shall mean the preferred form for making modifications,\par including but not limited to software source code, documentation\par source, and configuration files.\par \par "Object" form shall mean any form resulting from mechanical\par transformation or translation of a Source form, including but\par not limited to compiled object code, generated documentation,\par and conversions to other media types.\par \par "Work" shall mean the work of authorship, whether in Source or\par Object form, made available under the License, as indicated by a\par copyright notice that is included in or attached to the work\par (an example is provided in the Appendix below).\par \par "Derivative Works" shall mean any work, whether in Source or Object\par form, that is based on (or derived from) the Work and for which the\par editorial revisions, annotations, elaborations, or other modifications\par represent, as a whole, an original work of authorship. For the purposes\par of this License, Derivative Works shall not include works that remain\par separable from, or merely link (or bind by name) to the interfaces of,\par the Work and Derivative Works thereof.\par \par "Contribution" shall mean any work of authorship, including\par the original version of the Work and any modifications or additions\par to that Work or Derivative Works thereof, that is intentionally\par submitted to Licensor for inclusion in the Work by the copyright owner\par or by an individual or Legal Entity authorized to submit on behalf of\par the copyright owner. For the purposes of this definition, "submitted"\par means any form of electronic, verbal, or written communication sent\par to the Licensor or its representatives, including but not limited to\par communication on electronic mailing lists, source code control systems,\par and issue tracking systems that are managed by, or on behalf of, the\par Licensor for the purpose of discussing and improving the Work, but\par excluding communication that is conspicuously marked or otherwise\par designated in writing by the copyright owner as "Not a Contribution."\par \par "Contributor" shall mean Licensor and any individual or Legal Entity\par on behalf of whom a Contribution has been received by Licensor and\par subsequently incorporated within the Work.\par \par 2. Grant of Copyright License. Subject to the terms and conditions of\par this License, each Contributor hereby grants to You a perpetual,\par worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par copyright license to reproduce, prepare Derivative Works of,\par publicly display, publicly perform, sublicense, and distribute the\par Work and such Derivative Works in Source or Object form.\par \par 3. Grant of Patent License. Subject to the terms and conditions of\par this License, each Contributor hereby grants to You a perpetual,\par worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par (except as stated in this section) patent license to make, have made,\par use, offer to sell, sell, import, and otherwise transfer the Work,\par where such license applies only to those patent claims licensable\par by such Contributor that are necessarily infringed by their\par Contribution(s) alone or by combination of their Contribution(s)\par with the Work to which such Contribution(s) was submitted. If You\par institute patent litigation against any entity (including a\par cross-claim or counterclaim in a lawsuit) alleging that the Work\par or a Contribution incorporated within the Work constitutes direct\par or contributory patent infringement, then any patent licenses\par granted to You under this License for that Work shall terminate\par as of the date such litigation is filed.\par \par 4. Redistribution. You may reproduce and distribute copies of the\par Work or Derivative Works thereof in any medium, with or without\par modifications, and in Source or Object form, provided that You\par meet the following conditions:\par \par (a) You must give any other recipients of the Work or\par Derivative Works a copy of this License; and\par \par (b) You must cause any modified files to carry prominent notices\par stating that You changed the files; and\par \par (c) You must retain, in the Source form of any Derivative Works\par that You distribute, all copyright, patent, trademark, and\par attribution notices from the Source form of the Work,\par excluding those notices that do not pertain to any part of\par the Derivative Works; and\par \par (d) If the Work includes a "NOTICE" text file as part of its\par distribution, then any Derivative Works that You distribute must\par include a readable copy of the attribution notices contained\par within such NOTICE file, excluding those notices that do not\par pertain to any part of the Derivative Works, in at least one\par of the following places: within a NOTICE text file distributed\par as part of the Derivative Works; within the Source form or\par documentation, if provided along with the Derivative Works; or,\par within a display generated by the Derivative Works, if and\par wherever such third-party notices normally appear. The contents\par of the NOTICE file are for informational purposes only and\par do not modify the License. You may add Your own attribution\par notices within Derivative Works that You distribute, alongside\par or as an addendum to the NOTICE text from the Work, provided\par that such additional attribution notices cannot be construed\par as modifying the License.\par \par You may add Your own copyright statement to Your modifications and\par may provide additional or different license terms and conditions\par for use, reproduction, or distribution of Your modifications, or\par for any such Derivative Works as a whole, provided Your use,\par reproduction, and distribution of the Work otherwise complies with\par the conditions stated in this License.\par \par 5. Submission of Contributions. Unless You explicitly state otherwise,\par any Contribution intentionally submitted for inclusion in the Work\par by You to the Licensor shall be under the terms and conditions of\par this License, without any additional terms or conditions.\par Notwithstanding the above, nothing herein shall supersede or modify\par the terms of any separate license agreement you may have executed\par with Licensor regarding such Contributions.\par \par 6. Trademarks. This License does not grant permission to use the trade\par names, trademarks, service marks, or product names of the Licensor,\par except as required for reasonable and customary use in describing the\par origin of the Work and reproducing the content of the NOTICE file.\par \par 7. Disclaimer of Warranty. Unless required by applicable law or\par agreed to in writing, Licensor provides the Work (and each\par Contributor provides its Contributions) on an "AS IS" BASIS,\par WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\par implied, including, without limitation, any warranties or conditions\par of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\par PARTICULAR PURPOSE. You are solely responsible for determining the\par appropriateness of using or redistributing the Work and assume any\par risks associated with Your exercise of permissions under this License.\par \par 8. Limitation of Liability. In no event and under no legal theory,\par whether in tort (including negligence), contract, or otherwise,\par unless required by applicable law (such as deliberate and grossly\par negligent acts) or agreed to in writing, shall any Contributor be\par liable to You for damages, including any direct, indirect, special,\par incidental, or consequential damages of any character arising as a\par result of this License or out of the use or inability to use the\par Work (including but not limited to damages for loss of goodwill,\par work stoppage, computer failure or malfunction, or any and all\par other commercial damages or losses), even if such Contributor\par has been advised of the possibility of such damages.\par \par 9. Accepting Warranty or Additional Liability. While redistributing\par the Work or Derivative Works thereof, You may choose to offer,\par and charge a fee for, acceptance of support, warranty, indemnity,\par or other liability obligations and/or rights consistent with this\par License. However, in accepting such obligations, You may act only\par on Your own behalf and on Your sole responsibility, not on behalf\par of any other Contributor, and only if You agree to indemnify,\par defend, and hold each Contributor harmless for any liability\par incurred by, or claims asserted against, such Contributor by reason\par of your accepting any such warranty or additional liability.\par \par END OF TERMS AND CONDITIONS\par \par APPENDIX: How to apply the Apache License to your work.\par \par To apply the Apache License to your work, attach the following\par boilerplate notice, with the fields enclosed by brackets "[]"\par replaced with your own identifying information. (Don't include\par the brackets!) The text should be enclosed in the appropriate\par comment syntax for the file format. We also recommend that a\par file or class name and description of purpose be included on the\par same "printed page" as the copyright notice for easier\par identification within third-party archives.\par \par Copyright [yyyy] [name of copyright owner]\par \par Licensed under the Apache License, Version 2.0 (the "License");\par you may not use this file except in compliance with the License.\par You may obtain a copy of the License at\par \par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f0\fs22\par \par Unless required by applicable law or agreed to in writing, software\par distributed under the License is distributed on an "AS IS" BASIS,\par WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\par See the License for the specific language governing permissions and\par limitations under the License.\par \par \pard\widctlpar\tx916\tx1832\tx2748\tx3664\tx4580\tx5496\tx6412\tx7328\tx8244\tx9160\tx10076\tx10992\tx11908\tx12824\tx13740\tx14656\cf5\f1\fs20 ----------------------------------------------------------------\par Copyright on SQLitePCL.raw\par ----------------------------------------------------------------\par \par Version prior to 2.0 were labeled with the copyright owned by\par Zumero. In 2.0, this changed to SourceGear. There is no legal\par distinction, as Zumero is simply a dba name for SourceGear.\par \par And in either case, the open source license remains the same,\par Apache v2.\par \par ----------------------------------------------------------------\par License for SQLite\par ----------------------------------------------------------------\par \par ** The author disclaims copyright to this source code. In place of\par ** a legal notice, here is a blessing:\par **\par ** May you do good and not evil.\par ** May you find forgiveness for yourself and forgive others.\par ** May you share freely, never taking more than you give.\par **\par \par \par ----------------------------------------------------------------\par License for MS Open Tech\par ----------------------------------------------------------------\par \par // Copyright \'a9 Microsoft Open Technologies, Inc.\par // All Rights Reserved\par // Licensed under the Apache License, Version 2.0 (the "License"); you may not\par // use this file except in compliance with the License. You may obtain a copy\par // of the License at \par // {\cf0{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f1\fs20\par // \par // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\par // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY\par // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\par // MERCHANTABLITY OR NON-INFRINGEMENT.\par // \par // See the Apache 2 License for the specific language governing permissions and\par // limitations under the License.\par \par \par ----------------------------------------------------------------\par License for SQLCipher\par ----------------------------------------------------------------\par \par Copyright (c) 2008, ZETETIC LLC\par All rights reserved.\par \par Redistribution and use in source and binary forms, with or without\par modification, are permitted provided that the following conditions are met:\par * Redistributions of source code must retain the above copyright\par notice, this list of conditions and the following disclaimer.\par * Redistributions in binary form must reproduce the above copyright\par notice, this list of conditions and the following disclaimer in the\par documentation and/or other materials provided with the distribution.\par * Neither the name of the ZETETIC LLC nor the\par names of its contributors may be used to endorse or promote products\par derived from this software without specific prior written permission.\par \par THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY\par EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\par WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\par DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY\par DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\par (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\par LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\par ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\par (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\par SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\par \par \par ----------------------------------------------------------------\par License for OpenSSL libcrypto\par ----------------------------------------------------------------\par \par LICENSE ISSUES\par ==============\par \par The OpenSSL toolkit stays under a dual license, i.e. both the conditions of\par the OpenSSL License and the original SSLeay license apply to the toolkit.\par See below for the actual license texts. Actually both licenses are BSD-style\par Open Source licenses. In case of any license issues related to OpenSSL\par please contact [email protected].\par \par OpenSSL License\par ---------------\par \par /* ====================================================================\par * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved.\par *\par * Redistribution and use in source and binary forms, with or without\par * modification, are permitted provided that the following conditions\par * are met:\par *\par * 1. Redistributions of source code must retain the above copyright\par * notice, this list of conditions and the following disclaimer. \par *\par * 2. Redistributions in binary form must reproduce the above copyright\par * notice, this list of conditions and the following disclaimer in\par * the documentation and/or other materials provided with the\par * distribution.\par *\par * 3. All advertising materials mentioning features or use of this\par * software must display the following acknowledgment:\par * "This product includes software developed by the OpenSSL Project\par * for use in the OpenSSL Toolkit. ({\cf0{\field{\*\fldinst{HYPERLINK http://www.openssl.org/ }}{\fldrslt{http://www.openssl.org/\ul0\cf0}}}}\f1\fs20 )"\par *\par * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to\par * endorse or promote products derived from this software without\par * prior written permission. For written permission, please contact\par * [email protected].\par *\par * 5. Products derived from this software may not be called "OpenSSL"\par * nor may "OpenSSL" appear in their names without prior written\par * permission of the OpenSSL Project.\par *\par * 6. Redistributions of any form whatsoever must retain the following\par * acknowledgment:\par * "This product includes software developed by the OpenSSL Project\par * for use in the OpenSSL Toolkit ({\cf0{\field{\*\fldinst{HYPERLINK http://www.openssl.org/ }}{\fldrslt{http://www.openssl.org/\ul0\cf0}}}}\f1\fs20 )"\par *\par * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY\par * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\par * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\par * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR\par * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\par * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\par * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\par * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\par * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\par * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\par * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\par * OF THE POSSIBILITY OF SUCH DAMAGE.\par * ====================================================================\par *\par * This product includes cryptographic software written by Eric Young\par * ([email protected]). This product includes software written by Tim\par * Hudson ([email protected]).\par *\par */\par \par Original SSLeay License\par -----------------------\par \par /* Copyright (C) 1995-1998 Eric Young ([email protected])\par * All rights reserved.\par *\par * This package is an SSL implementation written\par * by Eric Young ([email protected]).\par * The implementation was written so as to conform with Netscapes SSL.\par * \par * This library is free for commercial and non-commercial use as long as\par * the following conditions are aheared to. The following conditions\par * apply to all code found in this distribution, be it the RC4, RSA,\par * lhash, DES, etc., code; not just the SSL code. The SSL documentation\par * included with this distribution is covered by the same copyright terms\par * except that the holder is Tim Hudson ([email protected]).\par * \par * Copyright remains Eric Young's, and as such any Copyright notices in\par * the code are not to be removed.\par * If this package is used in a product, Eric Young should be given attribution\par * as the author of the parts of the library used.\par * This can be in the form of a textual message at program startup or\par * in documentation (online or textual) provided with the package.\par * \par * Redistribution and use in source and binary forms, with or without\par * modification, are permitted provided that the following conditions\par * are met:\par * 1. Redistributions of source code must retain the copyright\par * notice, this list of conditions and the following disclaimer.\par * 2. Redistributions in binary form must reproduce the above copyright\par * notice, this list of conditions and the following disclaimer in the\par * documentation and/or other materials provided with the distribution.\par * 3. All advertising materials mentioning features or use of this software\par * must display the following acknowledgement:\par * "This product includes cryptographic software written by\par * Eric Young ([email protected])"\par * The word 'cryptographic' can be left out if the rouines from the library\par * being used are not cryptographic related :-).\par * 4. If you include any Windows specific code (or a derivative thereof) from \par * the apps directory (application code) you must include an acknowledgement:\par * "This product includes software written by Tim Hudson ([email protected])"\par * \par * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND\par * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\par * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\par * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\par * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\par * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\par * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\par * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\par * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\par * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\par * SUCH DAMAGE.\par * \par * The licence and distribution terms for any publically available version or\par * derivative of this code cannot be changed. i.e. this code cannot simply be\par * copied and put under another distribution licence\par * [including the GNU Public Licence.]\par */\par \pard\nowidctlpar\cf0\f0\fs22 =========================================\par END OF SQLitePCLRaw.provider.e_sqlite3.net45 NOTICES AND INFORMATION\par \par %% SQLitePCLRaw.lib.e_sqlite3.v110_xp NOTICES AND INFORMATION BEGIN HERE\par =========================================\par Apache License\par Version 2.0, January 2004\par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/ }}{\fldrslt{http://www.apache.org/licenses/\ul0\cf0}}}}\f0\fs22\par \par TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\par \par 1. Definitions.\par \par "License" shall mean the terms and conditions for use, reproduction,\par and distribution as defined by Sections 1 through 9 of this document.\par \par "Licensor" shall mean the copyright owner or entity authorized by\par the copyright owner that is granting the License.\par \par "Legal Entity" shall mean the union of the acting entity and all\par other entities that control, are controlled by, or are under common\par control with that entity. For the purposes of this definition,\par "control" means (i) the power, direct or indirect, to cause the\par direction or management of such entity, whether by contract or\par otherwise, or (ii) ownership of fifty percent (50%) or more of the\par outstanding shares, or (iii) beneficial ownership of such entity.\par \par "You" (or "Your") shall mean an individual or Legal Entity\par exercising permissions granted by this License.\par \par "Source" form shall mean the preferred form for making modifications,\par including but not limited to software source code, documentation\par source, and configuration files.\par \par "Object" form shall mean any form resulting from mechanical\par transformation or translation of a Source form, including but\par not limited to compiled object code, generated documentation,\par and conversions to other media types.\par \par "Work" shall mean the work of authorship, whether in Source or\par Object form, made available under the License, as indicated by a\par copyright notice that is included in or attached to the work\par (an example is provided in the Appendix below).\par \par "Derivative Works" shall mean any work, whether in Source or Object\par form, that is based on (or derived from) the Work and for which the\par editorial revisions, annotations, elaborations, or other modifications\par represent, as a whole, an original work of authorship. For the purposes\par of this License, Derivative Works shall not include works that remain\par separable from, or merely link (or bind by name) to the interfaces of,\par the Work and Derivative Works thereof.\par \par "Contribution" shall mean any work of authorship, including\par the original version of the Work and any modifications or additions\par to that Work or Derivative Works thereof, that is intentionally\par submitted to Licensor for inclusion in the Work by the copyright owner\par or by an individual or Legal Entity authorized to submit on behalf of\par the copyright owner. For the purposes of this definition, "submitted"\par means any form of electronic, verbal, or written communication sent\par to the Licensor or its representatives, including but not limited to\par communication on electronic mailing lists, source code control systems,\par and issue tracking systems that are managed by, or on behalf of, the\par Licensor for the purpose of discussing and improving the Work, but\par excluding communication that is conspicuously marked or otherwise\par designated in writing by the copyright owner as "Not a Contribution."\par \par "Contributor" shall mean Licensor and any individual or Legal Entity\par on behalf of whom a Contribution has been received by Licensor and\par subsequently incorporated within the Work.\par \par 2. Grant of Copyright License. Subject to the terms and conditions of\par this License, each Contributor hereby grants to You a perpetual,\par worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par copyright license to reproduce, prepare Derivative Works of,\par publicly display, publicly perform, sublicense, and distribute the\par Work and such Derivative Works in Source or Object form.\par \par 3. Grant of Patent License. Subject to the terms and conditions of\par this License, each Contributor hereby grants to You a perpetual,\par worldwide, non-exclusive, no-charge, royalty-free, irrevocable\par (except as stated in this section) patent license to make, have made,\par use, offer to sell, sell, import, and otherwise transfer the Work,\par where such license applies only to those patent claims licensable\par by such Contributor that are necessarily infringed by their\par Contribution(s) alone or by combination of their Contribution(s)\par with the Work to which such Contribution(s) was submitted. If You\par institute patent litigation against any entity (including a\par cross-claim or counterclaim in a lawsuit) alleging that the Work\par or a Contribution incorporated within the Work constitutes direct\par or contributory patent infringement, then any patent licenses\par granted to You under this License for that Work shall terminate\par as of the date such litigation is filed.\par \par 4. Redistribution. You may reproduce and distribute copies of the\par Work or Derivative Works thereof in any medium, with or without\par modifications, and in Source or Object form, provided that You\par meet the following conditions:\par \par (a) You must give any other recipients of the Work or\par Derivative Works a copy of this License; and\par \par (b) You must cause any modified files to carry prominent notices\par stating that You changed the files; and\par \par (c) You must retain, in the Source form of any Derivative Works\par that You distribute, all copyright, patent, trademark, and\par attribution notices from the Source form of the Work,\par excluding those notices that do not pertain to any part of\par the Derivative Works; and\par \par (d) If the Work includes a "NOTICE" text file as part of its\par distribution, then any Derivative Works that You distribute must\par include a readable copy of the attribution notices contained\par within such NOTICE file, excluding those notices that do not\par pertain to any part of the Derivative Works, in at least one\par of the following places: within a NOTICE text file distributed\par as part of the Derivative Works; within the Source form or\par documentation, if provided along with the Derivative Works; or,\par within a display generated by the Derivative Works, if and\par wherever such third-party notices normally appear. The contents\par of the NOTICE file are for informational purposes only and\par do not modify the License. You may add Your own attribution\par notices within Derivative Works that You distribute, alongside\par or as an addendum to the NOTICE text from the Work, provided\par that such additional attribution notices cannot be construed\par as modifying the License.\par \par You may add Your own copyright statement to Your modifications and\par may provide additional or different license terms and conditions\par for use, reproduction, or distribution of Your modifications, or\par for any such Derivative Works as a whole, provided Your use,\par reproduction, and distribution of the Work otherwise complies with\par the conditions stated in this License.\par \par 5. Submission of Contributions. Unless You explicitly state otherwise,\par any Contribution intentionally submitted for inclusion in the Work\par by You to the Licensor shall be under the terms and conditions of\par this License, without any additional terms or conditions.\par Notwithstanding the above, nothing herein shall supersede or modify\par the terms of any separate license agreement you may have executed\par with Licensor regarding such Contributions.\par \par 6. Trademarks. This License does not grant permission to use the trade\par names, trademarks, service marks, or product names of the Licensor,\par except as required for reasonable and customary use in describing the\par origin of the Work and reproducing the content of the NOTICE file.\par \par 7. Disclaimer of Warranty. Unless required by applicable law or\par agreed to in writing, Licensor provides the Work (and each\par Contributor provides its Contributions) on an "AS IS" BASIS,\par WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\par implied, including, without limitation, any warranties or conditions\par of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\par PARTICULAR PURPOSE. You are solely responsible for determining the\par appropriateness of using or redistributing the Work and assume any\par risks associated with Your exercise of permissions under this License.\par \par 8. Limitation of Liability. In no event and under no legal theory,\par whether in tort (including negligence), contract, or otherwise,\par unless required by applicable law (such as deliberate and grossly\par negligent acts) or agreed to in writing, shall any Contributor be\par liable to You for damages, including any direct, indirect, special,\par incidental, or consequential damages of any character arising as a\par result of this License or out of the use or inability to use the\par Work (including but not limited to damages for loss of goodwill,\par work stoppage, computer failure or malfunction, or any and all\par other commercial damages or losses), even if such Contributor\par has been advised of the possibility of such damages.\par \par 9. Accepting Warranty or Additional Liability. While redistributing\par the Work or Derivative Works thereof, You may choose to offer,\par and charge a fee for, acceptance of support, warranty, indemnity,\par or other liability obligations and/or rights consistent with this\par License. However, in accepting such obligations, You may act only\par on Your own behalf and on Your sole responsibility, not on behalf\par of any other Contributor, and only if You agree to indemnify,\par defend, and hold each Contributor harmless for any liability\par incurred by, or claims asserted against, such Contributor by reason\par of your accepting any such warranty or additional liability.\par \par END OF TERMS AND CONDITIONS\par \par APPENDIX: How to apply the Apache License to your work.\par \par To apply the Apache License to your work, attach the following\par boilerplate notice, with the fields enclosed by brackets "[]"\par replaced with your own identifying information. (Don't include\par the brackets!) The text should be enclosed in the appropriate\par comment syntax for the file format. We also recommend that a\par file or class name and description of purpose be included on the\par same "printed page" as the copyright notice for easier\par identification within third-party archives.\par \par Copyright [yyyy] [name of copyright owner]\par \par Licensed under the Apache License, Version 2.0 (the "License");\par you may not use this file except in compliance with the License.\par You may obtain a copy of the License at\par \par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f0\fs22\par \par Unless required by applicable law or agreed to in writing, software\par distributed under the License is distributed on an "AS IS" BASIS,\par WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\par See the License for the specific language governing permissions and\par limitations under the License.\par \par \pard\widctlpar\tx916\tx1832\tx2748\tx3664\tx4580\tx5496\tx6412\tx7328\tx8244\tx9160\tx10076\tx10992\tx11908\tx12824\tx13740\tx14656\cf5\f1\fs20 ----------------------------------------------------------------\par Copyright on SQLitePCL.raw\par ----------------------------------------------------------------\par \par Version prior to 2.0 were labeled with the copyright owned by\par Zumero. In 2.0, this changed to SourceGear. There is no legal\par distinction, as Zumero is simply a dba name for SourceGear.\par \par And in either case, the open source license remains the same,\par Apache v2.\par \par ----------------------------------------------------------------\par License for SQLite\par ----------------------------------------------------------------\par \par ** The author disclaims copyright to this source code. In place of\par ** a legal notice, here is a blessing:\par **\par ** May you do good and not evil.\par ** May you find forgiveness for yourself and forgive others.\par ** May you share freely, never taking more than you give.\par **\par \par \par ----------------------------------------------------------------\par License for MS Open Tech\par ----------------------------------------------------------------\par \par // Copyright \'a9 Microsoft Open Technologies, Inc.\par // All Rights Reserved\par // Licensed under the Apache License, Version 2.0 (the "License"); you may not\par // use this file except in compliance with the License. You may obtain a copy\par // of the License at \par // {\cf0{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f1\fs20\par // \par // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\par // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY\par // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\par // MERCHANTABLITY OR NON-INFRINGEMENT.\par // \par // See the Apache 2 License for the specific language governing permissions and\par // limitations under the License.\par \par \par ----------------------------------------------------------------\par License for SQLCipher\par ----------------------------------------------------------------\par \par Copyright (c) 2008, ZETETIC LLC\par All rights reserved.\par \par Redistribution and use in source and binary forms, with or without\par modification, are permitted provided that the following conditions are met:\par * Redistributions of source code must retain the above copyright\par notice, this list of conditions and the following disclaimer.\par * Redistributions in binary form must reproduce the above copyright\par notice, this list of conditions and the following disclaimer in the\par documentation and/or other materials provided with the distribution.\par * Neither the name of the ZETETIC LLC nor the\par names of its contributors may be used to endorse or promote products\par derived from this software without specific prior written permission.\par \par THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY\par EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\par WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\par DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY\par DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\par (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\par LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\par ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\par (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\par SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\par \par \par ----------------------------------------------------------------\par License for OpenSSL libcrypto\par ----------------------------------------------------------------\par \par LICENSE ISSUES\par ==============\par \par The OpenSSL toolkit stays under a dual license, i.e. both the conditions of\par the OpenSSL License and the original SSLeay license apply to the toolkit.\par See below for the actual license texts. Actually both licenses are BSD-style\par Open Source licenses. In case of any license issues related to OpenSSL\par please contact [email protected].\par \par OpenSSL License\par ---------------\par \par /* ====================================================================\par * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved.\par *\par * Redistribution and use in source and binary forms, with or without\par * modification, are permitted provided that the following conditions\par * are met:\par *\par * 1. Redistributions of source code must retain the above copyright\par * notice, this list of conditions and the following disclaimer. \par *\par * 2. Redistributions in binary form must reproduce the above copyright\par * notice, this list of conditions and the following disclaimer in\par * the documentation and/or other materials provided with the\par * distribution.\par *\par * 3. All advertising materials mentioning features or use of this\par * software must display the following acknowledgment:\par * "This product includes software developed by the OpenSSL Project\par * for use in the OpenSSL Toolkit. ({\cf0{\field{\*\fldinst{HYPERLINK http://www.openssl.org/ }}{\fldrslt{http://www.openssl.org/\ul0\cf0}}}}\f1\fs20 )"\par *\par * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to\par * endorse or promote products derived from this software without\par * prior written permission. For written permission, please contact\par * [email protected].\par *\par * 5. Products derived from this software may not be called "OpenSSL"\par * nor may "OpenSSL" appear in their names without prior written\par * permission of the OpenSSL Project.\par *\par * 6. Redistributions of any form whatsoever must retain the following\par * acknowledgment:\par * "This product includes software developed by the OpenSSL Project\par * for use in the OpenSSL Toolkit ({\cf0{\field{\*\fldinst{HYPERLINK http://www.openssl.org/ }}{\fldrslt{http://www.openssl.org/\ul0\cf0}}}}\f1\fs20 )"\par *\par * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY\par * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\par * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\par * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR\par * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\par * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\par * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\par * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\par * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\par * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\par * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\par * OF THE POSSIBILITY OF SUCH DAMAGE.\par * ====================================================================\par *\par * This product includes cryptographic software written by Eric Young\par * ([email protected]). This product includes software written by Tim\par * Hudson ([email protected]).\par *\par */\par \par Original SSLeay License\par -----------------------\par \par /* Copyright (C) 1995-1998 Eric Young ([email protected])\par * All rights reserved.\par *\par * This package is an SSL implementation written\par * by Eric Young ([email protected]).\par * The implementation was written so as to conform with Netscapes SSL.\par * \par * This library is free for commercial and non-commercial use as long as\par * the following conditions are aheared to. The following conditions\par * apply to all code found in this distribution, be it the RC4, RSA,\par * lhash, DES, etc., code; not just the SSL code. The SSL documentation\par * included with this distribution is covered by the same copyright terms\par * except that the holder is Tim Hudson ([email protected]).\par * \par * Copyright remains Eric Young's, and as such any Copyright notices in\par * the code are not to be removed.\par * If this package is used in a product, Eric Young should be given attribution\par * as the author of the parts of the library used.\par * This can be in the form of a textual message at program startup or\par * in documentation (online or textual) provided with the package.\par * \par * Redistribution and use in source and binary forms, with or without\par * modification, are permitted provided that the following conditions\par * are met:\par * 1. Redistributions of source code must retain the copyright\par * notice, this list of conditions and the following disclaimer.\par * 2. Redistributions in binary form must reproduce the above copyright\par * notice, this list of conditions and the following disclaimer in the\par * documentation and/or other materials provided with the distribution.\par * 3. All advertising materials mentioning features or use of this software\par * must display the following acknowledgement:\par * "This product includes cryptographic software written by\par * Eric Young ([email protected])"\par * The word 'cryptographic' can be left out if the rouines from the library\par * being used are not cryptographic related :-).\par * 4. If you include any Windows specific code (or a derivative thereof) from \par * the apps directory (application code) you must include an acknowledgement:\par * "This product includes software written by Tim Hudson ([email protected])"\par * \par * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND\par * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\par * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\par * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\par * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\par * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\par * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\par * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\par * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\par * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\par * SUCH DAMAGE.\par * \par * The licence and distribution terms for any publically available version or\par * derivative of this code cannot be changed. i.e. this code cannot simply be\par * copied and put under another distribution licence\par * [including the GNU Public Licence.]\par */\par \pard\nowidctlpar\cf0\f0\fs22 =========================================\par END OF SQLitePCLRaw.lib.e_sqlite3.v110_xp NOTICES AND INFORMATION\par \pard\sa200\sl276\slmult1\f2\lang9\par }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Test/CodeCleanupExportTests.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.Test.Utilities Imports Microsoft.VisualStudio.Language.CodeCleanUp Imports Microsoft.VisualStudio.LanguageServices.FindUsages Imports Microsoft.VisualStudio.LanguageServices.UnitTests Namespace Tests <UseExportProvider> Public Class CodeCleanupExportTests <Fact> Public Sub TestUniqueFixId() Dim exportProvider = VisualStudioTestCompositions.LanguageServices.ExportProviderFactory.CreateExportProvider() Dim fixIdDefinitions = exportProvider.GetExports(Of FixIdDefinition, NameMetadata)() Dim groups = fixIdDefinitions.GroupBy(Function(x) x.Metadata.Name).Where(Function(x) x.Count() > 1) Assert.Empty(groups.Select(Function(group) group.Select(Function(part) part.Metadata.Name))) 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.Test.Utilities Imports Microsoft.VisualStudio.Language.CodeCleanUp Imports Microsoft.VisualStudio.LanguageServices.FindUsages Imports Microsoft.VisualStudio.LanguageServices.UnitTests Namespace Tests <UseExportProvider> Public Class CodeCleanupExportTests <Fact> Public Sub TestUniqueFixId() Dim exportProvider = VisualStudioTestCompositions.LanguageServices.ExportProviderFactory.CreateExportProvider() Dim fixIdDefinitions = exportProvider.GetExports(Of FixIdDefinition, NameMetadata)() Dim groups = fixIdDefinitions.GroupBy(Function(x) x.Metadata.Name).Where(Function(x) x.Count() > 1) Assert.Empty(groups.Select(Function(group) group.Select(Function(part) part.Metadata.Name))) End Sub End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/Lsif/Generator/Writing/LsifFormat.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing { internal enum LsifFormat { /// <summary> /// Line format, where each line is a JSON object. /// </summary> Line, /// <summary> /// JSON format, where the entire output is a single JSON array. /// </summary> Json } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing { internal enum LsifFormat { /// <summary> /// Line format, where each line is a JSON object. /// </summary> Line, /// <summary> /// JSON format, where the entire output is a single JSON array. /// </summary> Json } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/vbc/vbc.rsp
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the MIT license. # See the LICENSE file in the project root for more information. # This file contains command-line options that the VB # command line compiler (VBC) will process as part # of every compilation, unless the "/noconfig" option # is specified. # Reference the common Framework libraries /r:Accessibility.dll /r:System.Configuration.dll /r:System.Configuration.Install.dll /r:System.Data.dll /r:System.Data.OracleClient.dll /r:System.Deployment.dll /r:System.Design.dll /r:System.DirectoryServices.dll /r:System.dll /r:System.Drawing.Design.dll /r:System.Drawing.dll /r:System.EnterpriseServices.dll /r:System.Management.dll /r:System.Messaging.dll /r:System.Runtime.Remoting.dll /r:System.Runtime.Serialization.Formatters.Soap.dll /r:System.Security.dll /r:System.ServiceProcess.dll /r:System.Transactions.dll /r:System.Web.dll /r:System.Web.Mobile.dll /r:System.Web.RegularExpressions.dll /r:System.Web.Services.dll /r:System.Windows.Forms.dll /r:System.Xml.dll /r:System.Workflow.Activities.dll /r:System.Workflow.ComponentModel.dll /r:System.Workflow.Runtime.dll /r:System.Runtime.Serialization.dll /r:System.ServiceModel.dll /r:System.Core.dll /r:System.Xml.Linq.dll /r:System.Data.Linq.dll /r:System.Data.DataSetExtensions.dll /r:System.Web.Extensions.dll /r:System.Web.Extensions.Design.dll /r:System.ServiceModel.Web.dll # Import System and Microsoft.VisualBasic /imports:System /imports:Microsoft.VisualBasic /imports:System.Linq /imports:System.Xml.Linq /optioninfer+
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the MIT license. # See the LICENSE file in the project root for more information. # This file contains command-line options that the VB # command line compiler (VBC) will process as part # of every compilation, unless the "/noconfig" option # is specified. # Reference the common Framework libraries /r:Accessibility.dll /r:System.Configuration.dll /r:System.Configuration.Install.dll /r:System.Data.dll /r:System.Data.OracleClient.dll /r:System.Deployment.dll /r:System.Design.dll /r:System.DirectoryServices.dll /r:System.dll /r:System.Drawing.Design.dll /r:System.Drawing.dll /r:System.EnterpriseServices.dll /r:System.Management.dll /r:System.Messaging.dll /r:System.Runtime.Remoting.dll /r:System.Runtime.Serialization.Formatters.Soap.dll /r:System.Security.dll /r:System.ServiceProcess.dll /r:System.Transactions.dll /r:System.Web.dll /r:System.Web.Mobile.dll /r:System.Web.RegularExpressions.dll /r:System.Web.Services.dll /r:System.Windows.Forms.dll /r:System.Xml.dll /r:System.Workflow.Activities.dll /r:System.Workflow.ComponentModel.dll /r:System.Workflow.Runtime.dll /r:System.Runtime.Serialization.dll /r:System.ServiceModel.dll /r:System.Core.dll /r:System.Xml.Linq.dll /r:System.Data.Linq.dll /r:System.Data.DataSetExtensions.dll /r:System.Web.Extensions.dll /r:System.Web.Extensions.Design.dll /r:System.ServiceModel.Web.dll # Import System and Microsoft.VisualBasic /imports:System /imports:Microsoft.VisualBasic /imports:System.Linq /imports:System.Xml.Linq /optioninfer+
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Rebuild/CompilationFactory.cs
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Rebuild { public abstract class CompilationFactory { public string AssemblyFileName { get; } public CompilationOptionsReader OptionsReader { get; } public ParseOptions ParseOptions => CommonParseOptions; public CompilationOptions CompilationOptions => CommonCompilationOptions; protected abstract ParseOptions CommonParseOptions { get; } protected abstract CompilationOptions CommonCompilationOptions { get; } protected CompilationFactory(string assemblyFileName, CompilationOptionsReader optionsReader) { AssemblyFileName = assemblyFileName; OptionsReader = optionsReader; } public static CompilationFactory Create(string assemblyFileName, CompilationOptionsReader optionsReader) => optionsReader.GetLanguageName() switch { LanguageNames.CSharp => CSharpCompilationFactory.Create(assemblyFileName, optionsReader), LanguageNames.VisualBasic => VisualBasicCompilationFactory.Create(assemblyFileName, optionsReader), var language => throw new InvalidDataException($"{assemblyFileName} has unsupported language {language}") }; public abstract SyntaxTree CreateSyntaxTree(string filePath, SourceText sourceText); public Compilation CreateCompilation(IRebuildArtifactResolver resolver) { var tuple = OptionsReader.ResolveArtifacts(resolver, CreateSyntaxTree); return CreateCompilation(tuple.SyntaxTrees, tuple.MetadataReferences); } public abstract Compilation CreateCompilation( ImmutableArray<SyntaxTree> syntaxTrees, ImmutableArray<MetadataReference> metadataReferences); public EmitResult Emit( Stream rebuildPeStream, Stream? rebuildPdbStream, IRebuildArtifactResolver rebuildArtifactResolver, CancellationToken cancellationToken) => Emit( rebuildPeStream, rebuildPdbStream, CreateCompilation(rebuildArtifactResolver), cancellationToken); public EmitResult Emit( Stream rebuildPeStream, Stream? rebuildPdbStream, ImmutableArray<SyntaxTree> syntaxTrees, ImmutableArray<MetadataReference> metadataReferences, CancellationToken cancellationToken) => Emit( rebuildPeStream, rebuildPdbStream, CreateCompilation(syntaxTrees, metadataReferences), cancellationToken); public EmitResult Emit( Stream rebuildPeStream, Stream? rebuildPdbStream, Compilation rebuildCompilation, CancellationToken cancellationToken) { var embeddedTexts = rebuildCompilation.SyntaxTrees .Select(st => (path: st.FilePath, text: st.GetText())) .Where(pair => pair.text.CanBeEmbedded) .Select(pair => EmbeddedText.FromSource(pair.path, pair.text)) .ToImmutableArray(); return Emit( rebuildPeStream, rebuildPdbStream, rebuildCompilation, embeddedTexts, cancellationToken); } public unsafe EmitResult Emit( Stream rebuildPeStream, Stream? rebuildPdbStream, Compilation rebuildCompilation, ImmutableArray<EmbeddedText> embeddedTexts, CancellationToken cancellationToken) { var peHeader = OptionsReader.PeReader.PEHeaders.PEHeader!; var win32Resources = OptionsReader.PeReader.GetSectionData(peHeader.ResourceTableDirectory.RelativeVirtualAddress); using var win32ResourceStream = win32Resources.Pointer != null ? new UnmanagedMemoryStream(win32Resources.Pointer, win32Resources.Length) : null; var sourceLink = OptionsReader.GetSourceLinkUtf8(); var debugEntryPoint = getDebugEntryPoint(); string? pdbFilePath; DebugInformationFormat debugInformationFormat; if (OptionsReader.HasEmbeddedPdb) { if (rebuildPdbStream is object) { throw new ArgumentException(RebuildResources.PDB_stream_must_be_null_because_the_compilation_has_an_embedded_PDB, nameof(rebuildPdbStream)); } debugInformationFormat = DebugInformationFormat.Embedded; pdbFilePath = null; } else { if (rebuildPdbStream is null) { throw new ArgumentException(RebuildResources.A_non_null_PDB_stream_must_be_provided_because_the_compilation_does_not_have_an_embedded_PDB, nameof(rebuildPdbStream)); } debugInformationFormat = DebugInformationFormat.PortablePdb; var codeViewEntry = OptionsReader.PeReader.ReadDebugDirectory().Single(entry => entry.Type == DebugDirectoryEntryType.CodeView); var codeView = OptionsReader.PeReader.ReadCodeViewDebugDirectoryData(codeViewEntry); pdbFilePath = codeView.Path ?? throw new InvalidOperationException(RebuildResources.Could_not_get_PDB_file_path); } var rebuildData = new RebuildData( OptionsReader.GetMetadataCompilationOptionsBlobReader(), getNonSourceFileDocumentNames(OptionsReader.PdbReader, OptionsReader.GetSourceFileCount())); var emitResult = rebuildCompilation.Emit( peStream: rebuildPeStream, pdbStream: rebuildPdbStream, xmlDocumentationStream: null, win32Resources: win32ResourceStream, manifestResources: OptionsReader.GetManifestResources(), options: new EmitOptions( debugInformationFormat: debugInformationFormat, pdbFilePath: pdbFilePath, highEntropyVirtualAddressSpace: (peHeader.DllCharacteristics & DllCharacteristics.HighEntropyVirtualAddressSpace) != 0, subsystemVersion: SubsystemVersion.Create(peHeader.MajorSubsystemVersion, peHeader.MinorSubsystemVersion)), debugEntryPoint: debugEntryPoint, metadataPEStream: null, rebuildData: rebuildData, sourceLinkStream: sourceLink != null ? new MemoryStream(sourceLink) : null, embeddedTexts: embeddedTexts, cancellationToken: cancellationToken); return emitResult; static ImmutableArray<string> getNonSourceFileDocumentNames(MetadataReader pdbReader, int sourceFileCount) { var count = pdbReader.Documents.Count - sourceFileCount; var builder = ArrayBuilder<string>.GetInstance(count); foreach (var documentHandle in pdbReader.Documents.Skip(sourceFileCount)) { var document = pdbReader.GetDocument(documentHandle); var name = pdbReader.GetString(document.Name); builder.Add(name); } return builder.ToImmutableAndFree(); } IMethodSymbol? getDebugEntryPoint() { if (OptionsReader.GetMainMethodInfo() is (string mainTypeName, string mainMethodName)) { var typeSymbol = rebuildCompilation.GetTypeByMetadataName(mainTypeName); if (typeSymbol is object) { var methodSymbols = typeSymbol .GetMembers(mainMethodName) .OfType<IMethodSymbol>(); return methodSymbols.FirstOrDefault(); } } return null; } } protected static (OptimizationLevel OptimizationLevel, bool DebugPlus) GetOptimizationLevel(string? value) { if (value is null) { return OptimizationLevelFacts.DefaultValues; } if (!OptimizationLevelFacts.TryParsePdbSerializedString(value, out OptimizationLevel optimizationLevel, out bool debugPlus)) { throw new InvalidOperationException(); } return (optimizationLevel, debugPlus); } protected static Platform GetPlatform(string? platform) => platform is null ? Platform.AnyCpu : (Platform)Enum.Parse(typeof(Platform), platform); } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Rebuild { public abstract class CompilationFactory { public string AssemblyFileName { get; } public CompilationOptionsReader OptionsReader { get; } public ParseOptions ParseOptions => CommonParseOptions; public CompilationOptions CompilationOptions => CommonCompilationOptions; protected abstract ParseOptions CommonParseOptions { get; } protected abstract CompilationOptions CommonCompilationOptions { get; } protected CompilationFactory(string assemblyFileName, CompilationOptionsReader optionsReader) { AssemblyFileName = assemblyFileName; OptionsReader = optionsReader; } public static CompilationFactory Create(string assemblyFileName, CompilationOptionsReader optionsReader) => optionsReader.GetLanguageName() switch { LanguageNames.CSharp => CSharpCompilationFactory.Create(assemblyFileName, optionsReader), LanguageNames.VisualBasic => VisualBasicCompilationFactory.Create(assemblyFileName, optionsReader), var language => throw new InvalidDataException($"{assemblyFileName} has unsupported language {language}") }; public abstract SyntaxTree CreateSyntaxTree(string filePath, SourceText sourceText); public Compilation CreateCompilation(IRebuildArtifactResolver resolver) { var tuple = OptionsReader.ResolveArtifacts(resolver, CreateSyntaxTree); return CreateCompilation(tuple.SyntaxTrees, tuple.MetadataReferences); } public abstract Compilation CreateCompilation( ImmutableArray<SyntaxTree> syntaxTrees, ImmutableArray<MetadataReference> metadataReferences); public EmitResult Emit( Stream rebuildPeStream, Stream? rebuildPdbStream, IRebuildArtifactResolver rebuildArtifactResolver, CancellationToken cancellationToken) => Emit( rebuildPeStream, rebuildPdbStream, CreateCompilation(rebuildArtifactResolver), cancellationToken); public EmitResult Emit( Stream rebuildPeStream, Stream? rebuildPdbStream, ImmutableArray<SyntaxTree> syntaxTrees, ImmutableArray<MetadataReference> metadataReferences, CancellationToken cancellationToken) => Emit( rebuildPeStream, rebuildPdbStream, CreateCompilation(syntaxTrees, metadataReferences), cancellationToken); public EmitResult Emit( Stream rebuildPeStream, Stream? rebuildPdbStream, Compilation rebuildCompilation, CancellationToken cancellationToken) { var embeddedTexts = rebuildCompilation.SyntaxTrees .Select(st => (path: st.FilePath, text: st.GetText())) .Where(pair => pair.text.CanBeEmbedded) .Select(pair => EmbeddedText.FromSource(pair.path, pair.text)) .ToImmutableArray(); return Emit( rebuildPeStream, rebuildPdbStream, rebuildCompilation, embeddedTexts, cancellationToken); } public unsafe EmitResult Emit( Stream rebuildPeStream, Stream? rebuildPdbStream, Compilation rebuildCompilation, ImmutableArray<EmbeddedText> embeddedTexts, CancellationToken cancellationToken) { var peHeader = OptionsReader.PeReader.PEHeaders.PEHeader!; var win32Resources = OptionsReader.PeReader.GetSectionData(peHeader.ResourceTableDirectory.RelativeVirtualAddress); using var win32ResourceStream = win32Resources.Pointer != null ? new UnmanagedMemoryStream(win32Resources.Pointer, win32Resources.Length) : null; var sourceLink = OptionsReader.GetSourceLinkUtf8(); var debugEntryPoint = getDebugEntryPoint(); string? pdbFilePath; DebugInformationFormat debugInformationFormat; if (OptionsReader.HasEmbeddedPdb) { if (rebuildPdbStream is object) { throw new ArgumentException(RebuildResources.PDB_stream_must_be_null_because_the_compilation_has_an_embedded_PDB, nameof(rebuildPdbStream)); } debugInformationFormat = DebugInformationFormat.Embedded; pdbFilePath = null; } else { if (rebuildPdbStream is null) { throw new ArgumentException(RebuildResources.A_non_null_PDB_stream_must_be_provided_because_the_compilation_does_not_have_an_embedded_PDB, nameof(rebuildPdbStream)); } debugInformationFormat = DebugInformationFormat.PortablePdb; var codeViewEntry = OptionsReader.PeReader.ReadDebugDirectory().Single(entry => entry.Type == DebugDirectoryEntryType.CodeView); var codeView = OptionsReader.PeReader.ReadCodeViewDebugDirectoryData(codeViewEntry); pdbFilePath = codeView.Path ?? throw new InvalidOperationException(RebuildResources.Could_not_get_PDB_file_path); } var rebuildData = new RebuildData( OptionsReader.GetMetadataCompilationOptionsBlobReader(), getNonSourceFileDocumentNames(OptionsReader.PdbReader, OptionsReader.GetSourceFileCount())); var emitResult = rebuildCompilation.Emit( peStream: rebuildPeStream, pdbStream: rebuildPdbStream, xmlDocumentationStream: null, win32Resources: win32ResourceStream, manifestResources: OptionsReader.GetManifestResources(), options: new EmitOptions( debugInformationFormat: debugInformationFormat, pdbFilePath: pdbFilePath, highEntropyVirtualAddressSpace: (peHeader.DllCharacteristics & DllCharacteristics.HighEntropyVirtualAddressSpace) != 0, subsystemVersion: SubsystemVersion.Create(peHeader.MajorSubsystemVersion, peHeader.MinorSubsystemVersion)), debugEntryPoint: debugEntryPoint, metadataPEStream: null, rebuildData: rebuildData, sourceLinkStream: sourceLink != null ? new MemoryStream(sourceLink) : null, embeddedTexts: embeddedTexts, cancellationToken: cancellationToken); return emitResult; static ImmutableArray<string> getNonSourceFileDocumentNames(MetadataReader pdbReader, int sourceFileCount) { var count = pdbReader.Documents.Count - sourceFileCount; var builder = ArrayBuilder<string>.GetInstance(count); foreach (var documentHandle in pdbReader.Documents.Skip(sourceFileCount)) { var document = pdbReader.GetDocument(documentHandle); var name = pdbReader.GetString(document.Name); builder.Add(name); } return builder.ToImmutableAndFree(); } IMethodSymbol? getDebugEntryPoint() { if (OptionsReader.GetMainMethodInfo() is (string mainTypeName, string mainMethodName)) { var typeSymbol = rebuildCompilation.GetTypeByMetadataName(mainTypeName); if (typeSymbol is object) { var methodSymbols = typeSymbol .GetMembers(mainMethodName) .OfType<IMethodSymbol>(); return methodSymbols.FirstOrDefault(); } } return null; } } protected static (OptimizationLevel OptimizationLevel, bool DebugPlus) GetOptimizationLevel(string? value) { if (value is null) { return OptimizationLevelFacts.DefaultValues; } if (!OptimizationLevelFacts.TryParsePdbSerializedString(value, out OptimizationLevel optimizationLevel, out bool debugPlus)) { throw new InvalidOperationException(); } return (optimizationLevel, debugPlus); } protected static Platform GetPlatform(string? platform) => platform is null ? Platform.AnyCpu : (Platform)Enum.Parse(typeof(Platform), platform); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/VisualBasic/EndConstructGeneration/VisualBasicEndConstructGenerationService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Implementation.EndConstructGeneration Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Internal.Log Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods Imports Microsoft.VisualStudio.Text.Operations Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration <ExportLanguageService(GetType(IEndConstructGenerationService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicEndConstructService Implements IEndConstructGenerationService Private ReadOnly _smartIndentationService As ISmartIndentationService Private ReadOnly _undoHistoryRegistry As ITextUndoHistoryRegistry Private ReadOnly _editorOperationsFactoryService As IEditorOperationsFactoryService Private ReadOnly _editorOptionsFactoryService As IEditorOptionsFactoryService <ImportingConstructor()> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New( smartIndentationService As ISmartIndentationService, undoHistoryRegistry As ITextUndoHistoryRegistry, editorOperationsFactoryService As IEditorOperationsFactoryService, editorOptionsFactoryService As IEditorOptionsFactoryService) ThrowIfNull(smartIndentationService) ThrowIfNull(undoHistoryRegistry) ThrowIfNull(editorOperationsFactoryService) ThrowIfNull(editorOptionsFactoryService) _smartIndentationService = smartIndentationService _undoHistoryRegistry = undoHistoryRegistry _editorOperationsFactoryService = editorOperationsFactoryService _editorOptionsFactoryService = editorOptionsFactoryService End Sub Private Shared Function IsMissingStatementError(statement As SyntaxNode, [error] As String) As Boolean Select Case [error] ' TODO(jasonmal): get rid of this. It is an open design goal to move missing end errors from the ' statement to the block. Besides making incremental parsing easier, it will also clean this mess up. ' Until then, I'm content with this hack. Case "BC30012" ' Missing #End If Return True Case "BC30481" ' Missing End Class Return True Case "BC30625" ' Missing End Module Return True Case "BC30185" ' Missing End Enum Return True Case "BC30253" ' Missing End Interface Return True Case "BC30624" ' Missing End Structure Return True Case "BC30626" ' Missing End Namespace Return True Case "BC30026" ' Missing End Sub Return True Case "BC30027" ' Missing End Function Return True Case "BC30631" ' Missing End Get Return True Case "BC30633" ' Missing End Set Return True Case "BC30025" ' Missing End Property Return True Case "BC30081" ' Missing End If Return True Case "BC30082" ' Missing End While Return True Case "BC30083" ' Missing Loop Return True Case "BC30084" ' Missing Next Return True Case "BC30085" ' Missing End With Return True Case "BC30095" ' Missing End Select Return True Case "BC36008" ' Missing End Using Return True Case "BC30675" ' Missing End SyncLock Return True Case "BC30681" ' Missing #End Region Return True Case "BC33005" ' Missing End Operator Return True Case "BC36759" ' Auto-implemented properties cannot have parameters Return True Case "BC36673" ' Missing End Sub for Lambda Return True Case "BC36674" ' Missing End Function for Lambda Return True Case "BC30384" ' Missing End Try Return True Case "BC30198", "BC30199" ' These happen if I type Dim x = Function without parenthesis, so as long as we are in that content, ' count this as an acceptable error. Return TypeOf statement Is LambdaHeaderSyntax Case "BC31114" ' Missing End Event Return True End Select Return False End Function Private Shared Function IsExpectedXmlNameError([error] As String) As Boolean Return [error] = "BC31146" End Function Private Shared Function IsMissingXmlEndTagError([error] As String) As Boolean Return [error] = "BC31151" End Function Private Shared Function IsExpectedXmlEndEmbeddedError([error] As String) As Boolean Return [error] = "BC31159" End Function Private Shared Function IsExpectedXmlEndPIError([error] As String) As Boolean Return [error] = "BC31160" End Function Private Shared Function IsExpectedXmlEndCommentError([error] As String) As Boolean Return [error] = "BC31161" End Function Private Shared Function IsExpectedXmlEndCDataError([error] As String) As Boolean Return [error] = "BC31162" End Function Private Function GetEndConstructState(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As EndConstructState Dim caretPosition = textView.GetCaretPoint(subjectBuffer) If caretPosition Is Nothing Then Return Nothing End If Dim document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges() If document Is Nothing Then Return Nothing End If Dim tree = document.GetSyntaxTreeSynchronously(cancellationToken) Dim tokenToLeft = tree.FindTokenOnLeftOfPosition(caretPosition.Value, cancellationToken, includeDirectives:=True, includeDocumentationComments:=True) If tokenToLeft.Kind = SyntaxKind.None Then Return Nothing End If Dim bufferOptions = _editorOptionsFactoryService.GetOptions(subjectBuffer) Return New EndConstructState( caretPosition.Value, New Lazy(Of SemanticModel)(Function() document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken)), tree, tokenToLeft, bufferOptions.GetNewLineCharacter()) End Function Friend Overridable Function TryDoEndConstructForEnterKey(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_DoStatement, cancellationToken) Using transaction = New CaretPreservingEditTransaction(VBEditorResources.End_Construct, textView, _undoHistoryRegistry, _editorOperationsFactoryService) transaction.MergePolicy = AutomaticCodeChangeMergePolicy.Instance ' The user may have some text selected. In this scenario, we want to guarantee ' two things: ' ' 1) the text that was selected is deleted, as a normal pressing of an enter key ' would do. Since we're not letting the editor do it's own thing during end ' construct generation, we need to make sure the selection is deleted. ' 2) that we compute what statements we should spit assuming the selected text ' is no longer there. Consider a scenario where the user has something like: ' ' If True Then ~~~~ ' ' and the completely invalid "~~~~" is selected. In VS2010, if you pressed ' enter, we would still spit enter, since we effectively view that code as ' "no longer there." ' ' The fix is simple: as a part of our transaction, we'll just delete anything ' under our selection. As long as our transaction goes through, the user won't ' suspect anything was fishy. If we don't spit, we'll cancel the transaction ' which will roll back this edit. _editorOperationsFactoryService.GetEditorOperations(textView).ReplaceSelection("") Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If ' Are we in the middle of XML tags? If state.TokenToLeft.Kind = SyntaxKind.GreaterThanToken Then Dim element = state.TokenToLeft.GetAncestor(Of XmlElementSyntax) If element IsNot Nothing Then If element.StartTag IsNot Nothing AndAlso element.StartTag.Span.End = state.CaretPosition AndAlso element.EndTag IsNot Nothing AndAlso element.EndTag.SpanStart = state.CaretPosition Then InsertBlankLineBetweenXmlTags(state, textView, subjectBuffer) transaction.Complete() Return True End If End If End If ' Figure out which statement that is to the left of us Dim statement = state.TokenToLeft.FirstAncestorOrSelf(Function(n) TypeOf n Is StatementSyntax OrElse TypeOf n Is DirectiveTriviaSyntax) ' Make sure we are after the last token of the statement or ' if the statement is a single-line If statement that ' we're after the "Then" or "Else" token. If statement Is Nothing Then Return False ElseIf statement.Kind = SyntaxKind.SingleLineIfStatement Then Dim asSingleLine = DirectCast(statement, SingleLineIfStatementSyntax) If state.TokenToLeft <> asSingleLine.ThenKeyword AndAlso (asSingleLine.ElseClause Is Nothing OrElse state.TokenToLeft <> asSingleLine.ElseClause.ElseKeyword) Then Return False End If ElseIf statement.GetLastToken() <> state.TokenToLeft Then Return False End If ' Make sure we were on the same line as the last token. Dim caretLine = subjectBuffer.CurrentSnapshot.GetLineNumberFromPosition(state.CaretPosition) Dim lineOfLastToken = subjectBuffer.CurrentSnapshot.GetLineNumberFromPosition(state.TokenToLeft.SpanStart) If caretLine <> lineOfLastToken Then Return False End If ' Make sure that we don't have any skipped trivia between our target token and ' the end of the line Dim nextToken = state.TokenToLeft.GetNextTokenOrEndOfFile() Dim nextTokenLine = subjectBuffer.CurrentSnapshot.GetLineNumberFromPosition(nextToken.SpanStart) If nextToken.IsKind(SyntaxKind.EndOfFileToken) AndAlso nextTokenLine = caretLine Then If nextToken.LeadingTrivia.Any(Function(trivia) trivia.IsKind(SyntaxKind.SkippedTokensTrivia)) Then Return False End If End If ' If this is an Imports or Implements declaration, we should use the enclosing type declaration. If TypeOf statement Is InheritsOrImplementsStatementSyntax Then Dim baseDeclaration = DirectCast(statement, InheritsOrImplementsStatementSyntax) Dim typeBlock = baseDeclaration.GetAncestor(Of TypeBlockSyntax)() If typeBlock Is Nothing Then Return False End If statement = typeBlock.BlockStatement End If If statement Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(statement) If errors.Any(Function(e) Not IsMissingStatementError(statement, e.Id)) Then If statement.Kind = SyntaxKind.SingleLineIfStatement Then Dim asSingleLine = DirectCast(statement, SingleLineIfStatementSyntax) Dim span = TextSpan.FromBounds(asSingleLine.IfKeyword.SpanStart, asSingleLine.ThenKeyword.Span.End) If errors.Any(Function(e) span.Contains(e.Location.SourceSpan)) Then Return False End If Else Return False End If End If ' Make sure this statement does not end with the line continuation character If statement.GetLastToken(includeZeroWidth:=True).TrailingTrivia.Any(Function(t) t.Kind = SyntaxKind.LineContinuationTrivia) Then Return False End If Dim visitor = New EndConstructStatementVisitor(textView, subjectBuffer, state, cancellationToken) Dim result = visitor.Visit(statement) If result Is Nothing Then Return False End If result.Apply(textView, subjectBuffer, state.CaretPosition, _smartIndentationService, _undoHistoryRegistry, _editorOperationsFactoryService) transaction.Complete() End Using End Using Return True End Function Private Sub InsertBlankLineBetweenXmlTags(state As EndConstructState, textView As ITextView, subjectBuffer As ITextBuffer) ' Add an extra newline first Using edit = subjectBuffer.CreateEdit() Dim aligningWhitespace = subjectBuffer.CurrentSnapshot.GetAligningWhitespace(state.TokenToLeft.Parent.Span.Start) edit.Insert(state.CaretPosition, state.NewLineCharacter + aligningWhitespace) edit.ApplyAndLogExceptions() End Using ' And now just send down a normal enter textView.TryMoveCaretToAndEnsureVisible(New SnapshotPoint(subjectBuffer.CurrentSnapshot, state.CaretPosition)) _editorOperationsFactoryService.GetEditorOperations(textView).InsertNewLine() End Sub Private Shared Function GetNodeFromToken(Of T As SyntaxNode)(token As SyntaxToken, expectedKind As SyntaxKind) As T If token.Kind <> expectedKind Then Return Nothing End If Return TryCast(token.Parent, T) End Function Private Shared Function InsertEndTextAndUpdateCaretPosition( view As ITextView, subjectBuffer As ITextBuffer, insertPosition As Integer, caretPosition As Integer, endText As String ) As Boolean Dim document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges() If document Is Nothing Then Return False End If subjectBuffer.ApplyChange(New TextChange(New TextSpan(insertPosition, 0), endText)) Dim caretPosAfterEdit = New SnapshotPoint(subjectBuffer.CurrentSnapshot, caretPosition) view.TryMoveCaretToAndEnsureVisible(caretPosAfterEdit) Return True End Function Friend Function TryDoXmlCDataEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlCData, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlCData = GetNodeFromToken(Of XmlCDataSectionSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.BeginCDataToken) If xmlCData Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlCData) ' Exactly one error is expected: ERRID_ExpectedXmlEndCData If errors.Count <> 1 Then Return False End If If Not IsExpectedXmlEndCDataError(errors(0).Id) Then Return False End If Dim endText = "]]>" Return InsertEndTextAndUpdateCaretPosition(textView, subjectBuffer, state.CaretPosition, state.TokenToLeft.Span.End, endText) End Using End Function Friend Function TryDoXmlCommentEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlComment, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlComment = GetNodeFromToken(Of XmlCommentSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.LessThanExclamationMinusMinusToken) If xmlComment Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlComment) ' Exactly one error is expected: ERRID_ExpectedXmlEndComment If errors.Count <> 1 Then Return False End If If Not IsExpectedXmlEndCommentError(errors(0).Id) Then Return False End If Dim endText = "-->" Return InsertEndTextAndUpdateCaretPosition(textView, subjectBuffer, state.CaretPosition, state.TokenToLeft.Span.End, endText) End Using End Function Friend Function TryDoXmlElementEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlElement, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlStartElement = GetNodeFromToken(Of XmlElementStartTagSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.GreaterThanToken) If xmlStartElement Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlStartElement) ' Exactly one error is expected: ERRID_MissingXmlEndTag If errors.Count <> 1 Then Return False End If If Not IsMissingXmlEndTagError(errors(0).Id) Then Return False End If Dim endTagText = "</" & xmlStartElement.Name.ToString & ">" Return InsertEndTextAndUpdateCaretPosition(textView, subjectBuffer, state.CaretPosition, state.TokenToLeft.Span.End, endTagText) End Using End Function Friend Function TryDoXmlEmbeddedExpressionEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlEmbeddedExpression, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlEmbeddedExpression = GetNodeFromToken(Of XmlEmbeddedExpressionSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.LessThanPercentEqualsToken) If xmlEmbeddedExpression Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlEmbeddedExpression) ' Errors should contain ERRID_ExpectedXmlEndEmbedded If Not errors.Any(Function(e) IsExpectedXmlEndEmbeddedError(e.Id)) Then Return False End If Dim endText = " %>" ' NOTE: two spaces are inserted. The caret will be moved between them Return InsertEndTextAndUpdateCaretPosition(textView, subjectBuffer, state.CaretPosition, state.TokenToLeft.Span.End + 1, endText) End Using End Function Friend Function TryDoXmlProcessingInstructionEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlProcessingInstruction, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlProcessingInstruction = GetNodeFromToken(Of XmlProcessingInstructionSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.LessThanQuestionToken) If xmlProcessingInstruction Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlProcessingInstruction) ' Exactly two errors are expected: ERRID_ExpectedXmlName and ERRID_ExpectedXmlEndPI If errors.Count <> 2 Then Return False End If If Not (errors.Any(Function(e) IsExpectedXmlNameError(e.Id)) AndAlso errors.Any(Function(e) IsExpectedXmlEndPIError(e.Id))) Then Return False End If Dim endText = "?>" Return InsertEndTextAndUpdateCaretPosition(textView, subjectBuffer, state.CaretPosition, state.TokenToLeft.Span.End, endText) End Using End Function Public Function TryDo(textView As ITextView, subjectBuffer As ITextBuffer, typedChar As Char, cancellationToken As CancellationToken) As Boolean Implements IEndConstructGenerationService.TryDo Select Case typedChar Case vbLf(0) Return Me.TryDoEndConstructForEnterKey(textView, subjectBuffer, cancellationToken) Case ">"c Return Me.TryDoXmlElementEndConstruct(textView, subjectBuffer, cancellationToken) Case "-"c Return Me.TryDoXmlCommentEndConstruct(textView, subjectBuffer, cancellationToken) Case "="c Return Me.TryDoXmlEmbeddedExpressionEndConstruct(textView, subjectBuffer, cancellationToken) Case "["c Return Me.TryDoXmlCDataEndConstruct(textView, subjectBuffer, cancellationToken) Case "?"c Return Me.TryDoXmlProcessingInstructionEndConstruct(textView, subjectBuffer, cancellationToken) End Select Return False End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Implementation.EndConstructGeneration Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Internal.Log Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods Imports Microsoft.VisualStudio.Text.Operations Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration <ExportLanguageService(GetType(IEndConstructGenerationService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicEndConstructService Implements IEndConstructGenerationService Private ReadOnly _smartIndentationService As ISmartIndentationService Private ReadOnly _undoHistoryRegistry As ITextUndoHistoryRegistry Private ReadOnly _editorOperationsFactoryService As IEditorOperationsFactoryService Private ReadOnly _editorOptionsFactoryService As IEditorOptionsFactoryService <ImportingConstructor()> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New( smartIndentationService As ISmartIndentationService, undoHistoryRegistry As ITextUndoHistoryRegistry, editorOperationsFactoryService As IEditorOperationsFactoryService, editorOptionsFactoryService As IEditorOptionsFactoryService) ThrowIfNull(smartIndentationService) ThrowIfNull(undoHistoryRegistry) ThrowIfNull(editorOperationsFactoryService) ThrowIfNull(editorOptionsFactoryService) _smartIndentationService = smartIndentationService _undoHistoryRegistry = undoHistoryRegistry _editorOperationsFactoryService = editorOperationsFactoryService _editorOptionsFactoryService = editorOptionsFactoryService End Sub Private Shared Function IsMissingStatementError(statement As SyntaxNode, [error] As String) As Boolean Select Case [error] ' TODO(jasonmal): get rid of this. It is an open design goal to move missing end errors from the ' statement to the block. Besides making incremental parsing easier, it will also clean this mess up. ' Until then, I'm content with this hack. Case "BC30012" ' Missing #End If Return True Case "BC30481" ' Missing End Class Return True Case "BC30625" ' Missing End Module Return True Case "BC30185" ' Missing End Enum Return True Case "BC30253" ' Missing End Interface Return True Case "BC30624" ' Missing End Structure Return True Case "BC30626" ' Missing End Namespace Return True Case "BC30026" ' Missing End Sub Return True Case "BC30027" ' Missing End Function Return True Case "BC30631" ' Missing End Get Return True Case "BC30633" ' Missing End Set Return True Case "BC30025" ' Missing End Property Return True Case "BC30081" ' Missing End If Return True Case "BC30082" ' Missing End While Return True Case "BC30083" ' Missing Loop Return True Case "BC30084" ' Missing Next Return True Case "BC30085" ' Missing End With Return True Case "BC30095" ' Missing End Select Return True Case "BC36008" ' Missing End Using Return True Case "BC30675" ' Missing End SyncLock Return True Case "BC30681" ' Missing #End Region Return True Case "BC33005" ' Missing End Operator Return True Case "BC36759" ' Auto-implemented properties cannot have parameters Return True Case "BC36673" ' Missing End Sub for Lambda Return True Case "BC36674" ' Missing End Function for Lambda Return True Case "BC30384" ' Missing End Try Return True Case "BC30198", "BC30199" ' These happen if I type Dim x = Function without parenthesis, so as long as we are in that content, ' count this as an acceptable error. Return TypeOf statement Is LambdaHeaderSyntax Case "BC31114" ' Missing End Event Return True End Select Return False End Function Private Shared Function IsExpectedXmlNameError([error] As String) As Boolean Return [error] = "BC31146" End Function Private Shared Function IsMissingXmlEndTagError([error] As String) As Boolean Return [error] = "BC31151" End Function Private Shared Function IsExpectedXmlEndEmbeddedError([error] As String) As Boolean Return [error] = "BC31159" End Function Private Shared Function IsExpectedXmlEndPIError([error] As String) As Boolean Return [error] = "BC31160" End Function Private Shared Function IsExpectedXmlEndCommentError([error] As String) As Boolean Return [error] = "BC31161" End Function Private Shared Function IsExpectedXmlEndCDataError([error] As String) As Boolean Return [error] = "BC31162" End Function Private Function GetEndConstructState(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As EndConstructState Dim caretPosition = textView.GetCaretPoint(subjectBuffer) If caretPosition Is Nothing Then Return Nothing End If Dim document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges() If document Is Nothing Then Return Nothing End If Dim tree = document.GetSyntaxTreeSynchronously(cancellationToken) Dim tokenToLeft = tree.FindTokenOnLeftOfPosition(caretPosition.Value, cancellationToken, includeDirectives:=True, includeDocumentationComments:=True) If tokenToLeft.Kind = SyntaxKind.None Then Return Nothing End If Dim bufferOptions = _editorOptionsFactoryService.GetOptions(subjectBuffer) Return New EndConstructState( caretPosition.Value, New Lazy(Of SemanticModel)(Function() document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken)), tree, tokenToLeft, bufferOptions.GetNewLineCharacter()) End Function Friend Overridable Function TryDoEndConstructForEnterKey(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_DoStatement, cancellationToken) Using transaction = New CaretPreservingEditTransaction(VBEditorResources.End_Construct, textView, _undoHistoryRegistry, _editorOperationsFactoryService) transaction.MergePolicy = AutomaticCodeChangeMergePolicy.Instance ' The user may have some text selected. In this scenario, we want to guarantee ' two things: ' ' 1) the text that was selected is deleted, as a normal pressing of an enter key ' would do. Since we're not letting the editor do it's own thing during end ' construct generation, we need to make sure the selection is deleted. ' 2) that we compute what statements we should spit assuming the selected text ' is no longer there. Consider a scenario where the user has something like: ' ' If True Then ~~~~ ' ' and the completely invalid "~~~~" is selected. In VS2010, if you pressed ' enter, we would still spit enter, since we effectively view that code as ' "no longer there." ' ' The fix is simple: as a part of our transaction, we'll just delete anything ' under our selection. As long as our transaction goes through, the user won't ' suspect anything was fishy. If we don't spit, we'll cancel the transaction ' which will roll back this edit. _editorOperationsFactoryService.GetEditorOperations(textView).ReplaceSelection("") Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If ' Are we in the middle of XML tags? If state.TokenToLeft.Kind = SyntaxKind.GreaterThanToken Then Dim element = state.TokenToLeft.GetAncestor(Of XmlElementSyntax) If element IsNot Nothing Then If element.StartTag IsNot Nothing AndAlso element.StartTag.Span.End = state.CaretPosition AndAlso element.EndTag IsNot Nothing AndAlso element.EndTag.SpanStart = state.CaretPosition Then InsertBlankLineBetweenXmlTags(state, textView, subjectBuffer) transaction.Complete() Return True End If End If End If ' Figure out which statement that is to the left of us Dim statement = state.TokenToLeft.FirstAncestorOrSelf(Function(n) TypeOf n Is StatementSyntax OrElse TypeOf n Is DirectiveTriviaSyntax) ' Make sure we are after the last token of the statement or ' if the statement is a single-line If statement that ' we're after the "Then" or "Else" token. If statement Is Nothing Then Return False ElseIf statement.Kind = SyntaxKind.SingleLineIfStatement Then Dim asSingleLine = DirectCast(statement, SingleLineIfStatementSyntax) If state.TokenToLeft <> asSingleLine.ThenKeyword AndAlso (asSingleLine.ElseClause Is Nothing OrElse state.TokenToLeft <> asSingleLine.ElseClause.ElseKeyword) Then Return False End If ElseIf statement.GetLastToken() <> state.TokenToLeft Then Return False End If ' Make sure we were on the same line as the last token. Dim caretLine = subjectBuffer.CurrentSnapshot.GetLineNumberFromPosition(state.CaretPosition) Dim lineOfLastToken = subjectBuffer.CurrentSnapshot.GetLineNumberFromPosition(state.TokenToLeft.SpanStart) If caretLine <> lineOfLastToken Then Return False End If ' Make sure that we don't have any skipped trivia between our target token and ' the end of the line Dim nextToken = state.TokenToLeft.GetNextTokenOrEndOfFile() Dim nextTokenLine = subjectBuffer.CurrentSnapshot.GetLineNumberFromPosition(nextToken.SpanStart) If nextToken.IsKind(SyntaxKind.EndOfFileToken) AndAlso nextTokenLine = caretLine Then If nextToken.LeadingTrivia.Any(Function(trivia) trivia.IsKind(SyntaxKind.SkippedTokensTrivia)) Then Return False End If End If ' If this is an Imports or Implements declaration, we should use the enclosing type declaration. If TypeOf statement Is InheritsOrImplementsStatementSyntax Then Dim baseDeclaration = DirectCast(statement, InheritsOrImplementsStatementSyntax) Dim typeBlock = baseDeclaration.GetAncestor(Of TypeBlockSyntax)() If typeBlock Is Nothing Then Return False End If statement = typeBlock.BlockStatement End If If statement Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(statement) If errors.Any(Function(e) Not IsMissingStatementError(statement, e.Id)) Then If statement.Kind = SyntaxKind.SingleLineIfStatement Then Dim asSingleLine = DirectCast(statement, SingleLineIfStatementSyntax) Dim span = TextSpan.FromBounds(asSingleLine.IfKeyword.SpanStart, asSingleLine.ThenKeyword.Span.End) If errors.Any(Function(e) span.Contains(e.Location.SourceSpan)) Then Return False End If Else Return False End If End If ' Make sure this statement does not end with the line continuation character If statement.GetLastToken(includeZeroWidth:=True).TrailingTrivia.Any(Function(t) t.Kind = SyntaxKind.LineContinuationTrivia) Then Return False End If Dim visitor = New EndConstructStatementVisitor(textView, subjectBuffer, state, cancellationToken) Dim result = visitor.Visit(statement) If result Is Nothing Then Return False End If result.Apply(textView, subjectBuffer, state.CaretPosition, _smartIndentationService, _undoHistoryRegistry, _editorOperationsFactoryService) transaction.Complete() End Using End Using Return True End Function Private Sub InsertBlankLineBetweenXmlTags(state As EndConstructState, textView As ITextView, subjectBuffer As ITextBuffer) ' Add an extra newline first Using edit = subjectBuffer.CreateEdit() Dim aligningWhitespace = subjectBuffer.CurrentSnapshot.GetAligningWhitespace(state.TokenToLeft.Parent.Span.Start) edit.Insert(state.CaretPosition, state.NewLineCharacter + aligningWhitespace) edit.ApplyAndLogExceptions() End Using ' And now just send down a normal enter textView.TryMoveCaretToAndEnsureVisible(New SnapshotPoint(subjectBuffer.CurrentSnapshot, state.CaretPosition)) _editorOperationsFactoryService.GetEditorOperations(textView).InsertNewLine() End Sub Private Shared Function GetNodeFromToken(Of T As SyntaxNode)(token As SyntaxToken, expectedKind As SyntaxKind) As T If token.Kind <> expectedKind Then Return Nothing End If Return TryCast(token.Parent, T) End Function Private Shared Function InsertEndTextAndUpdateCaretPosition( view As ITextView, subjectBuffer As ITextBuffer, insertPosition As Integer, caretPosition As Integer, endText As String ) As Boolean Dim document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges() If document Is Nothing Then Return False End If subjectBuffer.ApplyChange(New TextChange(New TextSpan(insertPosition, 0), endText)) Dim caretPosAfterEdit = New SnapshotPoint(subjectBuffer.CurrentSnapshot, caretPosition) view.TryMoveCaretToAndEnsureVisible(caretPosAfterEdit) Return True End Function Friend Function TryDoXmlCDataEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlCData, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlCData = GetNodeFromToken(Of XmlCDataSectionSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.BeginCDataToken) If xmlCData Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlCData) ' Exactly one error is expected: ERRID_ExpectedXmlEndCData If errors.Count <> 1 Then Return False End If If Not IsExpectedXmlEndCDataError(errors(0).Id) Then Return False End If Dim endText = "]]>" Return InsertEndTextAndUpdateCaretPosition(textView, subjectBuffer, state.CaretPosition, state.TokenToLeft.Span.End, endText) End Using End Function Friend Function TryDoXmlCommentEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlComment, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlComment = GetNodeFromToken(Of XmlCommentSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.LessThanExclamationMinusMinusToken) If xmlComment Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlComment) ' Exactly one error is expected: ERRID_ExpectedXmlEndComment If errors.Count <> 1 Then Return False End If If Not IsExpectedXmlEndCommentError(errors(0).Id) Then Return False End If Dim endText = "-->" Return InsertEndTextAndUpdateCaretPosition(textView, subjectBuffer, state.CaretPosition, state.TokenToLeft.Span.End, endText) End Using End Function Friend Function TryDoXmlElementEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlElement, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlStartElement = GetNodeFromToken(Of XmlElementStartTagSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.GreaterThanToken) If xmlStartElement Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlStartElement) ' Exactly one error is expected: ERRID_MissingXmlEndTag If errors.Count <> 1 Then Return False End If If Not IsMissingXmlEndTagError(errors(0).Id) Then Return False End If Dim endTagText = "</" & xmlStartElement.Name.ToString & ">" Return InsertEndTextAndUpdateCaretPosition(textView, subjectBuffer, state.CaretPosition, state.TokenToLeft.Span.End, endTagText) End Using End Function Friend Function TryDoXmlEmbeddedExpressionEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlEmbeddedExpression, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlEmbeddedExpression = GetNodeFromToken(Of XmlEmbeddedExpressionSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.LessThanPercentEqualsToken) If xmlEmbeddedExpression Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlEmbeddedExpression) ' Errors should contain ERRID_ExpectedXmlEndEmbedded If Not errors.Any(Function(e) IsExpectedXmlEndEmbeddedError(e.Id)) Then Return False End If Dim endText = " %>" ' NOTE: two spaces are inserted. The caret will be moved between them Return InsertEndTextAndUpdateCaretPosition(textView, subjectBuffer, state.CaretPosition, state.TokenToLeft.Span.End + 1, endText) End Using End Function Friend Function TryDoXmlProcessingInstructionEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlProcessingInstruction, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlProcessingInstruction = GetNodeFromToken(Of XmlProcessingInstructionSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.LessThanQuestionToken) If xmlProcessingInstruction Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlProcessingInstruction) ' Exactly two errors are expected: ERRID_ExpectedXmlName and ERRID_ExpectedXmlEndPI If errors.Count <> 2 Then Return False End If If Not (errors.Any(Function(e) IsExpectedXmlNameError(e.Id)) AndAlso errors.Any(Function(e) IsExpectedXmlEndPIError(e.Id))) Then Return False End If Dim endText = "?>" Return InsertEndTextAndUpdateCaretPosition(textView, subjectBuffer, state.CaretPosition, state.TokenToLeft.Span.End, endText) End Using End Function Public Function TryDo(textView As ITextView, subjectBuffer As ITextBuffer, typedChar As Char, cancellationToken As CancellationToken) As Boolean Implements IEndConstructGenerationService.TryDo Select Case typedChar Case vbLf(0) Return Me.TryDoEndConstructForEnterKey(textView, subjectBuffer, cancellationToken) Case ">"c Return Me.TryDoXmlElementEndConstruct(textView, subjectBuffer, cancellationToken) Case "-"c Return Me.TryDoXmlCommentEndConstruct(textView, subjectBuffer, cancellationToken) Case "="c Return Me.TryDoXmlEmbeddedExpressionEndConstruct(textView, subjectBuffer, cancellationToken) Case "["c Return Me.TryDoXmlCDataEndConstruct(textView, subjectBuffer, cancellationToken) Case "?"c Return Me.TryDoXmlProcessingInstructionEndConstruct(textView, subjectBuffer, cancellationToken) End Select Return False End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AssemblyAndNamespaceTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Imports System.Collections.Immutable Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class ContainerTests Inherits BasicTestBase ' Check that "basRootNS" is actually a bad root namespace Private Sub BadDefaultNS(badRootNS As String) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace(badRootNS).Errors, <expected> BC2014: the value '<%= badRootNS %>' is invalid for option 'RootNamespace' </expected>) End Sub <Fact> Public Sub SimpleAssembly() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Banana"> <file name="b.vb"> Namespace NS Public Class Goo End Class End Namespace </file> </compilation>) Dim sym = compilation.Assembly Assert.Equal("Banana", sym.Name) Assert.Equal("Banana, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", sym.ToTestDisplayString()) Assert.Equal(String.Empty, sym.GlobalNamespace.Name) Assert.Equal(SymbolKind.Assembly, sym.Kind) Assert.Equal(Accessibility.NotApplicable, sym.DeclaredAccessibility) Assert.False(sym.IsShared) Assert.False(sym.IsOverridable) Assert.False(sym.IsOverrides) Assert.False(sym.IsMustOverride) Assert.False(sym.IsNotOverridable) Assert.Null(sym.ContainingAssembly) Assert.Null(sym.ContainingSymbol) End Sub <WorkItem(537302, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537302")> <Fact> Public Sub SourceModule() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Banana"> <file name="m.vb"> Namespace NS Public Class Goo End Class End Namespace </file> </compilation>) Dim sym = compilation.SourceModule Assert.Equal("Banana.dll", sym.Name) Assert.Equal(String.Empty, sym.GlobalNamespace.Name) Assert.Equal(SymbolKind.NetModule, sym.Kind) Assert.Equal(Accessibility.NotApplicable, sym.DeclaredAccessibility) Assert.False(sym.IsShared) Assert.False(sym.IsOverridable) Assert.False(sym.IsOverrides) Assert.False(sym.IsMustOverride) Assert.False(sym.IsNotOverridable) Assert.Equal("Banana", sym.ContainingAssembly.Name) Assert.Equal("Banana", sym.ContainingSymbol.Name) End Sub <WorkItem(537421, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537421")> <Fact> Public Sub StandardModule() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Banana"> <file name="m.vb"> Namespace NS Module MGoo Dim A As Integer Sub MySub() End Sub Function Func(x As Long) As Long Return x End Function End Module End Namespace </file> </compilation>) Dim ns As NamespaceSymbol = DirectCast(compilation.SourceModule.GlobalNamespace.GetMembers("NS").Single(), NamespaceSymbol) Dim sym1 = ns.GetMembers("MGoo").Single() Assert.Equal("MGoo", sym1.Name) Assert.Equal("NS.MGoo", sym1.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sym1.Kind) ' default - Friend Assert.Equal(Accessibility.Friend, sym1.DeclaredAccessibility) Assert.False(sym1.IsShared) Assert.False(sym1.IsOverridable) Assert.False(sym1.IsOverrides) Assert.False(sym1.IsMustOverride) Assert.False(sym1.IsNotOverridable) Assert.Equal("Banana", sym1.ContainingAssembly.Name) Assert.Equal("NS", sym1.ContainingSymbol.Name) ' module member Dim smod = DirectCast(sym1, NamedTypeSymbol) Dim sym2 = DirectCast(smod.GetMembers("A").Single(), FieldSymbol) ' default - Private Assert.Equal(Accessibility.Private, sym2.DeclaredAccessibility) Assert.True(sym2.IsShared) Dim sym3 = DirectCast(smod.GetMembers("MySub").Single(), MethodSymbol) Dim sym4 = DirectCast(smod.GetMembers("Func").Single(), MethodSymbol) ' default - Public Assert.Equal(Accessibility.Public, sym3.DeclaredAccessibility) Assert.Equal(Accessibility.Public, sym4.DeclaredAccessibility) Assert.True(sym3.IsShared) Assert.True(sym4.IsShared) ' shared cctor 'sym4 = DirectCast(smod.GetMembers(WellKnownMemberNames.StaticConstructorName).Single(), MethodSymbol) End Sub ' Check that we disallow certain kids of bad root namespaces <Fact> Public Sub BadDefaultNSTest() BadDefaultNS("Goo.7") BadDefaultNS("Goo..Bar") BadDefaultNS(".X") BadDefaultNS("$") End Sub ' Check that parse errors are reported <Fact> Public Sub NamespaceParseErrors() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Banana"> <file name="a.vb"> Imports System.7 </file> <file name="b.vb"> Namespace Goo End Class </file> </compilation>) Dim expectedErrors = <errors> BC30205: End of statement expected. Imports System.7 ~~ BC30626: 'Namespace' statement must end with a matching 'End Namespace'. Namespace Goo ~~~~~~~~~~~~~ BC30460: 'End Class' must be preceded by a matching 'Class'. End Class ~~~~~~~~~ </errors> CompilationUtils.AssertTheseParseDiagnostics(compilation, expectedErrors) End Sub ' Check namespace symbols <Fact> Public Sub NSSym() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Namespace A End Namespace Namespace C End Namespace </file> <file name="b.vb"> Namespace A.B End Namespace Namespace a.B End Namespace Namespace e End Namespace </file> <file name="c.vb"> Namespace A.b.D End Namespace </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Assert.Equal("", globalNS.Name) Assert.Equal(SymbolKind.Namespace, globalNS.Kind) Assert.Equal(3, globalNS.GetMembers().Length()) Dim members = globalNS.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name, IdentifierComparison.Comparer).ToArray() Dim membersA = globalNS.GetMembers("a") Dim membersC = globalNS.GetMembers("c") Dim membersE = globalNS.GetMembers("E") Assert.Equal(3, members.Length) Assert.Equal(1, membersA.Length) Assert.Equal(1, membersC.Length) Assert.Equal(1, membersE.Length) Assert.True(members.SequenceEqual(membersA.Concat(membersC).Concat(membersE).AsEnumerable())) Assert.Equal("a", membersA.First().Name, IdentifierComparison.Comparer) Assert.Equal("C", membersC.First().Name, IdentifierComparison.Comparer) Assert.Equal("E", membersE.First().Name, IdentifierComparison.Comparer) Dim nsA As NamespaceSymbol = DirectCast(membersA.First(), NamespaceSymbol) Assert.Equal("A", nsA.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.Namespace, nsA.Kind) Assert.Equal(1, nsA.GetMembers().Length()) Dim nsB As NamespaceSymbol = DirectCast(nsA.GetMembers().First(), NamespaceSymbol) Assert.Equal("B", nsB.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.Namespace, nsB.Kind) Assert.Equal(1, nsB.GetMembers().Length()) Dim nsD As NamespaceSymbol = DirectCast(nsB.GetMembers().First(), NamespaceSymbol) Assert.Equal("D", nsD.Name) Assert.Equal(SymbolKind.Namespace, nsD.Kind) Assert.Equal(0, nsD.GetMembers().Length()) AssertTheseDeclarationDiagnostics(compilation, <expected> BC40055: Casing of namespace name 'a' does not match casing of namespace name 'A' in 'a.vb'. Namespace a.B ~ BC40055: Casing of namespace name 'b' does not match casing of namespace name 'B' in 'b.vb'. Namespace A.b.D ~ </expected>) End Sub ' Check namespace symbols in the presence of a root namespace <Fact> Public Sub NSSymWithRootNamespace() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Namespace A End Namespace Namespace E End Namespace </file> <file name="b.vb"> Namespace A.B End Namespace Namespace C End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithRootNamespace("Goo.Bar")) Dim globalNS = compilation.SourceModule.GlobalNamespace Assert.Equal("", globalNS.Name) Assert.Equal(SymbolKind.Namespace, globalNS.Kind) Assert.Equal(1, globalNS.GetMembers().Length()) Dim members = globalNS.GetMembers() Dim nsGoo As NamespaceSymbol = DirectCast(members.First(), NamespaceSymbol) Assert.Equal("Goo", nsGoo.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.Namespace, nsGoo.Kind) Assert.Equal(1, nsGoo.GetMembers().Length()) Dim membersGoo = nsGoo.GetMembers() Dim nsBar As NamespaceSymbol = DirectCast(membersGoo.First(), NamespaceSymbol) Assert.Equal("Bar", nsBar.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.Namespace, nsBar.Kind) Assert.Equal(3, nsBar.GetMembers().Length()) Dim membersBar = nsBar.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name, IdentifierComparison.Comparer).ToArray() Dim membersA = nsBar.GetMembers("a") Dim membersC = nsBar.GetMembers("c") Dim membersE = nsBar.GetMembers("E") Assert.Equal(3, membersBar.Length) Assert.Equal(1, membersA.Length) Assert.Equal(1, membersC.Length) Assert.Equal(1, membersE.Length) Assert.True(membersBar.SequenceEqual(membersA.Concat(membersC).Concat(membersE).AsEnumerable())) Assert.Equal("a", membersA.First().Name, IdentifierComparison.Comparer) Assert.Equal("C", membersC.First().Name, IdentifierComparison.Comparer) Assert.Equal("E", membersE.First().Name, IdentifierComparison.Comparer) Dim nsA As NamespaceSymbol = DirectCast(membersA.First(), NamespaceSymbol) Assert.Equal("A", nsA.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.Namespace, nsA.Kind) Assert.Equal(1, nsA.GetMembers().Length()) Dim nsB As NamespaceSymbol = DirectCast(nsA.GetMembers().First(), NamespaceSymbol) Assert.Equal("B", nsB.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.Namespace, nsB.Kind) Assert.Equal(0, nsB.GetMembers().Length()) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub ' Check namespace symbol containers in the presence of a root namespace <Fact> Public Sub NSContainersWithRootNamespace() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Class Type1 End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithRootNamespace("Goo.Bar")) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim members = globalNS.GetMembers() Dim nsGoo As NamespaceSymbol = DirectCast(members.First(), NamespaceSymbol) Dim membersGoo = nsGoo.GetMembers() Dim nsBar As NamespaceSymbol = DirectCast(membersGoo.First(), NamespaceSymbol) Dim type1Sym = nsBar.GetMembers("Type1").Single() Assert.Same(nsBar, type1Sym.ContainingSymbol) Assert.Same(nsGoo, nsBar.ContainingSymbol) Assert.Same(globalNS, nsGoo.ContainingSymbol) Assert.Same(compilation.SourceModule, globalNS.ContainingSymbol) End Sub ' Check namespace symbol containers in the presence of a root namespace <Fact> Public Sub NSContainersWithoutRootNamespace() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Class Type1 End Class </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim type1Sym = globalNS.GetMembers("Type1").Single() Assert.Same(globalNS, type1Sym.ContainingSymbol) Assert.Same(compilation.SourceModule, globalNS.ContainingSymbol) End Sub <Fact> Public Sub ImportsAlias01() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Test"> <file name="a.vb"> Imports ALS = N1.N2 Namespace N1 Namespace N2 Public Class A Sub S() End Sub End Class End Namespace End Namespace Namespace N3 Public Class B Inherits ALS.A End Class End Namespace </file> <file name="b.vb"> Imports ANO = N3 Namespace N1.N2 Class C Inherits ANO.B End Class End Namespace </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim n3 = DirectCast(globalNS.GetMembers("N3").Single(), NamespaceSymbol) Dim mem1 = DirectCast(n3.GetTypeMembers("B").Single(), NamedTypeSymbol) Assert.Equal("A", mem1.BaseType.Name) Assert.Equal("N1.N2.A", mem1.BaseType.ToTestDisplayString()) Dim n1 = DirectCast(globalNS.GetMembers("N1").Single(), NamespaceSymbol) Dim n2 = DirectCast(n1.GetMembers("N2").Single(), NamespaceSymbol) Dim mem2 = DirectCast(n2.GetTypeMembers("C").Single(), NamedTypeSymbol) Assert.Equal("B", mem2.BaseType.Name) Assert.Equal("N3.B", mem2.BaseType.ToTestDisplayString()) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <Fact, WorkItem(544009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544009")> Public Sub MultiModulesNamespace() Dim text3 = <![CDATA[ Namespace N1 Structure SGoo End Structure End Namespace ]]>.Value Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Test1"> <file name="a.vb"> Namespace N1 Class CGoo End Class End Namespace </file> </compilation>) Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Test2"> <file name="b.vb"> Namespace N1 Interface IGoo End Interface End Namespace </file> </compilation>) Dim compRef1 = New VisualBasicCompilationReference(comp1) Dim compRef2 = New VisualBasicCompilationReference(comp2) Dim comp = VisualBasicCompilation.Create("Test3", {VisualBasicSyntaxTree.ParseText(text3)}, {MscorlibRef, compRef1, compRef2}) Dim globalNS = comp.GlobalNamespace Dim ns = DirectCast(globalNS.GetMembers("N1").Single(), NamespaceSymbol) Assert.Equal(3, ns.GetTypeMembers().Length()) Dim ext = ns.Extent Assert.Equal(NamespaceKind.Compilation, ext.Kind) Assert.Equal("Compilation: " & GetType(VisualBasicCompilation).FullName, ext.ToString()) Dim constituents = ns.ConstituentNamespaces Assert.Equal(3, constituents.Length) Assert.True(constituents.Contains(TryCast(comp.SourceAssembly.GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol))) Assert.True(constituents.Contains(TryCast(comp.GetReferencedAssemblySymbol(compRef1).GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol))) Assert.True(constituents.Contains(TryCast(comp.GetReferencedAssemblySymbol(compRef2).GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol))) For Each constituentNs In constituents Assert.Equal(NamespaceKind.Module, constituentNs.Extent.Kind) Assert.Equal(ns.ToTestDisplayString(), constituentNs.ToTestDisplayString()) Next End Sub <WorkItem(537310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537310")> <Fact> Public Sub MultiModulesNamespaceCorLibraries() Dim text1 = <![CDATA[ Namespace N1 Class CGoo End Class End Namespace ]]>.Value Dim text2 = <![CDATA[ Namespace N1 Interface IGoo End Interface End Namespace ]]>.Value Dim text3 = <![CDATA[ Namespace N1 Structure SGoo End Structure End Namespace ]]>.Value Dim comp1 = VisualBasicCompilation.Create("Test1", syntaxTrees:={VisualBasicSyntaxTree.ParseText(text1)}) Dim comp2 = VisualBasicCompilation.Create("Test2", syntaxTrees:={VisualBasicSyntaxTree.ParseText(text2)}) Dim compRef1 = New VisualBasicCompilationReference(comp1) Dim compRef2 = New VisualBasicCompilationReference(comp2) Dim comp = VisualBasicCompilation.Create("Test3", {VisualBasicSyntaxTree.ParseText(text3)}, {compRef1, compRef2}) Dim globalNS = comp.GlobalNamespace Dim ns = DirectCast(globalNS.GetMembers("N1").Single(), NamespaceSymbol) Assert.Equal(3, ns.GetTypeMembers().Length()) Assert.Equal(NamespaceKind.Compilation, ns.Extent.Kind) Dim constituents = ns.ConstituentNamespaces Assert.Equal(3, constituents.Length) Assert.True(constituents.Contains(TryCast(comp.SourceAssembly.GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol))) Assert.True(constituents.Contains(TryCast(comp.GetReferencedAssemblySymbol(compRef1).GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol))) Assert.True(constituents.Contains(TryCast(comp.GetReferencedAssemblySymbol(compRef2).GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol))) For Each constituentNs In constituents Assert.Equal(NamespaceKind.Module, constituentNs.Extent.Kind) Assert.Equal(ns.ToTestDisplayString(), constituentNs.ToTestDisplayString()) Next End Sub <WorkItem(690871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/690871")> <Fact> Public Sub SpecialTypesAndAliases() Dim source = <compilation name="C"> <file> Public Class C End Class </file> </compilation> Dim aliasedCorlib = TestMetadata.Net451.mscorlib.WithAliases(ImmutableArray.Create("Goo")) Dim comp = CreateEmptyCompilationWithReferences(source, {aliasedCorlib}) ' NOTE: this doesn't compile in dev11 - it reports that it cannot find System.Object. ' However, we've already changed how special type lookup works, so this is not a major issue. comp.AssertNoDiagnostics() Dim objectType = comp.GetSpecialType(SpecialType.System_Object) Assert.Equal(TypeKind.Class, objectType.TypeKind) Assert.Equal("System.Object", objectType.ToTestDisplayString()) Assert.Equal(objectType, comp.Assembly.GetSpecialType(SpecialType.System_Object)) Assert.Equal(objectType, comp.Assembly.CorLibrary.GetSpecialType(SpecialType.System_Object)) End Sub <WorkItem(690871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/690871")> <Fact> Public Sub WellKnownTypesAndAliases() Dim [lib] = <compilation name="lib"> <file> Namespace System.Threading.Tasks Public Class Task Public Status As Integer End Class End Namespace </file> </compilation> Dim source = <compilation name="test"> <file> Imports System.Threading.Tasks Public Class App Public T as Task End Class </file> </compilation> Dim libComp = CreateEmptyCompilationWithReferences([lib], {MscorlibRef_v4_0_30316_17626}) Dim libRef = libComp.EmitToImageReference(aliases:=ImmutableArray.Create("myTask")) Dim comp = CreateEmptyCompilationWithReferences(source, {libRef, MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}) ' NOTE: Unlike in C#, aliases on metadata references are ignored, so the ' reference to System.Threading.Tasks is ambiguous. comp.AssertTheseDiagnostics( <expected> BC30560: 'Task' is ambiguous in the namespace 'System.Threading.Tasks'. Public T as Task ~~~~ </expected>) End Sub <Fact, WorkItem(54836, "https://github.com/dotnet/roslyn/issues/54836")> Public Sub RetargetableAttributeIsRespectedInSource() Dim code = <![CDATA[ Imports System.Reflection <Assembly: AssemblyFlags(AssemblyNameFlags.Retargetable)> ]]> Dim comp = CreateCompilation(code.Value) Assert.True(comp.Assembly.Identity.IsRetargetable) AssertTheseEmitDiagnostics(comp) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Imports System.Collections.Immutable Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class ContainerTests Inherits BasicTestBase ' Check that "basRootNS" is actually a bad root namespace Private Sub BadDefaultNS(badRootNS As String) AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace(badRootNS).Errors, <expected> BC2014: the value '<%= badRootNS %>' is invalid for option 'RootNamespace' </expected>) End Sub <Fact> Public Sub SimpleAssembly() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Banana"> <file name="b.vb"> Namespace NS Public Class Goo End Class End Namespace </file> </compilation>) Dim sym = compilation.Assembly Assert.Equal("Banana", sym.Name) Assert.Equal("Banana, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", sym.ToTestDisplayString()) Assert.Equal(String.Empty, sym.GlobalNamespace.Name) Assert.Equal(SymbolKind.Assembly, sym.Kind) Assert.Equal(Accessibility.NotApplicable, sym.DeclaredAccessibility) Assert.False(sym.IsShared) Assert.False(sym.IsOverridable) Assert.False(sym.IsOverrides) Assert.False(sym.IsMustOverride) Assert.False(sym.IsNotOverridable) Assert.Null(sym.ContainingAssembly) Assert.Null(sym.ContainingSymbol) End Sub <WorkItem(537302, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537302")> <Fact> Public Sub SourceModule() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Banana"> <file name="m.vb"> Namespace NS Public Class Goo End Class End Namespace </file> </compilation>) Dim sym = compilation.SourceModule Assert.Equal("Banana.dll", sym.Name) Assert.Equal(String.Empty, sym.GlobalNamespace.Name) Assert.Equal(SymbolKind.NetModule, sym.Kind) Assert.Equal(Accessibility.NotApplicable, sym.DeclaredAccessibility) Assert.False(sym.IsShared) Assert.False(sym.IsOverridable) Assert.False(sym.IsOverrides) Assert.False(sym.IsMustOverride) Assert.False(sym.IsNotOverridable) Assert.Equal("Banana", sym.ContainingAssembly.Name) Assert.Equal("Banana", sym.ContainingSymbol.Name) End Sub <WorkItem(537421, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537421")> <Fact> Public Sub StandardModule() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Banana"> <file name="m.vb"> Namespace NS Module MGoo Dim A As Integer Sub MySub() End Sub Function Func(x As Long) As Long Return x End Function End Module End Namespace </file> </compilation>) Dim ns As NamespaceSymbol = DirectCast(compilation.SourceModule.GlobalNamespace.GetMembers("NS").Single(), NamespaceSymbol) Dim sym1 = ns.GetMembers("MGoo").Single() Assert.Equal("MGoo", sym1.Name) Assert.Equal("NS.MGoo", sym1.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, sym1.Kind) ' default - Friend Assert.Equal(Accessibility.Friend, sym1.DeclaredAccessibility) Assert.False(sym1.IsShared) Assert.False(sym1.IsOverridable) Assert.False(sym1.IsOverrides) Assert.False(sym1.IsMustOverride) Assert.False(sym1.IsNotOverridable) Assert.Equal("Banana", sym1.ContainingAssembly.Name) Assert.Equal("NS", sym1.ContainingSymbol.Name) ' module member Dim smod = DirectCast(sym1, NamedTypeSymbol) Dim sym2 = DirectCast(smod.GetMembers("A").Single(), FieldSymbol) ' default - Private Assert.Equal(Accessibility.Private, sym2.DeclaredAccessibility) Assert.True(sym2.IsShared) Dim sym3 = DirectCast(smod.GetMembers("MySub").Single(), MethodSymbol) Dim sym4 = DirectCast(smod.GetMembers("Func").Single(), MethodSymbol) ' default - Public Assert.Equal(Accessibility.Public, sym3.DeclaredAccessibility) Assert.Equal(Accessibility.Public, sym4.DeclaredAccessibility) Assert.True(sym3.IsShared) Assert.True(sym4.IsShared) ' shared cctor 'sym4 = DirectCast(smod.GetMembers(WellKnownMemberNames.StaticConstructorName).Single(), MethodSymbol) End Sub ' Check that we disallow certain kids of bad root namespaces <Fact> Public Sub BadDefaultNSTest() BadDefaultNS("Goo.7") BadDefaultNS("Goo..Bar") BadDefaultNS(".X") BadDefaultNS("$") End Sub ' Check that parse errors are reported <Fact> Public Sub NamespaceParseErrors() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Banana"> <file name="a.vb"> Imports System.7 </file> <file name="b.vb"> Namespace Goo End Class </file> </compilation>) Dim expectedErrors = <errors> BC30205: End of statement expected. Imports System.7 ~~ BC30626: 'Namespace' statement must end with a matching 'End Namespace'. Namespace Goo ~~~~~~~~~~~~~ BC30460: 'End Class' must be preceded by a matching 'Class'. End Class ~~~~~~~~~ </errors> CompilationUtils.AssertTheseParseDiagnostics(compilation, expectedErrors) End Sub ' Check namespace symbols <Fact> Public Sub NSSym() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Namespace A End Namespace Namespace C End Namespace </file> <file name="b.vb"> Namespace A.B End Namespace Namespace a.B End Namespace Namespace e End Namespace </file> <file name="c.vb"> Namespace A.b.D End Namespace </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Assert.Equal("", globalNS.Name) Assert.Equal(SymbolKind.Namespace, globalNS.Kind) Assert.Equal(3, globalNS.GetMembers().Length()) Dim members = globalNS.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name, IdentifierComparison.Comparer).ToArray() Dim membersA = globalNS.GetMembers("a") Dim membersC = globalNS.GetMembers("c") Dim membersE = globalNS.GetMembers("E") Assert.Equal(3, members.Length) Assert.Equal(1, membersA.Length) Assert.Equal(1, membersC.Length) Assert.Equal(1, membersE.Length) Assert.True(members.SequenceEqual(membersA.Concat(membersC).Concat(membersE).AsEnumerable())) Assert.Equal("a", membersA.First().Name, IdentifierComparison.Comparer) Assert.Equal("C", membersC.First().Name, IdentifierComparison.Comparer) Assert.Equal("E", membersE.First().Name, IdentifierComparison.Comparer) Dim nsA As NamespaceSymbol = DirectCast(membersA.First(), NamespaceSymbol) Assert.Equal("A", nsA.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.Namespace, nsA.Kind) Assert.Equal(1, nsA.GetMembers().Length()) Dim nsB As NamespaceSymbol = DirectCast(nsA.GetMembers().First(), NamespaceSymbol) Assert.Equal("B", nsB.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.Namespace, nsB.Kind) Assert.Equal(1, nsB.GetMembers().Length()) Dim nsD As NamespaceSymbol = DirectCast(nsB.GetMembers().First(), NamespaceSymbol) Assert.Equal("D", nsD.Name) Assert.Equal(SymbolKind.Namespace, nsD.Kind) Assert.Equal(0, nsD.GetMembers().Length()) AssertTheseDeclarationDiagnostics(compilation, <expected> BC40055: Casing of namespace name 'a' does not match casing of namespace name 'A' in 'a.vb'. Namespace a.B ~ BC40055: Casing of namespace name 'b' does not match casing of namespace name 'B' in 'b.vb'. Namespace A.b.D ~ </expected>) End Sub ' Check namespace symbols in the presence of a root namespace <Fact> Public Sub NSSymWithRootNamespace() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Namespace A End Namespace Namespace E End Namespace </file> <file name="b.vb"> Namespace A.B End Namespace Namespace C End Namespace </file> </compilation>, options:=TestOptions.ReleaseExe.WithRootNamespace("Goo.Bar")) Dim globalNS = compilation.SourceModule.GlobalNamespace Assert.Equal("", globalNS.Name) Assert.Equal(SymbolKind.Namespace, globalNS.Kind) Assert.Equal(1, globalNS.GetMembers().Length()) Dim members = globalNS.GetMembers() Dim nsGoo As NamespaceSymbol = DirectCast(members.First(), NamespaceSymbol) Assert.Equal("Goo", nsGoo.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.Namespace, nsGoo.Kind) Assert.Equal(1, nsGoo.GetMembers().Length()) Dim membersGoo = nsGoo.GetMembers() Dim nsBar As NamespaceSymbol = DirectCast(membersGoo.First(), NamespaceSymbol) Assert.Equal("Bar", nsBar.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.Namespace, nsBar.Kind) Assert.Equal(3, nsBar.GetMembers().Length()) Dim membersBar = nsBar.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name, IdentifierComparison.Comparer).ToArray() Dim membersA = nsBar.GetMembers("a") Dim membersC = nsBar.GetMembers("c") Dim membersE = nsBar.GetMembers("E") Assert.Equal(3, membersBar.Length) Assert.Equal(1, membersA.Length) Assert.Equal(1, membersC.Length) Assert.Equal(1, membersE.Length) Assert.True(membersBar.SequenceEqual(membersA.Concat(membersC).Concat(membersE).AsEnumerable())) Assert.Equal("a", membersA.First().Name, IdentifierComparison.Comparer) Assert.Equal("C", membersC.First().Name, IdentifierComparison.Comparer) Assert.Equal("E", membersE.First().Name, IdentifierComparison.Comparer) Dim nsA As NamespaceSymbol = DirectCast(membersA.First(), NamespaceSymbol) Assert.Equal("A", nsA.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.Namespace, nsA.Kind) Assert.Equal(1, nsA.GetMembers().Length()) Dim nsB As NamespaceSymbol = DirectCast(nsA.GetMembers().First(), NamespaceSymbol) Assert.Equal("B", nsB.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.Namespace, nsB.Kind) Assert.Equal(0, nsB.GetMembers().Length()) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub ' Check namespace symbol containers in the presence of a root namespace <Fact> Public Sub NSContainersWithRootNamespace() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Class Type1 End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithRootNamespace("Goo.Bar")) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim members = globalNS.GetMembers() Dim nsGoo As NamespaceSymbol = DirectCast(members.First(), NamespaceSymbol) Dim membersGoo = nsGoo.GetMembers() Dim nsBar As NamespaceSymbol = DirectCast(membersGoo.First(), NamespaceSymbol) Dim type1Sym = nsBar.GetMembers("Type1").Single() Assert.Same(nsBar, type1Sym.ContainingSymbol) Assert.Same(nsGoo, nsBar.ContainingSymbol) Assert.Same(globalNS, nsGoo.ContainingSymbol) Assert.Same(compilation.SourceModule, globalNS.ContainingSymbol) End Sub ' Check namespace symbol containers in the presence of a root namespace <Fact> Public Sub NSContainersWithoutRootNamespace() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Class Type1 End Class </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim type1Sym = globalNS.GetMembers("Type1").Single() Assert.Same(globalNS, type1Sym.ContainingSymbol) Assert.Same(compilation.SourceModule, globalNS.ContainingSymbol) End Sub <Fact> Public Sub ImportsAlias01() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Test"> <file name="a.vb"> Imports ALS = N1.N2 Namespace N1 Namespace N2 Public Class A Sub S() End Sub End Class End Namespace End Namespace Namespace N3 Public Class B Inherits ALS.A End Class End Namespace </file> <file name="b.vb"> Imports ANO = N3 Namespace N1.N2 Class C Inherits ANO.B End Class End Namespace </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim n3 = DirectCast(globalNS.GetMembers("N3").Single(), NamespaceSymbol) Dim mem1 = DirectCast(n3.GetTypeMembers("B").Single(), NamedTypeSymbol) Assert.Equal("A", mem1.BaseType.Name) Assert.Equal("N1.N2.A", mem1.BaseType.ToTestDisplayString()) Dim n1 = DirectCast(globalNS.GetMembers("N1").Single(), NamespaceSymbol) Dim n2 = DirectCast(n1.GetMembers("N2").Single(), NamespaceSymbol) Dim mem2 = DirectCast(n2.GetTypeMembers("C").Single(), NamedTypeSymbol) Assert.Equal("B", mem2.BaseType.Name) Assert.Equal("N3.B", mem2.BaseType.ToTestDisplayString()) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <Fact, WorkItem(544009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544009")> Public Sub MultiModulesNamespace() Dim text3 = <![CDATA[ Namespace N1 Structure SGoo End Structure End Namespace ]]>.Value Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Test1"> <file name="a.vb"> Namespace N1 Class CGoo End Class End Namespace </file> </compilation>) Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Test2"> <file name="b.vb"> Namespace N1 Interface IGoo End Interface End Namespace </file> </compilation>) Dim compRef1 = New VisualBasicCompilationReference(comp1) Dim compRef2 = New VisualBasicCompilationReference(comp2) Dim comp = VisualBasicCompilation.Create("Test3", {VisualBasicSyntaxTree.ParseText(text3)}, {MscorlibRef, compRef1, compRef2}) Dim globalNS = comp.GlobalNamespace Dim ns = DirectCast(globalNS.GetMembers("N1").Single(), NamespaceSymbol) Assert.Equal(3, ns.GetTypeMembers().Length()) Dim ext = ns.Extent Assert.Equal(NamespaceKind.Compilation, ext.Kind) Assert.Equal("Compilation: " & GetType(VisualBasicCompilation).FullName, ext.ToString()) Dim constituents = ns.ConstituentNamespaces Assert.Equal(3, constituents.Length) Assert.True(constituents.Contains(TryCast(comp.SourceAssembly.GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol))) Assert.True(constituents.Contains(TryCast(comp.GetReferencedAssemblySymbol(compRef1).GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol))) Assert.True(constituents.Contains(TryCast(comp.GetReferencedAssemblySymbol(compRef2).GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol))) For Each constituentNs In constituents Assert.Equal(NamespaceKind.Module, constituentNs.Extent.Kind) Assert.Equal(ns.ToTestDisplayString(), constituentNs.ToTestDisplayString()) Next End Sub <WorkItem(537310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537310")> <Fact> Public Sub MultiModulesNamespaceCorLibraries() Dim text1 = <![CDATA[ Namespace N1 Class CGoo End Class End Namespace ]]>.Value Dim text2 = <![CDATA[ Namespace N1 Interface IGoo End Interface End Namespace ]]>.Value Dim text3 = <![CDATA[ Namespace N1 Structure SGoo End Structure End Namespace ]]>.Value Dim comp1 = VisualBasicCompilation.Create("Test1", syntaxTrees:={VisualBasicSyntaxTree.ParseText(text1)}) Dim comp2 = VisualBasicCompilation.Create("Test2", syntaxTrees:={VisualBasicSyntaxTree.ParseText(text2)}) Dim compRef1 = New VisualBasicCompilationReference(comp1) Dim compRef2 = New VisualBasicCompilationReference(comp2) Dim comp = VisualBasicCompilation.Create("Test3", {VisualBasicSyntaxTree.ParseText(text3)}, {compRef1, compRef2}) Dim globalNS = comp.GlobalNamespace Dim ns = DirectCast(globalNS.GetMembers("N1").Single(), NamespaceSymbol) Assert.Equal(3, ns.GetTypeMembers().Length()) Assert.Equal(NamespaceKind.Compilation, ns.Extent.Kind) Dim constituents = ns.ConstituentNamespaces Assert.Equal(3, constituents.Length) Assert.True(constituents.Contains(TryCast(comp.SourceAssembly.GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol))) Assert.True(constituents.Contains(TryCast(comp.GetReferencedAssemblySymbol(compRef1).GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol))) Assert.True(constituents.Contains(TryCast(comp.GetReferencedAssemblySymbol(compRef2).GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol))) For Each constituentNs In constituents Assert.Equal(NamespaceKind.Module, constituentNs.Extent.Kind) Assert.Equal(ns.ToTestDisplayString(), constituentNs.ToTestDisplayString()) Next End Sub <WorkItem(690871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/690871")> <Fact> Public Sub SpecialTypesAndAliases() Dim source = <compilation name="C"> <file> Public Class C End Class </file> </compilation> Dim aliasedCorlib = TestMetadata.Net451.mscorlib.WithAliases(ImmutableArray.Create("Goo")) Dim comp = CreateEmptyCompilationWithReferences(source, {aliasedCorlib}) ' NOTE: this doesn't compile in dev11 - it reports that it cannot find System.Object. ' However, we've already changed how special type lookup works, so this is not a major issue. comp.AssertNoDiagnostics() Dim objectType = comp.GetSpecialType(SpecialType.System_Object) Assert.Equal(TypeKind.Class, objectType.TypeKind) Assert.Equal("System.Object", objectType.ToTestDisplayString()) Assert.Equal(objectType, comp.Assembly.GetSpecialType(SpecialType.System_Object)) Assert.Equal(objectType, comp.Assembly.CorLibrary.GetSpecialType(SpecialType.System_Object)) End Sub <WorkItem(690871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/690871")> <Fact> Public Sub WellKnownTypesAndAliases() Dim [lib] = <compilation name="lib"> <file> Namespace System.Threading.Tasks Public Class Task Public Status As Integer End Class End Namespace </file> </compilation> Dim source = <compilation name="test"> <file> Imports System.Threading.Tasks Public Class App Public T as Task End Class </file> </compilation> Dim libComp = CreateEmptyCompilationWithReferences([lib], {MscorlibRef_v4_0_30316_17626}) Dim libRef = libComp.EmitToImageReference(aliases:=ImmutableArray.Create("myTask")) Dim comp = CreateEmptyCompilationWithReferences(source, {libRef, MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}) ' NOTE: Unlike in C#, aliases on metadata references are ignored, so the ' reference to System.Threading.Tasks is ambiguous. comp.AssertTheseDiagnostics( <expected> BC30560: 'Task' is ambiguous in the namespace 'System.Threading.Tasks'. Public T as Task ~~~~ </expected>) End Sub <Fact, WorkItem(54836, "https://github.com/dotnet/roslyn/issues/54836")> Public Sub RetargetableAttributeIsRespectedInSource() Dim code = <![CDATA[ Imports System.Reflection <Assembly: AssemblyFlags(AssemblyNameFlags.Retargetable)> ]]> Dim comp = CreateCompilation(code.Value) Assert.True(comp.Assembly.Identity.IsRetargetable) AssertTheseEmitDiagnostics(comp) End Sub End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/Progression/RoslynGraphProperties.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.GraphModel; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal static class RoslynGraphProperties { public static readonly GraphSchema Schema; /// <summary> /// A graph property that holds the SymbolId of the symbol. /// </summary> public static readonly GraphProperty SymbolId; /// <summary> /// A graph property that holds the ProjectId where you can find the symbol. Note this is /// not strictly the project that defines the symbol in the case the symbol is from metadata. /// It's simply a project that has a compilation which you can use to get to the symbol. /// </summary> public static readonly GraphProperty ContextProjectId; /// <summary> /// A graph property that holds the DocumentId where you can find the symbol. This is used /// to distinguish between multiple locations for partial types. This will only exist /// for symbols in source that have partial implementations. /// </summary> public static readonly GraphProperty ContextDocumentId; /// <summary> /// A graph property to hold the label we have generated for the node. /// </summary> public static readonly GraphProperty Label; /// <summary> /// A graph property to hold the formatted label we have generated for the node. /// </summary> public static readonly GraphProperty FormattedLabelWithoutContainingSymbol; /// <summary> /// A graph property to hold the formatted label that has the containing symbol name. /// </summary> public static readonly GraphProperty FormattedLabelWithContainingSymbol; /// <summary> /// A graph property to hold the description we have generated for the node. /// </summary> public static readonly GraphProperty Description; /// <summary> /// A graph property to hold the description that has the containing symbol name. /// </summary> public static readonly GraphProperty DescriptionWithContainingSymbol; public static readonly GraphProperty SymbolKind; public static readonly GraphProperty TypeKind; public static readonly GraphProperty MethodKind; public static readonly GraphProperty DeclaredAccessibility; public static readonly GraphProperty SymbolModifiers; public static readonly GraphProperty ExplicitInterfaceImplementations; static RoslynGraphProperties() { Schema = new GraphSchema("Roslyn"); SymbolKind = Schema.Properties.AddNewProperty( id: "SymbolKind", dataType: typeof(SymbolKind), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); TypeKind = Schema.Properties.AddNewProperty( id: "TypeKind", dataType: typeof(TypeKind), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); MethodKind = Schema.Properties.AddNewProperty( id: "MethodKind", dataType: typeof(MethodKind), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); DeclaredAccessibility = Schema.Properties.AddNewProperty( id: "DeclaredAccessibility", dataType: typeof(Accessibility), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); SymbolModifiers = Schema.Properties.AddNewProperty( id: "SymbolModifiers", dataType: typeof(DeclarationModifiers), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); ExplicitInterfaceImplementations = Schema.Properties.AddNewProperty( id: "ExplicitInterfaceImplementations", dataType: typeof(IList<SymbolKey>), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); SymbolId = Schema.Properties.AddNewProperty( id: "SymbolId", dataType: typeof(SymbolKey?), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); ContextProjectId = Schema.Properties.AddNewProperty( id: "ContextProjectId", dataType: typeof(ProjectId), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); ContextDocumentId = Schema.Properties.AddNewProperty( id: "ContextDocumentId", dataType: typeof(DocumentId), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); Label = Schema.Properties.AddNewProperty( id: "Label", dataType: typeof(string), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); FormattedLabelWithoutContainingSymbol = Schema.Properties.AddNewProperty( id: "FormattedLabelWithoutContainingSymbol", dataType: typeof(string), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); FormattedLabelWithContainingSymbol = Schema.Properties.AddNewProperty( id: "FormattedLabelWithContainingSymbol", dataType: typeof(string), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); Description = Schema.Properties.AddNewProperty( id: "Description", dataType: typeof(string), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); DescriptionWithContainingSymbol = Schema.Properties.AddNewProperty( id: "DescriptionWithContainingSymbol", dataType: typeof(string), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.GraphModel; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal static class RoslynGraphProperties { public static readonly GraphSchema Schema; /// <summary> /// A graph property that holds the SymbolId of the symbol. /// </summary> public static readonly GraphProperty SymbolId; /// <summary> /// A graph property that holds the ProjectId where you can find the symbol. Note this is /// not strictly the project that defines the symbol in the case the symbol is from metadata. /// It's simply a project that has a compilation which you can use to get to the symbol. /// </summary> public static readonly GraphProperty ContextProjectId; /// <summary> /// A graph property that holds the DocumentId where you can find the symbol. This is used /// to distinguish between multiple locations for partial types. This will only exist /// for symbols in source that have partial implementations. /// </summary> public static readonly GraphProperty ContextDocumentId; /// <summary> /// A graph property to hold the label we have generated for the node. /// </summary> public static readonly GraphProperty Label; /// <summary> /// A graph property to hold the formatted label we have generated for the node. /// </summary> public static readonly GraphProperty FormattedLabelWithoutContainingSymbol; /// <summary> /// A graph property to hold the formatted label that has the containing symbol name. /// </summary> public static readonly GraphProperty FormattedLabelWithContainingSymbol; /// <summary> /// A graph property to hold the description we have generated for the node. /// </summary> public static readonly GraphProperty Description; /// <summary> /// A graph property to hold the description that has the containing symbol name. /// </summary> public static readonly GraphProperty DescriptionWithContainingSymbol; public static readonly GraphProperty SymbolKind; public static readonly GraphProperty TypeKind; public static readonly GraphProperty MethodKind; public static readonly GraphProperty DeclaredAccessibility; public static readonly GraphProperty SymbolModifiers; public static readonly GraphProperty ExplicitInterfaceImplementations; static RoslynGraphProperties() { Schema = new GraphSchema("Roslyn"); SymbolKind = Schema.Properties.AddNewProperty( id: "SymbolKind", dataType: typeof(SymbolKind), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); TypeKind = Schema.Properties.AddNewProperty( id: "TypeKind", dataType: typeof(TypeKind), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); MethodKind = Schema.Properties.AddNewProperty( id: "MethodKind", dataType: typeof(MethodKind), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); DeclaredAccessibility = Schema.Properties.AddNewProperty( id: "DeclaredAccessibility", dataType: typeof(Accessibility), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); SymbolModifiers = Schema.Properties.AddNewProperty( id: "SymbolModifiers", dataType: typeof(DeclarationModifiers), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); ExplicitInterfaceImplementations = Schema.Properties.AddNewProperty( id: "ExplicitInterfaceImplementations", dataType: typeof(IList<SymbolKey>), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); SymbolId = Schema.Properties.AddNewProperty( id: "SymbolId", dataType: typeof(SymbolKey?), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); ContextProjectId = Schema.Properties.AddNewProperty( id: "ContextProjectId", dataType: typeof(ProjectId), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); ContextDocumentId = Schema.Properties.AddNewProperty( id: "ContextDocumentId", dataType: typeof(DocumentId), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); Label = Schema.Properties.AddNewProperty( id: "Label", dataType: typeof(string), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); FormattedLabelWithoutContainingSymbol = Schema.Properties.AddNewProperty( id: "FormattedLabelWithoutContainingSymbol", dataType: typeof(string), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); FormattedLabelWithContainingSymbol = Schema.Properties.AddNewProperty( id: "FormattedLabelWithContainingSymbol", dataType: typeof(string), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); Description = Schema.Properties.AddNewProperty( id: "Description", dataType: typeof(string), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); DescriptionWithContainingSymbol = Schema.Properties.AddNewProperty( id: "DescriptionWithContainingSymbol", dataType: typeof(string), callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable)); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/Emit/AsyncMoveNextBodyDebugInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Emit { /// <summary> /// Represents additional info needed by async method implementation methods /// (MoveNext methods) to properly emit necessary PDB data for async debugging. /// </summary> internal sealed class AsyncMoveNextBodyDebugInfo : StateMachineMoveNextBodyDebugInfo { /// <summary> /// IL offset of catch handler or -1 /// </summary> public readonly int CatchHandlerOffset; /// <summary> /// Set of IL offsets where await operators yield control /// </summary> public readonly ImmutableArray<int> YieldOffsets; /// <summary> /// Set of IL offsets where await operators are to be resumed /// </summary> public readonly ImmutableArray<int> ResumeOffsets; public AsyncMoveNextBodyDebugInfo( Cci.IMethodDefinition kickoffMethod, int catchHandlerOffset, ImmutableArray<int> yieldOffsets, ImmutableArray<int> resumeOffsets) : base(kickoffMethod) { Debug.Assert(!yieldOffsets.IsDefault); Debug.Assert(!resumeOffsets.IsDefault); Debug.Assert(yieldOffsets.Length == resumeOffsets.Length); CatchHandlerOffset = catchHandlerOffset; YieldOffsets = yieldOffsets; ResumeOffsets = resumeOffsets; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Emit { /// <summary> /// Represents additional info needed by async method implementation methods /// (MoveNext methods) to properly emit necessary PDB data for async debugging. /// </summary> internal sealed class AsyncMoveNextBodyDebugInfo : StateMachineMoveNextBodyDebugInfo { /// <summary> /// IL offset of catch handler or -1 /// </summary> public readonly int CatchHandlerOffset; /// <summary> /// Set of IL offsets where await operators yield control /// </summary> public readonly ImmutableArray<int> YieldOffsets; /// <summary> /// Set of IL offsets where await operators are to be resumed /// </summary> public readonly ImmutableArray<int> ResumeOffsets; public AsyncMoveNextBodyDebugInfo( Cci.IMethodDefinition kickoffMethod, int catchHandlerOffset, ImmutableArray<int> yieldOffsets, ImmutableArray<int> resumeOffsets) : base(kickoffMethod) { Debug.Assert(!yieldOffsets.IsDefault); Debug.Assert(!resumeOffsets.IsDefault); Debug.Assert(yieldOffsets.Length == resumeOffsets.Length); CatchHandlerOffset = catchHandlerOffset; YieldOffsets = yieldOffsets; ResumeOffsets = resumeOffsets; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/CSharp/Impl/CodeModel/ModifierFlags.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.VisualStudio.LanguageServices.CSharp.CodeModel { [Flags] internal enum ModifierFlags { // Note: These are in the order that they appear in modifier lists as generated by Code Model. Public = 1 << 0, Protected = 1 << 1, Internal = 1 << 2, Private = 1 << 3, Virtual = 1 << 4, Abstract = 1 << 5, New = 1 << 6, Override = 1 << 7, Sealed = 1 << 8, Static = 1 << 9, Extern = 1 << 10, Volatile = 1 << 11, ReadOnly = 1 << 12, Const = 1 << 13, Unsafe = 1 << 14, Async = 1 << 15, Partial = 1 << 16, AccessModifierMask = Private | Protected | Internal | Public } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.VisualStudio.LanguageServices.CSharp.CodeModel { [Flags] internal enum ModifierFlags { // Note: These are in the order that they appear in modifier lists as generated by Code Model. Public = 1 << 0, Protected = 1 << 1, Internal = 1 << 2, Private = 1 << 3, Virtual = 1 << 4, Abstract = 1 << 5, New = 1 << 6, Override = 1 << 7, Sealed = 1 << 8, Static = 1 << 9, Extern = 1 << 10, Volatile = 1 << 11, ReadOnly = 1 << 12, Const = 1 << 13, Unsafe = 1 << 14, Async = 1 << 15, Partial = 1 << 16, AccessModifierMask = Private | Protected | Internal | Public } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/CodeGen/LocalDebugId.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// Id that associates an emitted user-defined or long-lived synthesized local variable /// with a syntax node that defined it. If a syntax node defines multiple variables it /// provides information necessary to identify which one of these variables is it. /// </summary> internal struct LocalDebugId : IEquatable<LocalDebugId> { /// <summary> /// We calculate a "syntax offset" for each user-defined and long-lived synthesized variable. /// Every such variable symbol has to be associated with a syntax node (its declarator). /// In usual cases this is the textual distance of the declarator from the start of the method body. /// It gets a bit complicated when the containing method body is not contiguous (constructors). /// If the variable is in the body of the constructor the definition of syntax offset is the same. /// If the variable is defined in a constructor initializer or in a member initializer /// (this is only possible when declaration expressions or closures in primary constructors are involved) /// then the distance is a negative sum of the widths of all the initializers that succeed the declarator /// of the variable in the emitted constructor body plus the relative offset of the declarator from /// the start of the containing initializer. /// </summary> public readonly int SyntaxOffset; /// <summary> /// If a single node is a declarator for multiple variables of the same synthesized kind (it can only happen for synthesized variables) /// we calculate additional number "ordinal" for such variable. We assign the ordinals to the synthesized variables with the same kind /// and syntax offset in the order as they appear in the lowered bound tree. It is important that a valid EnC edit can't change /// the ordinal of a synthesized variable. If it could it would need to be assigned a different kind or associated with a different declarator node. /// </summary> public readonly int Ordinal; public static readonly LocalDebugId None = new LocalDebugId(isNone: true); private LocalDebugId(bool isNone) { Debug.Assert(isNone); this.SyntaxOffset = -1; this.Ordinal = -1; } public LocalDebugId(int syntaxOffset, int ordinal = 0) { Debug.Assert(ordinal >= 0); this.SyntaxOffset = syntaxOffset; this.Ordinal = ordinal; } public bool IsNone { get { return Ordinal == -1; } } public bool Equals(LocalDebugId other) { return SyntaxOffset == other.SyntaxOffset && Ordinal == other.Ordinal; } public override int GetHashCode() { return Hash.Combine(SyntaxOffset, Ordinal); } public override bool Equals(object? obj) { return obj is LocalDebugId && Equals((LocalDebugId)obj); } public override string ToString() { return SyntaxOffset + ":" + Ordinal; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// Id that associates an emitted user-defined or long-lived synthesized local variable /// with a syntax node that defined it. If a syntax node defines multiple variables it /// provides information necessary to identify which one of these variables is it. /// </summary> internal struct LocalDebugId : IEquatable<LocalDebugId> { /// <summary> /// We calculate a "syntax offset" for each user-defined and long-lived synthesized variable. /// Every such variable symbol has to be associated with a syntax node (its declarator). /// In usual cases this is the textual distance of the declarator from the start of the method body. /// It gets a bit complicated when the containing method body is not contiguous (constructors). /// If the variable is in the body of the constructor the definition of syntax offset is the same. /// If the variable is defined in a constructor initializer or in a member initializer /// (this is only possible when declaration expressions or closures in primary constructors are involved) /// then the distance is a negative sum of the widths of all the initializers that succeed the declarator /// of the variable in the emitted constructor body plus the relative offset of the declarator from /// the start of the containing initializer. /// </summary> public readonly int SyntaxOffset; /// <summary> /// If a single node is a declarator for multiple variables of the same synthesized kind (it can only happen for synthesized variables) /// we calculate additional number "ordinal" for such variable. We assign the ordinals to the synthesized variables with the same kind /// and syntax offset in the order as they appear in the lowered bound tree. It is important that a valid EnC edit can't change /// the ordinal of a synthesized variable. If it could it would need to be assigned a different kind or associated with a different declarator node. /// </summary> public readonly int Ordinal; public static readonly LocalDebugId None = new LocalDebugId(isNone: true); private LocalDebugId(bool isNone) { Debug.Assert(isNone); this.SyntaxOffset = -1; this.Ordinal = -1; } public LocalDebugId(int syntaxOffset, int ordinal = 0) { Debug.Assert(ordinal >= 0); this.SyntaxOffset = syntaxOffset; this.Ordinal = ordinal; } public bool IsNone { get { return Ordinal == -1; } } public bool Equals(LocalDebugId other) { return SyntaxOffset == other.SyntaxOffset && Ordinal == other.Ordinal; } public override int GetHashCode() { return Hash.Combine(SyntaxOffset, Ordinal); } public override bool Equals(object? obj) { return obj is LocalDebugId && Equals((LocalDebugId)obj); } public override string ToString() { return SyntaxOffset + ":" + Ordinal; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Test/Symbol/Symbols/ImplicitClassTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ImplicitClassTests : CSharpTestBase { [Fact] public void ImplicitClassSymbol() { var c = CreateEmptyCompilation(@" namespace N { void Goo() { } } ", new[] { MscorlibRef }); var n = ((NamespaceSymbol)c.Assembly.GlobalNamespace.GetMembers("N").Single()); var implicitClass = ((NamedTypeSymbol)n.GetMembers().Single()); Assert.Equal(0, implicitClass.GetAttributes().Length); Assert.Equal(0, implicitClass.Interfaces().Length); Assert.Equal(c.ObjectType, implicitClass.BaseType()); Assert.Equal(0, implicitClass.Arity); Assert.True(implicitClass.IsImplicitlyDeclared); Assert.Equal(SyntaxKind.NamespaceDeclaration, implicitClass.DeclaringSyntaxReferences.Single().GetSyntax().Kind()); Assert.False(implicitClass.IsSubmissionClass); Assert.False(implicitClass.IsScriptClass); var c2 = CreateCompilationWithMscorlib45("", new[] { c.ToMetadataReference() }); n = ((NamespaceSymbol)c2.GlobalNamespace.GetMembers("N").Single()); implicitClass = ((NamedTypeSymbol)n.GetMembers().Single()); Assert.IsType<CSharp.Symbols.Retargeting.RetargetingNamedTypeSymbol>(implicitClass); Assert.Equal(0, implicitClass.Interfaces().Length); Assert.Equal(c2.ObjectType, implicitClass.BaseType()); } [Fact] public void ScriptClassSymbol() { var c = CreateCompilation(@" base.ToString(); void Goo() { } ", parseOptions: TestOptions.Script); var scriptClass = (NamedTypeSymbol)c.Assembly.GlobalNamespace.GetMember("Script"); Assert.Equal(0, scriptClass.GetAttributes().Length); Assert.Equal(0, scriptClass.Interfaces().Length); Assert.Null(scriptClass.BaseType()); Assert.Equal(0, scriptClass.Arity); Assert.True(scriptClass.IsImplicitlyDeclared); Assert.Equal(SyntaxKind.CompilationUnit, scriptClass.DeclaringSyntaxReferences.Single().GetSyntax().Kind()); Assert.False(scriptClass.IsSubmissionClass); Assert.True(scriptClass.IsScriptClass); var tree = c.SyntaxTrees.Single(); var model = c.GetSemanticModel(tree); IEnumerable<IdentifierNameSyntax> identifiers = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>(); var toStringIdentifier = identifiers.Where(node => node.Identifier.ValueText.Equals("ToString")).Single(); Assert.Null(model.GetSymbolInfo(toStringIdentifier).Symbol); } [Fact, WorkItem(531535, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531535")] public void Events() { var c = CreateCompilationWithMscorlib45(@" event System.Action e; ", parseOptions: TestOptions.Script); c.VerifyDiagnostics(); var @event = c.ScriptClass.GetMember<EventSymbol>("e"); Assert.False(@event.TypeWithAnnotations.IsDefault); } [WorkItem(598860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598860")] [Fact] public void AliasQualifiedNamespaceName() { var comp = CreateCompilation(@" namespace N::A { void Goo() { } } "); // Used to assert. comp.VerifyDiagnostics( // (2,11): error CS7000: Unexpected use of an aliased name // namespace N::A Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "N::A"), // (4,10): error CS0116: A namespace does not directly contain members such as fields or methods // void Goo() Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "Goo")); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var namespaceDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<NamespaceDeclarationSyntax>().Single(); var methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.Equal("A", model.GetDeclaredSymbol(namespaceDecl).Name); Assert.Equal("Goo", model.GetDeclaredSymbol(methodDecl).Name); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ImplicitClassTests : CSharpTestBase { [Fact] public void ImplicitClassSymbol() { var c = CreateEmptyCompilation(@" namespace N { void Goo() { } } ", new[] { MscorlibRef }); var n = ((NamespaceSymbol)c.Assembly.GlobalNamespace.GetMembers("N").Single()); var implicitClass = ((NamedTypeSymbol)n.GetMembers().Single()); Assert.Equal(0, implicitClass.GetAttributes().Length); Assert.Equal(0, implicitClass.Interfaces().Length); Assert.Equal(c.ObjectType, implicitClass.BaseType()); Assert.Equal(0, implicitClass.Arity); Assert.True(implicitClass.IsImplicitlyDeclared); Assert.Equal(SyntaxKind.NamespaceDeclaration, implicitClass.DeclaringSyntaxReferences.Single().GetSyntax().Kind()); Assert.False(implicitClass.IsSubmissionClass); Assert.False(implicitClass.IsScriptClass); var c2 = CreateCompilationWithMscorlib45("", new[] { c.ToMetadataReference() }); n = ((NamespaceSymbol)c2.GlobalNamespace.GetMembers("N").Single()); implicitClass = ((NamedTypeSymbol)n.GetMembers().Single()); Assert.IsType<CSharp.Symbols.Retargeting.RetargetingNamedTypeSymbol>(implicitClass); Assert.Equal(0, implicitClass.Interfaces().Length); Assert.Equal(c2.ObjectType, implicitClass.BaseType()); } [Fact] public void ScriptClassSymbol() { var c = CreateCompilation(@" base.ToString(); void Goo() { } ", parseOptions: TestOptions.Script); var scriptClass = (NamedTypeSymbol)c.Assembly.GlobalNamespace.GetMember("Script"); Assert.Equal(0, scriptClass.GetAttributes().Length); Assert.Equal(0, scriptClass.Interfaces().Length); Assert.Null(scriptClass.BaseType()); Assert.Equal(0, scriptClass.Arity); Assert.True(scriptClass.IsImplicitlyDeclared); Assert.Equal(SyntaxKind.CompilationUnit, scriptClass.DeclaringSyntaxReferences.Single().GetSyntax().Kind()); Assert.False(scriptClass.IsSubmissionClass); Assert.True(scriptClass.IsScriptClass); var tree = c.SyntaxTrees.Single(); var model = c.GetSemanticModel(tree); IEnumerable<IdentifierNameSyntax> identifiers = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>(); var toStringIdentifier = identifiers.Where(node => node.Identifier.ValueText.Equals("ToString")).Single(); Assert.Null(model.GetSymbolInfo(toStringIdentifier).Symbol); } [Fact, WorkItem(531535, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531535")] public void Events() { var c = CreateCompilationWithMscorlib45(@" event System.Action e; ", parseOptions: TestOptions.Script); c.VerifyDiagnostics(); var @event = c.ScriptClass.GetMember<EventSymbol>("e"); Assert.False(@event.TypeWithAnnotations.IsDefault); } [WorkItem(598860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598860")] [Fact] public void AliasQualifiedNamespaceName() { var comp = CreateCompilation(@" namespace N::A { void Goo() { } } "); // Used to assert. comp.VerifyDiagnostics( // (2,11): error CS7000: Unexpected use of an aliased name // namespace N::A Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "N::A"), // (4,10): error CS0116: A namespace does not directly contain members such as fields or methods // void Goo() Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "Goo")); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var namespaceDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<NamespaceDeclarationSyntax>().Single(); var methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.Equal("A", model.GetDeclaredSymbol(namespaceDecl).Name); Assert.Equal("Goo", model.GetDeclaredSymbol(methodDecl).Name); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/Symbols/IPropertySymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a property or indexer. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IPropertySymbol : ISymbol { /// <summary> /// Returns whether the property is really an indexer. /// </summary> bool IsIndexer { get; } /// <summary> /// True if this is a read-only property; that is, a property with no set accessor. /// </summary> bool IsReadOnly { get; } /// <summary> /// True if this is a write-only property; that is, a property with no get accessor. /// </summary> bool IsWriteOnly { get; } /// <summary> /// True if this property is required to be set in an object initializer during construction. /// </summary> bool IsRequired { get; } /// <summary> /// Returns true if this property is an auto-created WithEvents property that takes place of /// a field member when the field is marked as WithEvents. /// </summary> bool IsWithEvents { get; } /// <summary> /// Returns true if this property returns by reference. /// </summary> bool ReturnsByRef { get; } /// <summary> /// Returns true if this property returns by reference a readonly variable. /// </summary> bool ReturnsByRefReadonly { get; } /// <summary> /// Returns the RefKind of the property. /// </summary> RefKind RefKind { get; } /// <summary> /// The type of the property. /// </summary> ITypeSymbol Type { get; } NullableAnnotation NullableAnnotation { get; } /// <summary> /// The parameters of this property. If this property has no parameters, returns /// an empty list. Parameters are only present on indexers, or on some properties /// imported from a COM interface. /// </summary> ImmutableArray<IParameterSymbol> Parameters { get; } /// <summary> /// The 'get' accessor of the property, or null if the property is write-only. /// </summary> IMethodSymbol? GetMethod { get; } /// <summary> /// The 'set' accessor of the property, or null if the property is read-only. /// </summary> IMethodSymbol? SetMethod { get; } /// <summary> /// The original definition of the property. If the property is constructed from another /// symbol by type substitution, OriginalDefinition gets the original symbol, as it was /// defined in source or metadata. /// </summary> new IPropertySymbol OriginalDefinition { get; } /// <summary> /// Returns the overridden property, or null. /// </summary> IPropertySymbol? OverriddenProperty { get; } /// <summary> /// Returns interface properties explicitly implemented by this property. /// </summary> /// <remarks> /// Properties imported from metadata can explicitly implement more than one property. /// </remarks> ImmutableArray<IPropertySymbol> ExplicitInterfaceImplementations { get; } /// <summary> /// Custom modifiers associated with the ref modifier, or an empty array if there are none. /// </summary> ImmutableArray<CustomModifier> RefCustomModifiers { get; } /// <summary> /// The list of custom modifiers, if any, associated with the type of the property. /// </summary> ImmutableArray<CustomModifier> TypeCustomModifiers { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a property or indexer. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IPropertySymbol : ISymbol { /// <summary> /// Returns whether the property is really an indexer. /// </summary> bool IsIndexer { get; } /// <summary> /// True if this is a read-only property; that is, a property with no set accessor. /// </summary> bool IsReadOnly { get; } /// <summary> /// True if this is a write-only property; that is, a property with no get accessor. /// </summary> bool IsWriteOnly { get; } /// <summary> /// True if this property is required to be set in an object initializer during construction. /// </summary> bool IsRequired { get; } /// <summary> /// Returns true if this property is an auto-created WithEvents property that takes place of /// a field member when the field is marked as WithEvents. /// </summary> bool IsWithEvents { get; } /// <summary> /// Returns true if this property returns by reference. /// </summary> bool ReturnsByRef { get; } /// <summary> /// Returns true if this property returns by reference a readonly variable. /// </summary> bool ReturnsByRefReadonly { get; } /// <summary> /// Returns the RefKind of the property. /// </summary> RefKind RefKind { get; } /// <summary> /// The type of the property. /// </summary> ITypeSymbol Type { get; } NullableAnnotation NullableAnnotation { get; } /// <summary> /// The parameters of this property. If this property has no parameters, returns /// an empty list. Parameters are only present on indexers, or on some properties /// imported from a COM interface. /// </summary> ImmutableArray<IParameterSymbol> Parameters { get; } /// <summary> /// The 'get' accessor of the property, or null if the property is write-only. /// </summary> IMethodSymbol? GetMethod { get; } /// <summary> /// The 'set' accessor of the property, or null if the property is read-only. /// </summary> IMethodSymbol? SetMethod { get; } /// <summary> /// The original definition of the property. If the property is constructed from another /// symbol by type substitution, OriginalDefinition gets the original symbol, as it was /// defined in source or metadata. /// </summary> new IPropertySymbol OriginalDefinition { get; } /// <summary> /// Returns the overridden property, or null. /// </summary> IPropertySymbol? OverriddenProperty { get; } /// <summary> /// Returns interface properties explicitly implemented by this property. /// </summary> /// <remarks> /// Properties imported from metadata can explicitly implement more than one property. /// </remarks> ImmutableArray<IPropertySymbol> ExplicitInterfaceImplementations { get; } /// <summary> /// Custom modifiers associated with the ref modifier, or an empty array if there are none. /// </summary> ImmutableArray<CustomModifier> RefCustomModifiers { get; } /// <summary> /// The list of custom modifiers, if any, associated with the type of the property. /// </summary> ImmutableArray<CustomModifier> TypeCustomModifiers { get; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/VisualBasic/Portable/Parser/BlockContexts/ExecutableStatementContext.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax '----------------------------------------------------------------------------- ' Contains the definition of the ExecutableStatementContext. The base class ' for all blocks that contain statements. '----------------------------------------------------------------------------- Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend MustInherit Class ExecutableStatementContext Inherits DeclarationContext Friend Sub New(contextKind As SyntaxKind, statement As StatementSyntax, prevContext As BlockContext) MyBase.New(contextKind, statement, prevContext) End Sub Friend NotOverridable Overrides Function Parse() As StatementSyntax Return Parser.ParseStatementInMethodBody() End Function Friend Overrides Function ProcessSyntax(node As VisualBasicSyntaxNode) As BlockContext If Parser.IsDeclarationStatement(node.Kind) Then ' VS 314714 ' When we have specifiers or attributes preceding an invalid method declaration, ' we want an error of ERRID_InvInsideEndsProc reported, so that this file is decompiled ' to no state. This will remove the task list error (no state) added in FindEndProc. ' Without this fix, an invalid identifier error will be reported, and the file will ' not decompile far enough. The task list error will incorrectly stay around. ' ' Note: This bug addresses the requirement that this method (ParseStatementInMethodBody) ' should report ERRID_InvInsideEndsProc in exactly the same cases that FindEndProc ' does 'End the current block and add the block to the context above 'This must end not only the current block but the current method. Dim declarationContext = FindNearest(Function(s) SyntaxFacts.IsMethodBlock(s) OrElse s = SyntaxKind.ConstructorBlock OrElse s = SyntaxKind.OperatorBlock OrElse SyntaxFacts.IsAccessorBlock(s)) If declarationContext IsNot Nothing Then Dim context = declarationContext.PrevBlock RecoverFromMissingEnd(context) 'Let the outer context process this statement Return context.ProcessSyntax(Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideEndsProc)) Else ' we are in a block in a top-level code: node = Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideBlock, SyntaxFacts.GetBlockName(BlockKind)) Return MyBase.ProcessSyntax(node) End If Else Select Case node.Kind Case _ SyntaxKind.InheritsStatement, SyntaxKind.ImplementsStatement, SyntaxKind.OptionStatement, SyntaxKind.ImportsStatement Dim declarationContext = FindNearest(Function(s) SyntaxFacts.IsMethodBlock(s) OrElse s = SyntaxKind.ConstructorBlock OrElse s = SyntaxKind.OperatorBlock OrElse SyntaxFacts.IsAccessorBlock(s) OrElse SyntaxFacts.IsMultiLineLambdaExpression(s) OrElse SyntaxFacts.IsSingleLineLambdaExpression(s)) If declarationContext IsNot Nothing Then ' in a method or multiline lambda expression: node = Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideProc) Else ' we are in a block or in top-level code: node = Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideBlock, SyntaxFacts.GetBlockName(BlockKind)) End If Add(node) Return Me Case Else Dim newContext = TryProcessExecutableStatement(node) Return If(newContext, MyBase.ProcessSyntax(node)) End Select End If End Function Friend Overrides Function TryLinkSyntax(node As VisualBasicSyntaxNode, ByRef newContext As BlockContext) As LinkResult newContext = Nothing Select Case node.Kind ' these are errors, but ParseStatementInMethodBody accepts them for error recovery Case _ SyntaxKind.OptionStatement, SyntaxKind.ImportsStatement, SyntaxKind.InheritsStatement, SyntaxKind.ImplementsStatement, SyntaxKind.NamespaceStatement Return UseSyntax(node, newContext) Case _ SyntaxKind.ClassStatement, SyntaxKind.StructureStatement, SyntaxKind.ModuleStatement, SyntaxKind.InterfaceStatement ' Reuse as long as the statement does not have modifiers. ' These statements parse differently when they appear at the top level and when they appear within a method body. ' Within a method body, if the statement begins with a modifier then the statement is parsed as a variable declaration (with an error). If Not DirectCast(node, TypeStatementSyntax).Modifiers.Any() Then Return UseSyntax(node, newContext) Else newContext = Me Return LinkResult.NotUsed End If Case SyntaxKind.EnumStatement ' Reuse as long as the statement does not have modifiers ' These statements parse differently when they appear at the top level and when they appear within a method body. ' Within a method body, if the statement begins with a modifier then the statement is parsed as a variable declaration (with an error). If Not DirectCast(node, EnumStatementSyntax).Modifiers.Any() Then Return UseSyntax(node, newContext) Else newContext = Me Return LinkResult.NotUsed End If Case _ SyntaxKind.SubNewStatement, SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement ' Reuse as long as the statement does not have modifiers ' These statements parse differently when they appear at the top level and when they appear within a method body. ' Within a method body, if the statement begins with a dim/const then the statement is parsed as a variable declaration (with an error). If Not DirectCast(node, MethodBaseSyntax).Modifiers.Any() Then Return UseSyntax(node, newContext) Else newContext = Me Return LinkResult.NotUsed End If Case _ SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.OperatorStatement, SyntaxKind.PropertyStatement, SyntaxKind.EventStatement ' Reuse as long as the statement does not have dim or const If Not DirectCast(node, MethodBaseSyntax).Modifiers.Any(SyntaxKind.DimKeyword, SyntaxKind.ConstKeyword) Then Return UseSyntax(node, newContext) Else newContext = Me Return LinkResult.NotUsed End If ' these blocks cannot happen in current context so we should crumble them ' on next pass we will give error on the first statement Case _ SyntaxKind.SubBlock, SyntaxKind.ConstructorBlock, SyntaxKind.FunctionBlock, SyntaxKind.OperatorBlock, SyntaxKind.PropertyBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.EventBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.NamespaceBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.EnumBlock, SyntaxKind.ModuleBlock, SyntaxKind.InterfaceBlock, SyntaxKind.CaseBlock, SyntaxKind.CaseElseBlock, SyntaxKind.CatchBlock, SyntaxKind.FinallyBlock, SyntaxKind.ElseBlock, SyntaxKind.ElseIfBlock, SyntaxKind.SingleLineElseClause, SyntaxKind.AttributeList, SyntaxKind.ConstructorBlock, SyntaxKind.FieldDeclaration newContext = Me Return LinkResult.Crumble Case _ SyntaxKind.SetAccessorStatement, SyntaxKind.GetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement ' Don't reuse a set statement. Set/Get are parsed differently in declarations and executable contexts newContext = Me Return LinkResult.NotUsed Case Else Return TryLinkStatement(node, newContext) End Select End Function Friend Overrides Function ProcessStatementTerminator(lambdaContext As BlockContext) As BlockContext Dim kind = Parser.CurrentToken.Kind Dim singleLine = IsSingleLine If singleLine Then Select Case kind Case SyntaxKind.StatementTerminatorToken, SyntaxKind.EndOfFileToken ' A single-line statement is terminated at the end of the line. Dim context = EndBlock(Nothing) Return context.ProcessStatementTerminator(lambdaContext) End Select End If Dim allowLeadingMultiline = False Select Case kind Case SyntaxKind.StatementTerminatorToken allowLeadingMultiline = True Case SyntaxKind.ColonToken allowLeadingMultiline = Not IsSingleLine End Select If lambdaContext Is Nothing OrElse Parser.IsNextStatementInsideLambda(Me, lambdaContext, allowLeadingMultiline) Then ' More statements within the block so the statement ' terminator can be consumed. Parser.ConsumeStatementTerminator(colonAsSeparator:=singleLine) Return Me Else ' The following statement is considered outside the enclosing lambda, so the lambda ' should be terminated but the statement terminator should not be consumed ' since it represents the end of a containing expression statement. Return EndLambda() End If End Function Friend Overrides ReadOnly Property IsSingleLine As Boolean Get Return PrevBlock.IsSingleLine End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax '----------------------------------------------------------------------------- ' Contains the definition of the ExecutableStatementContext. The base class ' for all blocks that contain statements. '----------------------------------------------------------------------------- Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend MustInherit Class ExecutableStatementContext Inherits DeclarationContext Friend Sub New(contextKind As SyntaxKind, statement As StatementSyntax, prevContext As BlockContext) MyBase.New(contextKind, statement, prevContext) End Sub Friend NotOverridable Overrides Function Parse() As StatementSyntax Return Parser.ParseStatementInMethodBody() End Function Friend Overrides Function ProcessSyntax(node As VisualBasicSyntaxNode) As BlockContext If Parser.IsDeclarationStatement(node.Kind) Then ' VS 314714 ' When we have specifiers or attributes preceding an invalid method declaration, ' we want an error of ERRID_InvInsideEndsProc reported, so that this file is decompiled ' to no state. This will remove the task list error (no state) added in FindEndProc. ' Without this fix, an invalid identifier error will be reported, and the file will ' not decompile far enough. The task list error will incorrectly stay around. ' ' Note: This bug addresses the requirement that this method (ParseStatementInMethodBody) ' should report ERRID_InvInsideEndsProc in exactly the same cases that FindEndProc ' does 'End the current block and add the block to the context above 'This must end not only the current block but the current method. Dim declarationContext = FindNearest(Function(s) SyntaxFacts.IsMethodBlock(s) OrElse s = SyntaxKind.ConstructorBlock OrElse s = SyntaxKind.OperatorBlock OrElse SyntaxFacts.IsAccessorBlock(s)) If declarationContext IsNot Nothing Then Dim context = declarationContext.PrevBlock RecoverFromMissingEnd(context) 'Let the outer context process this statement Return context.ProcessSyntax(Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideEndsProc)) Else ' we are in a block in a top-level code: node = Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideBlock, SyntaxFacts.GetBlockName(BlockKind)) Return MyBase.ProcessSyntax(node) End If Else Select Case node.Kind Case _ SyntaxKind.InheritsStatement, SyntaxKind.ImplementsStatement, SyntaxKind.OptionStatement, SyntaxKind.ImportsStatement Dim declarationContext = FindNearest(Function(s) SyntaxFacts.IsMethodBlock(s) OrElse s = SyntaxKind.ConstructorBlock OrElse s = SyntaxKind.OperatorBlock OrElse SyntaxFacts.IsAccessorBlock(s) OrElse SyntaxFacts.IsMultiLineLambdaExpression(s) OrElse SyntaxFacts.IsSingleLineLambdaExpression(s)) If declarationContext IsNot Nothing Then ' in a method or multiline lambda expression: node = Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideProc) Else ' we are in a block or in top-level code: node = Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideBlock, SyntaxFacts.GetBlockName(BlockKind)) End If Add(node) Return Me Case Else Dim newContext = TryProcessExecutableStatement(node) Return If(newContext, MyBase.ProcessSyntax(node)) End Select End If End Function Friend Overrides Function TryLinkSyntax(node As VisualBasicSyntaxNode, ByRef newContext As BlockContext) As LinkResult newContext = Nothing Select Case node.Kind ' these are errors, but ParseStatementInMethodBody accepts them for error recovery Case _ SyntaxKind.OptionStatement, SyntaxKind.ImportsStatement, SyntaxKind.InheritsStatement, SyntaxKind.ImplementsStatement, SyntaxKind.NamespaceStatement Return UseSyntax(node, newContext) Case _ SyntaxKind.ClassStatement, SyntaxKind.StructureStatement, SyntaxKind.ModuleStatement, SyntaxKind.InterfaceStatement ' Reuse as long as the statement does not have modifiers. ' These statements parse differently when they appear at the top level and when they appear within a method body. ' Within a method body, if the statement begins with a modifier then the statement is parsed as a variable declaration (with an error). If Not DirectCast(node, TypeStatementSyntax).Modifiers.Any() Then Return UseSyntax(node, newContext) Else newContext = Me Return LinkResult.NotUsed End If Case SyntaxKind.EnumStatement ' Reuse as long as the statement does not have modifiers ' These statements parse differently when they appear at the top level and when they appear within a method body. ' Within a method body, if the statement begins with a modifier then the statement is parsed as a variable declaration (with an error). If Not DirectCast(node, EnumStatementSyntax).Modifiers.Any() Then Return UseSyntax(node, newContext) Else newContext = Me Return LinkResult.NotUsed End If Case _ SyntaxKind.SubNewStatement, SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement ' Reuse as long as the statement does not have modifiers ' These statements parse differently when they appear at the top level and when they appear within a method body. ' Within a method body, if the statement begins with a dim/const then the statement is parsed as a variable declaration (with an error). If Not DirectCast(node, MethodBaseSyntax).Modifiers.Any() Then Return UseSyntax(node, newContext) Else newContext = Me Return LinkResult.NotUsed End If Case _ SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.OperatorStatement, SyntaxKind.PropertyStatement, SyntaxKind.EventStatement ' Reuse as long as the statement does not have dim or const If Not DirectCast(node, MethodBaseSyntax).Modifiers.Any(SyntaxKind.DimKeyword, SyntaxKind.ConstKeyword) Then Return UseSyntax(node, newContext) Else newContext = Me Return LinkResult.NotUsed End If ' these blocks cannot happen in current context so we should crumble them ' on next pass we will give error on the first statement Case _ SyntaxKind.SubBlock, SyntaxKind.ConstructorBlock, SyntaxKind.FunctionBlock, SyntaxKind.OperatorBlock, SyntaxKind.PropertyBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.EventBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.NamespaceBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.EnumBlock, SyntaxKind.ModuleBlock, SyntaxKind.InterfaceBlock, SyntaxKind.CaseBlock, SyntaxKind.CaseElseBlock, SyntaxKind.CatchBlock, SyntaxKind.FinallyBlock, SyntaxKind.ElseBlock, SyntaxKind.ElseIfBlock, SyntaxKind.SingleLineElseClause, SyntaxKind.AttributeList, SyntaxKind.ConstructorBlock, SyntaxKind.FieldDeclaration newContext = Me Return LinkResult.Crumble Case _ SyntaxKind.SetAccessorStatement, SyntaxKind.GetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement ' Don't reuse a set statement. Set/Get are parsed differently in declarations and executable contexts newContext = Me Return LinkResult.NotUsed Case Else Return TryLinkStatement(node, newContext) End Select End Function Friend Overrides Function ProcessStatementTerminator(lambdaContext As BlockContext) As BlockContext Dim kind = Parser.CurrentToken.Kind Dim singleLine = IsSingleLine If singleLine Then Select Case kind Case SyntaxKind.StatementTerminatorToken, SyntaxKind.EndOfFileToken ' A single-line statement is terminated at the end of the line. Dim context = EndBlock(Nothing) Return context.ProcessStatementTerminator(lambdaContext) End Select End If Dim allowLeadingMultiline = False Select Case kind Case SyntaxKind.StatementTerminatorToken allowLeadingMultiline = True Case SyntaxKind.ColonToken allowLeadingMultiline = Not IsSingleLine End Select If lambdaContext Is Nothing OrElse Parser.IsNextStatementInsideLambda(Me, lambdaContext, allowLeadingMultiline) Then ' More statements within the block so the statement ' terminator can be consumed. Parser.ConsumeStatementTerminator(colonAsSeparator:=singleLine) Return Me Else ' The following statement is considered outside the enclosing lambda, so the lambda ' should be terminated but the statement terminator should not be consumed ' since it represents the end of a containing expression statement. Return EndLambda() End If End Function Friend Overrides ReadOnly Property IsSingleLine As Boolean Get Return PrevBlock.IsSingleLine End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Portable/Binder/Semantics/BestTypeInferrer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal static class BestTypeInferrer { public static NullableAnnotation GetNullableAnnotation(ArrayBuilder<TypeWithAnnotations> types) { #if DEBUG var example = types.FirstOrDefault(t => t.HasType); #endif var result = NullableAnnotation.NotAnnotated; foreach (var type in types) { #if DEBUG Debug.Assert(!type.HasType || type.Equals(example, TypeCompareKind.AllIgnoreOptions)); #endif // This uses the covariant merging rules. result = result.Join(type.NullableAnnotation); } return result; } public static NullableFlowState GetNullableState(ArrayBuilder<TypeWithState> types) { NullableFlowState result = NullableFlowState.NotNull; foreach (var type in types) { result = result.Join(type.State); } return result; } /// <remarks> /// This method finds the best common type of a set of expressions as per section 7.5.2.14 of the specification. /// NOTE: If some or all of the expressions have error types, we return error type as the inference result. /// </remarks> public static TypeSymbol? InferBestType( ImmutableArray<BoundExpression> exprs, ConversionsBase conversions, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out bool inferredFromFunctionType) { // SPEC: 7.5.2.14 Finding the best common type of a set of expressions // SPEC: In some cases, a common type needs to be inferred for a set of expressions. In particular, the element types of implicitly typed arrays and // SPEC: the return types of anonymous functions with block bodies are found in this way. // SPEC: Intuitively, given a set of expressions E1…Em this inference should be equivalent to calling a method: // SPEC: T M<X>(X x1 … X xm) // SPEC: with the Ei as arguments. // SPEC: More precisely, the inference starts out with an unfixed type variable X. Output type inferences are then made from each Ei to X. // SPEC: Finally, X is fixed and, if successful, the resulting type S is the resulting best common type for the expressions. // SPEC: If no such S exists, the expressions have no best common type. // All non-null types are candidates for best type inference. IEqualityComparer<TypeSymbol> comparer = conversions.IncludeNullability ? Symbols.SymbolEqualityComparer.ConsiderEverything : Symbols.SymbolEqualityComparer.IgnoringNullable; HashSet<TypeSymbol> candidateTypes = new HashSet<TypeSymbol>(comparer); foreach (BoundExpression expr in exprs) { TypeSymbol? type = expr.GetTypeOrFunctionType(); if (type is { }) { if (type.IsErrorType()) { inferredFromFunctionType = false; return type; } candidateTypes.Add(type); } } // Perform best type inference on candidate types. var builder = ArrayBuilder<TypeSymbol>.GetInstance(candidateTypes.Count); builder.AddRange(candidateTypes); var result = GetBestType(builder, conversions, ref useSiteInfo); builder.Free(); if (result is FunctionTypeSymbol functionType) { result = functionType.GetInternalDelegateType(); inferredFromFunctionType = result is { }; return result; } inferredFromFunctionType = false; return result; } /// <remarks> /// This method implements best type inference for the conditional operator ?:. /// NOTE: If either expression is an error type, we return error type as the inference result. /// </remarks> public static TypeSymbol? InferBestTypeForConditionalOperator( BoundExpression expr1, BoundExpression expr2, Conversions conversions, out bool hadMultipleCandidates, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The second and third operands, x and y, of the ?: operator control the type of the conditional expression. // SPEC: • If x has type X and y has type Y then // SPEC: o If an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression. // SPEC: o If an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression. // SPEC: o Otherwise, no expression type can be determined, and a compile-time error occurs. // SPEC: • If only one of x and y has a type, and both x and y, are implicitly convertible to that type, then that is the type of the conditional expression. // SPEC: • Otherwise, no expression type can be determined, and a compile-time error occurs. // A type is a candidate if all expressions are convertible to that type. ArrayBuilder<TypeSymbol> candidateTypes = ArrayBuilder<TypeSymbol>.GetInstance(); try { var conversionsWithoutNullability = conversions.WithNullability(false); TypeSymbol? type1 = expr1.Type; if (type1 is { }) { if (type1.IsErrorType()) { hadMultipleCandidates = false; return type1; } if (conversionsWithoutNullability.ClassifyImplicitConversionFromExpression(expr2, type1, ref useSiteInfo).Exists) { candidateTypes.Add(type1); } } TypeSymbol? type2 = expr2.Type; if (type2 is { }) { if (type2.IsErrorType()) { hadMultipleCandidates = false; return type2; } if (conversionsWithoutNullability.ClassifyImplicitConversionFromExpression(expr1, type2, ref useSiteInfo).Exists) { candidateTypes.Add(type2); } } hadMultipleCandidates = candidateTypes.Count > 1; return GetBestType(candidateTypes, conversions, ref useSiteInfo); } finally { candidateTypes.Free(); } } internal static TypeSymbol? GetBestType( ArrayBuilder<TypeSymbol> types, ConversionsBase conversions, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // This code assumes that the types in the list are unique. // This code answers the famous Mike Montwill interview question: Can you find the // unique best member of a set in O(n) time if the pairwise betterness algorithm // might be intransitive? // Short-circuit some common cases. switch (types.Count) { case 0: return null; case 1: return checkType(types[0]); } TypeSymbol? best = null; int bestIndex = -1; for (int i = 0; i < types.Count; i++) { TypeSymbol? type = checkType(types[i]); if (type is null) { continue; } if (best is null) { best = type; bestIndex = i; } else { var better = Better(best, type, conversions, ref useSiteInfo); if (better is null) { best = null; } else { best = better; bestIndex = i; } } } if (best is null) { return null; } // We have actually only determined that every type *after* best was worse. Now check // that every type *before* best was also worse. for (int i = 0; i < bestIndex; i++) { TypeSymbol? type = checkType(types[i]); if (type is null) { continue; } TypeSymbol? better = Better(best, type, conversions, ref useSiteInfo); if (!best.Equals(better, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return null; } } return best; static TypeSymbol? checkType(TypeSymbol type) => type is FunctionTypeSymbol functionType && functionType.GetInternalDelegateType() is null ? null : type; } /// <summary> /// Returns the better type amongst the two, with some possible modifications (dynamic/object or tuple names). /// </summary> private static TypeSymbol? Better( TypeSymbol type1, TypeSymbol? type2, ConversionsBase conversions, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Anything is better than an error sym. if (type1.IsErrorType()) { return type2; } if (type2 is null || type2.IsErrorType()) { return type1; } // Prefer types other than FunctionTypeSymbol. if (type1 is FunctionTypeSymbol) { if (!(type2 is FunctionTypeSymbol)) { return type2; } } else if (type2 is FunctionTypeSymbol) { return type1; } var conversionsWithoutNullability = conversions.WithNullability(false); var t1tot2 = conversionsWithoutNullability.ClassifyImplicitConversionFromTypeWhenNeitherOrBothFunctionTypes(type1, type2, ref useSiteInfo).Exists; var t2tot1 = conversionsWithoutNullability.ClassifyImplicitConversionFromTypeWhenNeitherOrBothFunctionTypes(type2, type1, ref useSiteInfo).Exists; if (t1tot2 && t2tot1) { if (type1.Equals(type2, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return type1.MergeEquivalentTypes(type2, VarianceKind.Out); } return null; } if (t1tot2) { return type2; } if (t2tot1) { return type1; } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal static class BestTypeInferrer { public static NullableAnnotation GetNullableAnnotation(ArrayBuilder<TypeWithAnnotations> types) { #if DEBUG var example = types.FirstOrDefault(t => t.HasType); #endif var result = NullableAnnotation.NotAnnotated; foreach (var type in types) { #if DEBUG Debug.Assert(!type.HasType || type.Equals(example, TypeCompareKind.AllIgnoreOptions)); #endif // This uses the covariant merging rules. result = result.Join(type.NullableAnnotation); } return result; } public static NullableFlowState GetNullableState(ArrayBuilder<TypeWithState> types) { NullableFlowState result = NullableFlowState.NotNull; foreach (var type in types) { result = result.Join(type.State); } return result; } /// <remarks> /// This method finds the best common type of a set of expressions as per section 7.5.2.14 of the specification. /// NOTE: If some or all of the expressions have error types, we return error type as the inference result. /// </remarks> public static TypeSymbol? InferBestType( ImmutableArray<BoundExpression> exprs, ConversionsBase conversions, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out bool inferredFromFunctionType) { // SPEC: 7.5.2.14 Finding the best common type of a set of expressions // SPEC: In some cases, a common type needs to be inferred for a set of expressions. In particular, the element types of implicitly typed arrays and // SPEC: the return types of anonymous functions with block bodies are found in this way. // SPEC: Intuitively, given a set of expressions E1…Em this inference should be equivalent to calling a method: // SPEC: T M<X>(X x1 … X xm) // SPEC: with the Ei as arguments. // SPEC: More precisely, the inference starts out with an unfixed type variable X. Output type inferences are then made from each Ei to X. // SPEC: Finally, X is fixed and, if successful, the resulting type S is the resulting best common type for the expressions. // SPEC: If no such S exists, the expressions have no best common type. // All non-null types are candidates for best type inference. IEqualityComparer<TypeSymbol> comparer = conversions.IncludeNullability ? Symbols.SymbolEqualityComparer.ConsiderEverything : Symbols.SymbolEqualityComparer.IgnoringNullable; HashSet<TypeSymbol> candidateTypes = new HashSet<TypeSymbol>(comparer); foreach (BoundExpression expr in exprs) { TypeSymbol? type = expr.GetTypeOrFunctionType(); if (type is { }) { if (type.IsErrorType()) { inferredFromFunctionType = false; return type; } candidateTypes.Add(type); } } // Perform best type inference on candidate types. var builder = ArrayBuilder<TypeSymbol>.GetInstance(candidateTypes.Count); builder.AddRange(candidateTypes); var result = GetBestType(builder, conversions, ref useSiteInfo); builder.Free(); if (result is FunctionTypeSymbol functionType) { result = functionType.GetInternalDelegateType(); inferredFromFunctionType = result is { }; return result; } inferredFromFunctionType = false; return result; } /// <remarks> /// This method implements best type inference for the conditional operator ?:. /// NOTE: If either expression is an error type, we return error type as the inference result. /// </remarks> public static TypeSymbol? InferBestTypeForConditionalOperator( BoundExpression expr1, BoundExpression expr2, Conversions conversions, out bool hadMultipleCandidates, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The second and third operands, x and y, of the ?: operator control the type of the conditional expression. // SPEC: • If x has type X and y has type Y then // SPEC: o If an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression. // SPEC: o If an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression. // SPEC: o Otherwise, no expression type can be determined, and a compile-time error occurs. // SPEC: • If only one of x and y has a type, and both x and y, are implicitly convertible to that type, then that is the type of the conditional expression. // SPEC: • Otherwise, no expression type can be determined, and a compile-time error occurs. // A type is a candidate if all expressions are convertible to that type. ArrayBuilder<TypeSymbol> candidateTypes = ArrayBuilder<TypeSymbol>.GetInstance(); try { var conversionsWithoutNullability = conversions.WithNullability(false); TypeSymbol? type1 = expr1.Type; if (type1 is { }) { if (type1.IsErrorType()) { hadMultipleCandidates = false; return type1; } if (conversionsWithoutNullability.ClassifyImplicitConversionFromExpression(expr2, type1, ref useSiteInfo).Exists) { candidateTypes.Add(type1); } } TypeSymbol? type2 = expr2.Type; if (type2 is { }) { if (type2.IsErrorType()) { hadMultipleCandidates = false; return type2; } if (conversionsWithoutNullability.ClassifyImplicitConversionFromExpression(expr1, type2, ref useSiteInfo).Exists) { candidateTypes.Add(type2); } } hadMultipleCandidates = candidateTypes.Count > 1; return GetBestType(candidateTypes, conversions, ref useSiteInfo); } finally { candidateTypes.Free(); } } internal static TypeSymbol? GetBestType( ArrayBuilder<TypeSymbol> types, ConversionsBase conversions, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // This code assumes that the types in the list are unique. // This code answers the famous Mike Montwill interview question: Can you find the // unique best member of a set in O(n) time if the pairwise betterness algorithm // might be intransitive? // Short-circuit some common cases. switch (types.Count) { case 0: return null; case 1: return checkType(types[0]); } TypeSymbol? best = null; int bestIndex = -1; for (int i = 0; i < types.Count; i++) { TypeSymbol? type = checkType(types[i]); if (type is null) { continue; } if (best is null) { best = type; bestIndex = i; } else { var better = Better(best, type, conversions, ref useSiteInfo); if (better is null) { best = null; } else { best = better; bestIndex = i; } } } if (best is null) { return null; } // We have actually only determined that every type *after* best was worse. Now check // that every type *before* best was also worse. for (int i = 0; i < bestIndex; i++) { TypeSymbol? type = checkType(types[i]); if (type is null) { continue; } TypeSymbol? better = Better(best, type, conversions, ref useSiteInfo); if (!best.Equals(better, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return null; } } return best; static TypeSymbol? checkType(TypeSymbol type) => type is FunctionTypeSymbol functionType && functionType.GetInternalDelegateType() is null ? null : type; } /// <summary> /// Returns the better type amongst the two, with some possible modifications (dynamic/object or tuple names). /// </summary> private static TypeSymbol? Better( TypeSymbol type1, TypeSymbol? type2, ConversionsBase conversions, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Anything is better than an error sym. if (type1.IsErrorType()) { return type2; } if (type2 is null || type2.IsErrorType()) { return type1; } // Prefer types other than FunctionTypeSymbol. if (type1 is FunctionTypeSymbol) { if (!(type2 is FunctionTypeSymbol)) { return type2; } } else if (type2 is FunctionTypeSymbol) { return type1; } var conversionsWithoutNullability = conversions.WithNullability(false); var t1tot2 = conversionsWithoutNullability.ClassifyImplicitConversionFromTypeWhenNeitherOrBothFunctionTypes(type1, type2, ref useSiteInfo).Exists; var t2tot1 = conversionsWithoutNullability.ClassifyImplicitConversionFromTypeWhenNeitherOrBothFunctionTypes(type2, type1, ref useSiteInfo).Exists; if (t1tot2 && t2tot1) { if (type1.Equals(type2, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return type1.MergeEquivalentTypes(type2, VarianceKind.Out); } return null; } if (t1tot2) { return type2; } if (t2tot1) { return type1; } return null; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/IfStatementHighlighter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Highlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.KeywordHighlighting { [ExportHighlighter(LanguageNames.CSharp), Shared] internal class IfStatementHighlighter : AbstractKeywordHighlighter<IfStatementSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public IfStatementHighlighter() { } protected override void AddHighlights( IfStatementSyntax ifStatement, List<TextSpan> highlights, CancellationToken cancellationToken) { if (ifStatement.Parent.Kind() != SyntaxKind.ElseClause) { ComputeSpans(ifStatement, highlights); } } private static void ComputeSpans( IfStatementSyntax ifStatement, List<TextSpan> highlights) { highlights.Add(ifStatement.IfKeyword.Span); // Loop to get all the else if parts while (ifStatement != null && ifStatement.Else != null) { // Check for 'else if' scenario' (the statement in the else clause is an if statement) var elseKeyword = ifStatement.Else.ElseKeyword; if (ifStatement.Else.Statement is IfStatementSyntax elseIfStatement) { if (OnlySpacesBetween(elseKeyword, elseIfStatement.IfKeyword)) { // Highlight both else and if tokens if they are on the same line highlights.Add(TextSpan.FromBounds( elseKeyword.SpanStart, elseIfStatement.IfKeyword.Span.End)); } else { // Highlight the else and if tokens separately highlights.Add(elseKeyword.Span); highlights.Add(elseIfStatement.IfKeyword.Span); } // Continue the enumeration looking for more else blocks ifStatement = elseIfStatement; } else { // Highlight just the else and we're done highlights.Add(elseKeyword.Span); break; } } } public static bool OnlySpacesBetween(SyntaxToken first, SyntaxToken second) { return first.TrailingTrivia.AsString().All(c => c == ' ') && second.LeadingTrivia.AsString().All(c => c == ' '); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Highlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.KeywordHighlighting { [ExportHighlighter(LanguageNames.CSharp), Shared] internal class IfStatementHighlighter : AbstractKeywordHighlighter<IfStatementSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public IfStatementHighlighter() { } protected override void AddHighlights( IfStatementSyntax ifStatement, List<TextSpan> highlights, CancellationToken cancellationToken) { if (ifStatement.Parent.Kind() != SyntaxKind.ElseClause) { ComputeSpans(ifStatement, highlights); } } private static void ComputeSpans( IfStatementSyntax ifStatement, List<TextSpan> highlights) { highlights.Add(ifStatement.IfKeyword.Span); // Loop to get all the else if parts while (ifStatement != null && ifStatement.Else != null) { // Check for 'else if' scenario' (the statement in the else clause is an if statement) var elseKeyword = ifStatement.Else.ElseKeyword; if (ifStatement.Else.Statement is IfStatementSyntax elseIfStatement) { if (OnlySpacesBetween(elseKeyword, elseIfStatement.IfKeyword)) { // Highlight both else and if tokens if they are on the same line highlights.Add(TextSpan.FromBounds( elseKeyword.SpanStart, elseIfStatement.IfKeyword.Span.End)); } else { // Highlight the else and if tokens separately highlights.Add(elseKeyword.Span); highlights.Add(elseIfStatement.IfKeyword.Span); } // Continue the enumeration looking for more else blocks ifStatement = elseIfStatement; } else { // Highlight just the else and we're done highlights.Add(elseKeyword.Span); break; } } } public static bool OnlySpacesBetween(SyntaxToken first, SyntaxToken second) { return first.TrailingTrivia.AsString().All(c => c == ' ') && second.LeadingTrivia.AsString().All(c => c == ' '); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Test/Resources/Core/SymbolsTests/UseSiteErrors/CSharpErrors.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // Depends on Unavailable.dll // csc /target:library /reference:Unavailable.dll CSharpErrors.cs namespace CSharpErrors { public class Subclass1 : UnavailableClass { } public class Subclass2<T> : UnavailableClass<T> { } public class Subclass3 : UnavailableClass<int> { } public class ImplementingClass1 : UnavailableInterface { } public class ImplementingClass2<T> : UnavailableInterface<T> { } public class ImplementingClass3 : UnavailableInterface<int> { } public struct ImplementingStruct1 : UnavailableInterface { } public struct ImplementingStruct2<T> : UnavailableInterface<T> { } public struct ImplementingStruct3 : UnavailableInterface<int> { } public delegate UnavailableClass DelegateReturnType1(); public delegate UnavailableClass DelegateReturnType2(); public delegate void DelegateParameterType1(UnavailableClass u); public delegate void DelegateParameterType2(UnavailableClass[] u); public delegate UnavailableClass<T> DelegateParameterType3<T>(UnavailableClass<T> u); public class ClassMethods { public virtual UnavailableClass ReturnType1() { return null; } public virtual UnavailableClass[] ReturnType2() { return null; } public virtual void ParameterType1(UnavailableClass u) { } public virtual void ParameterType2(UnavailableClass[] u) { } } public interface InterfaceMethods { UnavailableClass ReturnType1(); UnavailableClass[] ReturnType2(); void ParameterType1(UnavailableClass u); void ParameterType2(UnavailableClass[] u); } public class ClassProperties { public virtual UnavailableClass GetSet1 { get; set; } public virtual UnavailableClass[] GetSet2 { get; set; } public virtual UnavailableClass Get1 { get { return null; } } public virtual UnavailableClass[] Get2 { get { return null; } } public virtual UnavailableClass Set1 { set { } } public virtual UnavailableClass[] Set2 { set { } } } public interface InterfaceProperties { UnavailableClass GetSet1 { get; set; } UnavailableClass[] GetSet2 { get; set; } UnavailableClass Get1 { get; } UnavailableClass[] Get2 { get; } UnavailableClass Set1 { set; } UnavailableClass[] Set2 { set; } } public delegate void EventDelegate<T>(); public class ClassEvents { public virtual event UnavailableDelegate Event1; public virtual event EventDelegate<UnavailableClass> Event2; public virtual event EventDelegate<UnavailableClass[]> Event3; } public interface InterfaceEvents { event UnavailableDelegate Event1; event EventDelegate<UnavailableClass> Event2; event EventDelegate<UnavailableClass[]> Event3; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // Depends on Unavailable.dll // csc /target:library /reference:Unavailable.dll CSharpErrors.cs namespace CSharpErrors { public class Subclass1 : UnavailableClass { } public class Subclass2<T> : UnavailableClass<T> { } public class Subclass3 : UnavailableClass<int> { } public class ImplementingClass1 : UnavailableInterface { } public class ImplementingClass2<T> : UnavailableInterface<T> { } public class ImplementingClass3 : UnavailableInterface<int> { } public struct ImplementingStruct1 : UnavailableInterface { } public struct ImplementingStruct2<T> : UnavailableInterface<T> { } public struct ImplementingStruct3 : UnavailableInterface<int> { } public delegate UnavailableClass DelegateReturnType1(); public delegate UnavailableClass DelegateReturnType2(); public delegate void DelegateParameterType1(UnavailableClass u); public delegate void DelegateParameterType2(UnavailableClass[] u); public delegate UnavailableClass<T> DelegateParameterType3<T>(UnavailableClass<T> u); public class ClassMethods { public virtual UnavailableClass ReturnType1() { return null; } public virtual UnavailableClass[] ReturnType2() { return null; } public virtual void ParameterType1(UnavailableClass u) { } public virtual void ParameterType2(UnavailableClass[] u) { } } public interface InterfaceMethods { UnavailableClass ReturnType1(); UnavailableClass[] ReturnType2(); void ParameterType1(UnavailableClass u); void ParameterType2(UnavailableClass[] u); } public class ClassProperties { public virtual UnavailableClass GetSet1 { get; set; } public virtual UnavailableClass[] GetSet2 { get; set; } public virtual UnavailableClass Get1 { get { return null; } } public virtual UnavailableClass[] Get2 { get { return null; } } public virtual UnavailableClass Set1 { set { } } public virtual UnavailableClass[] Set2 { set { } } } public interface InterfaceProperties { UnavailableClass GetSet1 { get; set; } UnavailableClass[] GetSet2 { get; set; } UnavailableClass Get1 { get; } UnavailableClass[] Get2 { get; } UnavailableClass Set1 { set; } UnavailableClass[] Set2 { set; } } public delegate void EventDelegate<T>(); public class ClassEvents { public virtual event UnavailableDelegate Event1; public virtual event EventDelegate<UnavailableClass> Event2; public virtual event EventDelegate<UnavailableClass[]> Event3; } public interface InterfaceEvents { event UnavailableDelegate Event1; event EventDelegate<UnavailableClass> Event2; event EventDelegate<UnavailableClass[]> Event3; } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Analyzers/Core/Analyzers/UseConditionalExpression/UseConditionalExpressionHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal static partial class UseConditionalExpressionHelpers { public static bool CanConvert( ISyntaxFacts syntaxFacts, IConditionalOperation ifOperation, IOperation whenTrue, IOperation whenFalse) { // Will likely not work as intended if the if directive spans any preprocessor directives. So // do not offer for now. Note: we pass in both the node for the ifOperation and the // whenFalse portion. The whenFalse portion isn't necessary under the ifOperation. For // example in: // // ```c# // #if DEBUG // if (check) // return 3; // #endif // return 2; // ``` // // In this case, we want to see that this cross the `#endif` if (syntaxFacts.SpansPreprocessorDirective(ifOperation.Syntax, whenFalse.Syntax)) { return false; } // User may have comments on the when-true/when-false statements. These statements can // be very important. Often they indicate why the true/false branches are important in // the first place. We don't have any place to put these, so we don't offer here. if (HasRegularComments(syntaxFacts, whenTrue.Syntax) || HasRegularComments(syntaxFacts, whenFalse.Syntax)) { return false; } return true; } /// <summary> /// Will unwrap a block with a single statement in it to just that block. Used so we can /// support both <c>if (expr) { statement }</c> and <c>if (expr) statement</c> /// </summary> [return: NotNullIfNotNull("statement")] public static IOperation? UnwrapSingleStatementBlock(IOperation? statement) => statement is IBlockOperation block && block.Operations.Length == 1 ? block.Operations[0] : statement; public static IOperation UnwrapImplicitConversion(IOperation value) => value is IConversionOperation conversion && conversion.IsImplicit ? conversion.Operand : value; public static bool HasRegularComments(ISyntaxFacts syntaxFacts, SyntaxNode syntax) => HasRegularCommentTrivia(syntaxFacts, syntax.GetLeadingTrivia()) || HasRegularCommentTrivia(syntaxFacts, syntax.GetTrailingTrivia()); public static bool HasRegularCommentTrivia(ISyntaxFacts syntaxFacts, SyntaxTriviaList triviaList) { foreach (var trivia in triviaList) { if (syntaxFacts.IsRegularComment(trivia)) { return true; } } return false; } public static bool HasInconvertibleThrowStatement( ISyntaxFacts syntaxFacts, bool isRef, IThrowOperation? trueThrow, IThrowOperation? falseThrow) { // Can't convert to `x ? throw ... : throw ...` as there's no best common type between the two (even when // throwing the same exception type). if (trueThrow != null && falseThrow != null) return true; var anyThrow = trueThrow ?? falseThrow; if (anyThrow != null) { // can only convert to a conditional expression if the lang supports throw-exprs. if (!syntaxFacts.SupportsThrowExpression(anyThrow.Syntax.SyntaxTree.Options)) return true; // `ref` can't be used with `throw`. if (isRef) 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.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal static partial class UseConditionalExpressionHelpers { public static bool CanConvert( ISyntaxFacts syntaxFacts, IConditionalOperation ifOperation, IOperation whenTrue, IOperation whenFalse) { // Will likely not work as intended if the if directive spans any preprocessor directives. So // do not offer for now. Note: we pass in both the node for the ifOperation and the // whenFalse portion. The whenFalse portion isn't necessary under the ifOperation. For // example in: // // ```c# // #if DEBUG // if (check) // return 3; // #endif // return 2; // ``` // // In this case, we want to see that this cross the `#endif` if (syntaxFacts.SpansPreprocessorDirective(ifOperation.Syntax, whenFalse.Syntax)) { return false; } // User may have comments on the when-true/when-false statements. These statements can // be very important. Often they indicate why the true/false branches are important in // the first place. We don't have any place to put these, so we don't offer here. if (HasRegularComments(syntaxFacts, whenTrue.Syntax) || HasRegularComments(syntaxFacts, whenFalse.Syntax)) { return false; } return true; } /// <summary> /// Will unwrap a block with a single statement in it to just that block. Used so we can /// support both <c>if (expr) { statement }</c> and <c>if (expr) statement</c> /// </summary> [return: NotNullIfNotNull("statement")] public static IOperation? UnwrapSingleStatementBlock(IOperation? statement) => statement is IBlockOperation block && block.Operations.Length == 1 ? block.Operations[0] : statement; public static IOperation UnwrapImplicitConversion(IOperation value) => value is IConversionOperation conversion && conversion.IsImplicit ? conversion.Operand : value; public static bool HasRegularComments(ISyntaxFacts syntaxFacts, SyntaxNode syntax) => HasRegularCommentTrivia(syntaxFacts, syntax.GetLeadingTrivia()) || HasRegularCommentTrivia(syntaxFacts, syntax.GetTrailingTrivia()); public static bool HasRegularCommentTrivia(ISyntaxFacts syntaxFacts, SyntaxTriviaList triviaList) { foreach (var trivia in triviaList) { if (syntaxFacts.IsRegularComment(trivia)) { return true; } } return false; } public static bool HasInconvertibleThrowStatement( ISyntaxFacts syntaxFacts, bool isRef, IThrowOperation? trueThrow, IThrowOperation? falseThrow) { // Can't convert to `x ? throw ... : throw ...` as there's no best common type between the two (even when // throwing the same exception type). if (trueThrow != null && falseThrow != null) return true; var anyThrow = trueThrow ?? falseThrow; if (anyThrow != null) { // can only convert to a conditional expression if the lang supports throw-exprs. if (!syntaxFacts.SupportsThrowExpression(anyThrow.Syntax.SyntaxTree.Options)) return true; // `ref` can't be used with `throw`. if (isRef) return true; } return false; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Xaml/Impl/Features/Commands/IXamlCommandService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Commands { internal interface IXamlCommandService : ILanguageService { /// <summary> /// Execute the <paramref name="command"/> with the <paramref name="commandArguments"/> /// </summary> /// <param name="document">TextDocument command was triggered on</param> /// <param name="command">The command that will be executed</param> /// <param name="commandArguments">The arguments need by the command</param> /// <param name="cancellationToken">cancellationToken</param> /// <returns>True if the command has been executed, otherwise false</returns> Task<bool> ExecuteCommandAsync(TextDocument document, string command, object[]? commandArguments, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Commands { internal interface IXamlCommandService : ILanguageService { /// <summary> /// Execute the <paramref name="command"/> with the <paramref name="commandArguments"/> /// </summary> /// <param name="document">TextDocument command was triggered on</param> /// <param name="command">The command that will be executed</param> /// <param name="commandArguments">The arguments need by the command</param> /// <param name="cancellationToken">cancellationToken</param> /// <returns>True if the command has been executed, otherwise false</returns> Task<bool> ExecuteCommandAsync(TextDocument document, string command, object[]? commandArguments, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ICoalesceOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_ICoalesceOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_01() { var source = @" class C { void F(int? input, int alternative, int result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Identity) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_02() { var source = @" class C { void F(int? input, long alternative, long result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int64) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNumeric) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNumeric) Operand: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_03() { var source = @" class C { void F(int? input, long? alternative, long? result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int64?) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64?, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) Operand: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64?) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int64?, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_04() { var source = @" class C { void F(string input, object alternative, object result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Object) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.String) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.String) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_05() { var source = @" class C { void F(int? input, System.DateTime alternative, object result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'int?' and 'DateTime' // result = input ?? alternative; Diagnostic(ErrorCode.ERR_BadBinaryOps, "input ?? alternative").WithArguments("??", "int?", "System.DateTime").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: ?, IsInvalid) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input') ValueConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.DateTime, IsInvalid) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'input') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.DateTime, IsInvalid) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsInvalid) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'input ?? alternative') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(60059, "https://github.com/dotnet/roslyn/issues/60059")] public void CoalesceOperation_06() { var source = @" class C { void F(int? input, dynamic alternative, dynamic result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source, references: new[] { CSharpRef }, targetFramework: TargetFramework.Mscorlib40AndSystemCore); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: dynamic) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Boxing) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Boxing) Operand: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_07() { var source = @" class C { void F(dynamic alternative, dynamic result) /*<bind>*/{ result = null ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source, references: new[] { CSharpRef }, targetFramework: TargetFramework.Mscorlib40AndSystemCore); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: dynamic) (Syntax: 'null ?? alternative') Expression: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = nu ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'result = nu ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'null ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_08() { var source = @" class C { void F(int alternative, int result) /*<bind>*/{ result = null ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0019: Operator '??' cannot be applied to operands of type '<null>' and 'int' // result = null ?? alternative; Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? alternative").WithArguments("??", "<null>", "int").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: ?, IsInvalid) (Syntax: 'null ?? alternative') Expression: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') ValueConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'null') Value: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsInvalid, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'null') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = nu ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'result = nu ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'null ?? alternative') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_09() { var source = @" class C { void F(int? alternative, int? result) /*<bind>*/{ result = null ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'null ?? alternative') Expression: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NullLiteral) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NullLiteral) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = nu ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = nu ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'null ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_10() { var source = @" class C { void F(int? input, byte? alternative, int? result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Identity) WhenNull: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'alternative') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Byte?) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'alternative') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) Operand: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Byte?) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_11() { var source = @" class C { void F(int? input, int? alternative, int? result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Identity) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_12() { var source = @" class C { void F(int? input1, int? alternative1, int? input2, int? alternative2, int? result) /*<bind>*/{ result = (input1 ?? alternative1) ?? (input2 ?? alternative2); }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [3] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative1') Value: IParameterReferenceOperation: alternative1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative1') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1 ?? alternative1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1 ?? alternative1') Leaving: {R2} Entering: {R4} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1 ?? alternative1') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1 ?? alternative1') Next (Regular) Block[B10] Leaving: {R2} } .locals {R4} { CaptureIds: [4] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input2') Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input2') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input2') Leaving: {R4} Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input2') Next (Regular) Block[B10] Leaving: {R4} } Block[B9] - Block Predecessors: [B7] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative2') Value: IParameterReferenceOperation: alternative2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative2') Next (Regular) Block[B10] Block[B10] - Block Predecessors: [B6] [B8] [B9] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = (i ... ernative2);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = (i ... ternative2)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: '(input1 ?? ... ternative2)') Next (Regular) Block[B11] Leaving: {R1} } Block[B11] - Exit Predecessors: [B10] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_13() { var source = @" class C { const string input = ""a""; void F(object alternative, object result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IFieldReferenceOperation: System.String C.input (Static) (OperationKind.FieldReference, Type: System.String, Constant: ""a"") (Syntax: 'input') Instance Receiver: null Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, Constant: ""a"", IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, Constant: ""a"", IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_14() { string source = @" class P { void M1(int? i, int j, int result) /*<bind>*/{ result = i ?? j; }/*</bind>*/ } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'i') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j') Value: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i ?? j;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = i ?? j') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i ?? j') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedGraph, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_ICoalesceOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_01() { var source = @" class C { void F(int? input, int alternative, int result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Identity) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_02() { var source = @" class C { void F(int? input, long alternative, long result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int64) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNumeric) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNumeric) Operand: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_03() { var source = @" class C { void F(int? input, long? alternative, long? result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int64?) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64?, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) Operand: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64?) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int64?, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_04() { var source = @" class C { void F(string input, object alternative, object result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Object) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.String) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.String) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_05() { var source = @" class C { void F(int? input, System.DateTime alternative, object result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'int?' and 'DateTime' // result = input ?? alternative; Diagnostic(ErrorCode.ERR_BadBinaryOps, "input ?? alternative").WithArguments("??", "int?", "System.DateTime").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: ?, IsInvalid) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input') ValueConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.DateTime, IsInvalid) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'input') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.DateTime, IsInvalid) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsInvalid) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'input ?? alternative') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(60059, "https://github.com/dotnet/roslyn/issues/60059")] public void CoalesceOperation_06() { var source = @" class C { void F(int? input, dynamic alternative, dynamic result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source, references: new[] { CSharpRef }, targetFramework: TargetFramework.Mscorlib40AndSystemCore); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: dynamic) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Boxing) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Boxing) Operand: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_07() { var source = @" class C { void F(dynamic alternative, dynamic result) /*<bind>*/{ result = null ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source, references: new[] { CSharpRef }, targetFramework: TargetFramework.Mscorlib40AndSystemCore); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: dynamic) (Syntax: 'null ?? alternative') Expression: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = nu ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'result = nu ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'null ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_08() { var source = @" class C { void F(int alternative, int result) /*<bind>*/{ result = null ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0019: Operator '??' cannot be applied to operands of type '<null>' and 'int' // result = null ?? alternative; Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? alternative").WithArguments("??", "<null>", "int").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: ?, IsInvalid) (Syntax: 'null ?? alternative') Expression: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') ValueConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'null') Value: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsInvalid, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'null') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = nu ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'result = nu ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'null ?? alternative') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_09() { var source = @" class C { void F(int? alternative, int? result) /*<bind>*/{ result = null ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'null ?? alternative') Expression: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NullLiteral) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NullLiteral) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = nu ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = nu ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'null ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_10() { var source = @" class C { void F(int? input, byte? alternative, int? result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Identity) WhenNull: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'alternative') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Byte?) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'alternative') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) Operand: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Byte?) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_11() { var source = @" class C { void F(int? input, int? alternative, int? result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Identity) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_12() { var source = @" class C { void F(int? input1, int? alternative1, int? input2, int? alternative2, int? result) /*<bind>*/{ result = (input1 ?? alternative1) ?? (input2 ?? alternative2); }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [3] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative1') Value: IParameterReferenceOperation: alternative1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative1') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1 ?? alternative1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1 ?? alternative1') Leaving: {R2} Entering: {R4} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1 ?? alternative1') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1 ?? alternative1') Next (Regular) Block[B10] Leaving: {R2} } .locals {R4} { CaptureIds: [4] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input2') Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input2') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input2') Leaving: {R4} Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input2') Next (Regular) Block[B10] Leaving: {R4} } Block[B9] - Block Predecessors: [B7] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative2') Value: IParameterReferenceOperation: alternative2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative2') Next (Regular) Block[B10] Block[B10] - Block Predecessors: [B6] [B8] [B9] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = (i ... ernative2);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = (i ... ternative2)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: '(input1 ?? ... ternative2)') Next (Regular) Block[B11] Leaving: {R1} } Block[B11] - Exit Predecessors: [B10] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_13() { var source = @" class C { const string input = ""a""; void F(object alternative, object result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IFieldReferenceOperation: System.String C.input (Static) (OperationKind.FieldReference, Type: System.String, Constant: ""a"") (Syntax: 'input') Instance Receiver: null Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, Constant: ""a"", IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, Constant: ""a"", IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_14() { string source = @" class P { void M1(int? i, int j, int result) /*<bind>*/{ result = i ?? j; }/*</bind>*/ } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'i') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j') Value: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i ?? j;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = i ?? j') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i ?? j') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedGraph, expectedDiagnostics); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/CoreTestUtilities/AsynchronousOperationListenerExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.TestHooks; namespace Roslyn.Test.Utilities { public static class AsynchronousOperationListenerExtensions { internal static async Task WaitAllDispatcherOperationAndTasksAsync(this IAsynchronousOperationListenerProvider provider, Workspace? workspace, params string[] featureNames) { await ((AsynchronousOperationListenerProvider)provider).WaitAllAsync(workspace, featureNames).ConfigureAwait(false); } internal static IAsynchronousOperationWaiter GetWaiter(this IAsynchronousOperationListenerProvider provider, string featureName) => (IAsynchronousOperationWaiter)provider.GetListener(featureName); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.TestHooks; namespace Roslyn.Test.Utilities { public static class AsynchronousOperationListenerExtensions { internal static async Task WaitAllDispatcherOperationAndTasksAsync(this IAsynchronousOperationListenerProvider provider, Workspace? workspace, params string[] featureNames) { await ((AsynchronousOperationListenerProvider)provider).WaitAllAsync(workspace, featureNames).ConfigureAwait(false); } internal static IAsynchronousOperationWaiter GetWaiter(this IAsynchronousOperationListenerProvider provider, string featureName) => (IAsynchronousOperationWaiter)provider.GetListener(featureName); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/Core/Tagging/AsynchronousTaggerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Workspaces; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal abstract class AsynchronousTaggerProvider<TTag> : AbstractAsynchronousTaggerProvider<TTag>, ITaggerProvider where TTag : ITag { protected AsynchronousTaggerProvider( IThreadingContext threadingContext, IGlobalOptionService globalOptions, ITextBufferVisibilityTracker? visibilityTracker, IAsynchronousOperationListener asyncListener) : base(threadingContext, globalOptions, visibilityTracker, asyncListener) { } public ITagger<T>? CreateTagger<T>(ITextBuffer subjectBuffer) where T : ITag { if (subjectBuffer == null) throw new ArgumentNullException(nameof(subjectBuffer)); return this.CreateTaggerWorker<T>(null, subjectBuffer); } ITagger<T>? ITaggerProvider.CreateTagger<T>(ITextBuffer buffer) => CreateTagger<T>(buffer); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Workspaces; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal abstract class AsynchronousTaggerProvider<TTag> : AbstractAsynchronousTaggerProvider<TTag>, ITaggerProvider where TTag : ITag { protected AsynchronousTaggerProvider( IThreadingContext threadingContext, IGlobalOptionService globalOptions, ITextBufferVisibilityTracker? visibilityTracker, IAsynchronousOperationListener asyncListener) : base(threadingContext, globalOptions, visibilityTracker, asyncListener) { } public ITagger<T>? CreateTagger<T>(ITextBuffer subjectBuffer) where T : ITag { if (subjectBuffer == null) throw new ArgumentNullException(nameof(subjectBuffer)); return this.CreateTaggerWorker<T>(null, subjectBuffer); } ITagger<T>? ITaggerProvider.CreateTagger<T>(ITextBuffer buffer) => CreateTagger<T>(buffer); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/CSharp/Portable/Symbols/PublicModel/DiscardSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class DiscardSymbol : Symbol, IDiscardSymbol { private readonly Symbols.DiscardSymbol _underlying; private ITypeSymbol? _lazyType; public DiscardSymbol(Symbols.DiscardSymbol underlying) { RoslynDebug.Assert(underlying != null); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; ITypeSymbol IDiscardSymbol.Type { get { if (_lazyType is null) { Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null); } return _lazyType; } } CodeAnalysis.NullableAnnotation IDiscardSymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation(); protected override void Accept(SymbolVisitor visitor) => visitor.VisitDiscard(this); protected override TResult? Accept<TResult>(SymbolVisitor<TResult> visitor) where TResult : default => visitor.VisitDiscard(this); protected override TResult Accept<TArgument, TResult>(SymbolVisitor<TArgument, TResult> visitor, TArgument argument) => visitor.VisitDiscard(this, argument); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class DiscardSymbol : Symbol, IDiscardSymbol { private readonly Symbols.DiscardSymbol _underlying; private ITypeSymbol? _lazyType; public DiscardSymbol(Symbols.DiscardSymbol underlying) { RoslynDebug.Assert(underlying != null); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; ITypeSymbol IDiscardSymbol.Type { get { if (_lazyType is null) { Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null); } return _lazyType; } } CodeAnalysis.NullableAnnotation IDiscardSymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation(); protected override void Accept(SymbolVisitor visitor) => visitor.VisitDiscard(this); protected override TResult? Accept<TResult>(SymbolVisitor<TResult> visitor) where TResult : default => visitor.VisitDiscard(this); protected override TResult Accept<TArgument, TResult>(SymbolVisitor<TArgument, TResult> visitor, TArgument argument) => visitor.VisitDiscard(this, argument); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/Syntax/InternalSyntax/SyntaxList`1.Enumerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { internal partial struct SyntaxList<TNode> where TNode : GreenNode { internal struct Enumerator { private readonly SyntaxList<TNode> _list; private int _index; internal Enumerator(SyntaxList<TNode> list) { _list = list; _index = -1; } public bool MoveNext() { var newIndex = _index + 1; if (newIndex < _list.Count) { _index = newIndex; return true; } return false; } public TNode Current { get { return _list[_index]!; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { internal partial struct SyntaxList<TNode> where TNode : GreenNode { internal struct Enumerator { private readonly SyntaxList<TNode> _list; private int _index; internal Enumerator(SyntaxList<TNode> list) { _list = list; _index = -1; } public bool MoveNext() { var newIndex = _index + 1; if (newIndex < _list.Count) { _index = newIndex; return true; } return false; } public TNode Current { get { return _list[_index]!; } } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/CSharpTest2/Recommendations/GetKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class GetKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int Goo { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyPrivate() { await VerifyKeywordAsync( @"class C { int Goo { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyAttribute() { await VerifyKeywordAsync( @"class C { int Goo { [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertySet() { await VerifyKeywordAsync( @"class C { int Goo { set; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertySetAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { set; private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertySetAndAttribute() { await VerifyKeywordAsync( @"class C { int Goo { set; [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertySetAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { set; [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSetAccessorBlock() { await VerifyKeywordAsync( @"class C { int Goo { set { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSetAccessorBlockAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { set { } private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSetAccessorBlockAndAttribute() { await VerifyKeywordAsync( @"class C { int Goo { set { } [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSetAccessorBlockAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { set { } [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPropertyGetKeyword() { await VerifyAbsenceAsync( @"class C { int Goo { get $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPropertyGetAccessor() { await VerifyAbsenceAsync( @"class C { int Goo { get; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEvent() { await VerifyAbsenceAsync( @"class C { event Goo E { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexer() { await VerifyKeywordAsync( @"class C { int this[int i] { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerSet() { await VerifyKeywordAsync( @"class C { int this[int i] { set; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerSetAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { set; private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerSetAndAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { set; [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerSetAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { set; [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerSetBlock() { await VerifyKeywordAsync( @"class C { int this[int i] { set { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerSetBlockAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { set { } private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerSetBlockAndAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { set { } [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerSetBlockAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { set { } [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIndexerGetKeyword() { await VerifyAbsenceAsync( @"class C { int this[int i] { get $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIndexerGetAccessor() { await VerifyAbsenceAsync( @"class C { int this[int i] { get; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeSemicolon() { await VerifyKeywordAsync( @"class C { int this[int i] { $$; }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtectedInternal() { await VerifyKeywordAsync( @"class C { int this[int i] { protected internal $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternalProtected() { await VerifyKeywordAsync( @"class C { int this[int i] { internal protected $$ }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class GetKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int Goo { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyPrivate() { await VerifyKeywordAsync( @"class C { int Goo { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyAttribute() { await VerifyKeywordAsync( @"class C { int Goo { [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertySet() { await VerifyKeywordAsync( @"class C { int Goo { set; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertySetAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { set; private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertySetAndAttribute() { await VerifyKeywordAsync( @"class C { int Goo { set; [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertySetAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { set; [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSetAccessorBlock() { await VerifyKeywordAsync( @"class C { int Goo { set { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSetAccessorBlockAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { set { } private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSetAccessorBlockAndAttribute() { await VerifyKeywordAsync( @"class C { int Goo { set { } [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSetAccessorBlockAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { set { } [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPropertyGetKeyword() { await VerifyAbsenceAsync( @"class C { int Goo { get $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPropertyGetAccessor() { await VerifyAbsenceAsync( @"class C { int Goo { get; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEvent() { await VerifyAbsenceAsync( @"class C { event Goo E { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexer() { await VerifyKeywordAsync( @"class C { int this[int i] { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerSet() { await VerifyKeywordAsync( @"class C { int this[int i] { set; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerSetAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { set; private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerSetAndAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { set; [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerSetAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { set; [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerSetBlock() { await VerifyKeywordAsync( @"class C { int this[int i] { set { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerSetBlockAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { set { } private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerSetBlockAndAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { set { } [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerSetBlockAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { set { } [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIndexerGetKeyword() { await VerifyAbsenceAsync( @"class C { int this[int i] { get $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIndexerGetAccessor() { await VerifyAbsenceAsync( @"class C { int this[int i] { get; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeSemicolon() { await VerifyKeywordAsync( @"class C { int this[int i] { $$; }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtectedInternal() { await VerifyKeywordAsync( @"class C { int this[int i] { protected internal $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternalProtected() { await VerifyKeywordAsync( @"class C { int this[int i] { internal protected $$ }"); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/DuplicatedGuidsBecomeCircularReferential.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProjectGuid>{C71872E2-0D54-4C4E-B6A9-8C1726B7B78C}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>ReferenceTest</RootNamespace> <AssemblyName>ReferenceTest</AssemblyName> <TargetFrameworkVersion>v4.8</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Xml" /> <Reference Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="FooClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Library1\Library1.csproj"> <Project>{695A589E-ACF6-4AE2-9B45-F84CF63CF0FA}</Project> <Name>Library1</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProjectGuid>{C71872E2-0D54-4C4E-B6A9-8C1726B7B78C}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>ReferenceTest</RootNamespace> <AssemblyName>ReferenceTest</AssemblyName> <TargetFrameworkVersion>v4.8</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Xml" /> <Reference Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="FooClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Library1\Library1.csproj"> <Project>{695A589E-ACF6-4AE2-9B45-F84CF63CF0FA}</Project> <Name>Library1</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/Core/Portable/Diagnostics/AnalyzerUpdateArgsId.cs
// Licensed to the .NET Foundation under one or more 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.Common; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Base type of a type that is used as <see cref="UpdatedEventArgs.Id"/> for live diagnostic /// </summary> internal class AnalyzerUpdateArgsId : BuildToolId.Base<DiagnosticAnalyzer>, ISupportLiveUpdate { public DiagnosticAnalyzer Analyzer => _Field1!; protected AnalyzerUpdateArgsId(DiagnosticAnalyzer analyzer) : base(analyzer) { } public override string BuildTool => Analyzer.GetAnalyzerAssemblyName(); } }
// Licensed to the .NET Foundation under one or more 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.Common; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Base type of a type that is used as <see cref="UpdatedEventArgs.Id"/> for live diagnostic /// </summary> internal class AnalyzerUpdateArgsId : BuildToolId.Base<DiagnosticAnalyzer>, ISupportLiveUpdate { public DiagnosticAnalyzer Analyzer => _Field1!; protected AnalyzerUpdateArgsId(DiagnosticAnalyzer analyzer) : base(analyzer) { } public override string BuildTool => Analyzer.GetAnalyzerAssemblyName(); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/VisualBasic/Portable/Structure/Providers/DoLoopBlockStructureProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class DoLoopBlockStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of DoLoopBlockSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, node As DoLoopBlockSyntax, ByRef spans As TemporaryArray(Of BlockSpan), options As BlockStructureOptions, cancellationToken As CancellationToken) spans.AddIfNotNull(CreateBlockSpanFromBlock( node, node.DoStatement, autoCollapse:=False, type:=BlockTypes.Loop, isCollapsible:=True)) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class DoLoopBlockStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of DoLoopBlockSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, node As DoLoopBlockSyntax, ByRef spans As TemporaryArray(Of BlockSpan), options As BlockStructureOptions, cancellationToken As CancellationToken) spans.AddIfNotNull(CreateBlockSpanFromBlock( node, node.DoStatement, autoCollapse:=False, type:=BlockTypes.Loop, isCollapsible:=True)) End Sub End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/Test2/FindReferences/FindReferencesTests.LabelSymbols.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestLabel1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void Goo() { $${|Definition:Goo|}: int Goo; goto [|Goo|]; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestLabel2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void Goo() { {|Definition:Goo|}: int Goo; goto [|$$Goo|]; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(529060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529060")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestNumericLabel1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M Sub Main() label1: GoTo $$[|200|] {|Definition:200|}: GoTo label1 End Sub End Module </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(529060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529060")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestNumericLabel2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M Sub Main() label1: GoTo [|200|] {|Definition:$$200|}: GoTo label1 End Sub End Module </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestLabelInSourceGeneratedDocument(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <DocumentFromSourceGenerator> class C { void Goo() { $${|Definition:Goo|}: int Goo; goto [|Goo|]; } } </DocumentFromSourceGenerator> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestLabel1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void Goo() { $${|Definition:Goo|}: int Goo; goto [|Goo|]; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestLabel2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void Goo() { {|Definition:Goo|}: int Goo; goto [|$$Goo|]; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(529060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529060")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestNumericLabel1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M Sub Main() label1: GoTo $$[|200|] {|Definition:200|}: GoTo label1 End Sub End Module </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(529060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529060")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestNumericLabel2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M Sub Main() label1: GoTo [|200|] {|Definition:$$200|}: GoTo label1 End Sub End Module </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestLabelInSourceGeneratedDocument(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <DocumentFromSourceGenerator> class C { void Goo() { $${|Definition:Goo|}: int Goo; goto [|Goo|]; } } </DocumentFromSourceGenerator> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Features/VisualBasic/Portable/SignatureHelp/ObjectCreationExpressionSignatureHelpProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.DocumentationComments Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp <ExportSignatureHelpProvider("ObjectCreationExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]> Partial Friend Class ObjectCreationExpressionSignatureHelpProvider Inherits AbstractVisualBasicSignatureHelpProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean Return ch = "("c OrElse ch = ","c End Function Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean Return ch = ")"c End Function Private Shared Function GetCurrentArgumentState(root As SyntaxNode, position As Integer, syntaxFacts As ISyntaxFactsService, currentSpan As TextSpan, cancellationToken As CancellationToken) As SignatureHelpState Dim expression As ObjectCreationExpressionSyntax = Nothing If TryGetObjectCreationExpression(root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, expression) AndAlso currentSpan.Start = SignatureHelpUtilities.GetSignatureHelpSpan(expression.ArgumentList).Start Then Return SignatureHelpUtilities.GetSignatureHelpState(expression.ArgumentList, position) End If Return Nothing End Function Private Shared Function TryGetObjectCreationExpression(root As SyntaxNode, position As Integer, syntaxFacts As ISyntaxFactsService, triggerReason As SignatureHelpTriggerReason, cancellationToken As CancellationToken, ByRef expression As ObjectCreationExpressionSyntax) As Boolean If Not CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, AddressOf IsTriggerToken, AddressOf IsArgumentListToken, cancellationToken, expression) Then Return False End If Return expression.ArgumentList IsNot Nothing End Function Private Shared Function IsTriggerToken(token As SyntaxToken) As Boolean Return (token.Kind = SyntaxKind.OpenParenToken OrElse token.Kind = SyntaxKind.CommaToken) AndAlso TypeOf token.Parent Is ArgumentListSyntax AndAlso TypeOf token.Parent.Parent Is ObjectCreationExpressionSyntax End Function Private Shared Function IsArgumentListToken(node As ObjectCreationExpressionSyntax, token As SyntaxToken) As Boolean Return node.ArgumentList IsNot Nothing AndAlso node.ArgumentList.Span.Contains(token.SpanStart) AndAlso token <> node.ArgumentList.CloseParenToken End Function Protected Overrides Async Function GetItemsWorkerAsync(document As Document, position As Integer, triggerInfo As SignatureHelpTriggerInfo, options As SignatureHelpOptions, cancellationToken As CancellationToken) As Task(Of SignatureHelpItems) Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim objectCreationExpression As ObjectCreationExpressionSyntax = Nothing If Not TryGetObjectCreationExpression(root, position, document.GetLanguageService(Of ISyntaxFactsService), triggerInfo.TriggerReason, cancellationToken, objectCreationExpression) Then Return Nothing End If Dim semanticModel = Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False) Dim type = TryCast(semanticModel.GetTypeInfo(objectCreationExpression, cancellationToken).Type, INamedTypeSymbol) If type Is Nothing Then Return Nothing End If Dim within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken) If within Is Nothing Then Return Nothing End If Dim structuralTypeDisplayService = document.GetLanguageService(Of IStructuralTypeDisplayService)() Dim documentationCommentFormattingService = document.GetLanguageService(Of IDocumentationCommentFormattingService)() Dim textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(objectCreationExpression.ArgumentList) Dim syntaxFacts = document.GetLanguageService(Of ISyntaxFactsService) Dim itemsAndSelected = If(type.TypeKind = TypeKind.Delegate, GetDelegateTypeConstructors(objectCreationExpression, semanticModel, structuralTypeDisplayService, documentationCommentFormattingService, type), GetNormalTypeConstructors(document, objectCreationExpression, semanticModel, structuralTypeDisplayService, type, within, options, cancellationToken)) Return CreateSignatureHelpItems(itemsAndSelected.items, textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), itemsAndSelected.selectedItem) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.DocumentationComments Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp <ExportSignatureHelpProvider("ObjectCreationExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]> Partial Friend Class ObjectCreationExpressionSignatureHelpProvider Inherits AbstractVisualBasicSignatureHelpProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean Return ch = "("c OrElse ch = ","c End Function Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean Return ch = ")"c End Function Private Shared Function GetCurrentArgumentState(root As SyntaxNode, position As Integer, syntaxFacts As ISyntaxFactsService, currentSpan As TextSpan, cancellationToken As CancellationToken) As SignatureHelpState Dim expression As ObjectCreationExpressionSyntax = Nothing If TryGetObjectCreationExpression(root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, expression) AndAlso currentSpan.Start = SignatureHelpUtilities.GetSignatureHelpSpan(expression.ArgumentList).Start Then Return SignatureHelpUtilities.GetSignatureHelpState(expression.ArgumentList, position) End If Return Nothing End Function Private Shared Function TryGetObjectCreationExpression(root As SyntaxNode, position As Integer, syntaxFacts As ISyntaxFactsService, triggerReason As SignatureHelpTriggerReason, cancellationToken As CancellationToken, ByRef expression As ObjectCreationExpressionSyntax) As Boolean If Not CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, AddressOf IsTriggerToken, AddressOf IsArgumentListToken, cancellationToken, expression) Then Return False End If Return expression.ArgumentList IsNot Nothing End Function Private Shared Function IsTriggerToken(token As SyntaxToken) As Boolean Return (token.Kind = SyntaxKind.OpenParenToken OrElse token.Kind = SyntaxKind.CommaToken) AndAlso TypeOf token.Parent Is ArgumentListSyntax AndAlso TypeOf token.Parent.Parent Is ObjectCreationExpressionSyntax End Function Private Shared Function IsArgumentListToken(node As ObjectCreationExpressionSyntax, token As SyntaxToken) As Boolean Return node.ArgumentList IsNot Nothing AndAlso node.ArgumentList.Span.Contains(token.SpanStart) AndAlso token <> node.ArgumentList.CloseParenToken End Function Protected Overrides Async Function GetItemsWorkerAsync(document As Document, position As Integer, triggerInfo As SignatureHelpTriggerInfo, options As SignatureHelpOptions, cancellationToken As CancellationToken) As Task(Of SignatureHelpItems) Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim objectCreationExpression As ObjectCreationExpressionSyntax = Nothing If Not TryGetObjectCreationExpression(root, position, document.GetLanguageService(Of ISyntaxFactsService), triggerInfo.TriggerReason, cancellationToken, objectCreationExpression) Then Return Nothing End If Dim semanticModel = Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False) Dim type = TryCast(semanticModel.GetTypeInfo(objectCreationExpression, cancellationToken).Type, INamedTypeSymbol) If type Is Nothing Then Return Nothing End If Dim within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken) If within Is Nothing Then Return Nothing End If Dim structuralTypeDisplayService = document.GetLanguageService(Of IStructuralTypeDisplayService)() Dim documentationCommentFormattingService = document.GetLanguageService(Of IDocumentationCommentFormattingService)() Dim textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(objectCreationExpression.ArgumentList) Dim syntaxFacts = document.GetLanguageService(Of ISyntaxFactsService) Dim itemsAndSelected = If(type.TypeKind = TypeKind.Delegate, GetDelegateTypeConstructors(objectCreationExpression, semanticModel, structuralTypeDisplayService, documentationCommentFormattingService, type), GetNormalTypeConstructors(document, objectCreationExpression, semanticModel, structuralTypeDisplayService, type, within, options, cancellationToken)) Return CreateSignatureHelpItems(itemsAndSelected.items, textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), itemsAndSelected.selectedItem) End Function End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.it.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="it" original="../BasicVSResources.resx"> <body> <trans-unit id="Add_missing_imports_on_paste"> <source>Add missing imports on paste</source> <target state="translated">Aggiungi Import mancanti dopo operazione Incolla</target> <note>'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="Collapse_imports_on_file_open"> <source>Collapse Imports on file open</source> <target state="translated">Comprimi importazioni all'apertura del file</target> <note /> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators: = &lt;&gt; &lt; &gt; &lt;= &gt;= Like Is</source> <target state="translated">In operatori relazionali: = &lt;&gt; &lt; &gt; &lt;= &gt;= Like Is</target> <note /> </trans-unit> <trans-unit id="Insert_apostrophe_at_the_start_of_new_lines_when_writing_apostrophe_comments"> <source>Insert ' at the start of new lines when writing ' comments</source> <target state="translated">Inserisci * all'inizio di nuove righe quando si scrivono commenti '</target> <note /> </trans-unit> <trans-unit id="Microsoft_Visual_Basic"> <source>Microsoft Visual Basic</source> <target state="translated">Microsoft Visual Basic</target> <note /> </trans-unit> <trans-unit id="Insert_Snippet"> <source>Insert Snippet</source> <target state="translated">Inserisci frammento</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="Automatic_insertion_of_Interface_and_MustOverride_members"> <source>Automatic _insertion of Interface and MustOverride members</source> <target state="translated">_Inserimento automatico di membri Interface e MustOverride</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">Mai</target> <note /> </trans-unit> <trans-unit id="Prefer_IsNot_expression"> <source>Prefer 'IsNot' expression</source> <target state="translated">Preferisci l'espressione 'IsNot'</target> <note /> </trans-unit> <trans-unit id="Prefer_Is_Nothing_for_reference_equality_checks"> <source>Prefer 'Is Nothing' for reference equality checks</source> <target state="translated">Preferisci 'Is Nothing' per i controlli di uguaglianza dei riferimenti</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_object_creation"> <source>Prefer simplified object creation</source> <target state="translated">Preferire la creazione semplificata degli oggetti</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_Imports"> <source>Remove unnecessary Imports</source> <target state="translated">Rimuovi direttive Import non necessarie</target> <note>{Locked="Import"} 'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="Show_hints_for_New_expressions"> <source>Show hints for 'New' expressions</source> <target state="translated">Mostra suggerimenti per le espressioni 'New'</target> <note /> </trans-unit> <trans-unit id="Show_items_from_unimported_namespaces"> <source>Show items from unimported namespaces</source> <target state="translated">Mostra elementi da spazi dei nomi non importati</target> <note /> </trans-unit> <trans-unit id="Show_procedure_line_separators"> <source>_Show procedure line separators</source> <target state="translated">_Mostra separatori di riga routine</target> <note /> </trans-unit> <trans-unit id="Don_t_put_ByRef_on_custom_structure"> <source>_Don't put ByRef on custom structure</source> <target state="translated">_Non inserire ByRef nella struttura personalizzata</target> <note /> </trans-unit> <trans-unit id="Editor_Help"> <source>Editor Help</source> <target state="translated">Guida Editor</target> <note /> </trans-unit> <trans-unit id="A_utomatic_insertion_of_end_constructs"> <source>A_utomatic insertion of end constructs</source> <target state="translated">Inserimento a_utomatico di costrutti End</target> <note /> </trans-unit> <trans-unit id="Highlight_related_keywords_under_cursor"> <source>Highlight related _keywords under cursor</source> <target state="translated">Evidenzia _parole chiave correlate sotto il cursore</target> <note /> </trans-unit> <trans-unit id="Highlight_references_to_symbol_under_cursor"> <source>_Highlight references to symbol under cursor</source> <target state="translated">_Evidenzia riferimenti a simbolo sotto il cursore</target> <note /> </trans-unit> <trans-unit id="Pretty_listing_reformatting_of_code"> <source>_Pretty listing (reformatting) of code</source> <target state="translated">_Riformattazione del codice</target> <note /> </trans-unit> <trans-unit id="Enter_outlining_mode_when_files_open"> <source>_Enter outlining mode when files open</source> <target state="translated">Attiva m_odalità struttura all'apertura dei file</target> <note /> </trans-unit> <trans-unit id="Extract_Method"> <source>Extract Method</source> <target state="translated">Estrai metodo</target> <note /> </trans-unit> <trans-unit id="Generate_XML_documentation_comments_for"> <source>_Generate XML documentation comments for '''</source> <target state="translated">_Genera commenti in formato documentazione XML per '''</target> <note>{Locked="'''"} "'''" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Highlighting"> <source>Highlighting</source> <target state="translated">Evidenziazione</target> <note /> </trans-unit> <trans-unit id="Optimize_for_solution_size"> <source>Optimize for solution size</source> <target state="translated">Ottimizza in base alle dimensioni della soluzione</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">Normale</target> <note /> </trans-unit> <trans-unit id="Show_remarks_in_Quick_Info"> <source>Show remarks in Quick Info</source> <target state="translated">Mostra i commenti in Informazioni rapide</target> <note /> </trans-unit> <trans-unit id="Small"> <source>Small</source> <target state="translated">Piccola</target> <note /> </trans-unit> <trans-unit id="Performance"> <source>Performance</source> <target state="translated">Prestazioni</target> <note /> </trans-unit> <trans-unit id="Show_preview_for_rename_tracking"> <source>Show preview for rename _tracking</source> <target state="translated">Mostra anteprima per verifica _ridenominazione</target> <note /> </trans-unit> <trans-unit id="Navigate_to_Object_Browser_for_symbols_defined_in_metadata"> <source>_Navigate to Object Browser for symbols defined in metadata</source> <target state="translated">_Passa a Visualizzatore oggetti per i simboli definiti nei metadati</target> <note /> </trans-unit> <trans-unit id="Go_to_Definition"> <source>Go to Definition</source> <target state="translated">Vai a definizione</target> <note /> </trans-unit> <trans-unit id="Import_Directives"> <source>Import Directives</source> <target state="translated">Direttive import</target> <note /> </trans-unit> <trans-unit id="Sort_imports"> <source>Sort imports</source> <target state="translated">Ordina direttive Import</target> <note>{Locked="Import"} 'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="Suggest_imports_for_types_in_NuGet_packages"> <source>Suggest imports for types in _NuGet packages</source> <target state="translated">Suggerisci le direttive import per i tipi in pacchetti _NuGet</target> <note /> </trans-unit> <trans-unit id="Suggest_imports_for_types_in_reference_assemblies"> <source>Suggest imports for types in _reference assemblies</source> <target state="translated">Suggerisci le direttive import per i tipi in _assembly di riferimento</target> <note /> </trans-unit> <trans-unit id="Place_System_directives_first_when_sorting_imports"> <source>_Place 'System' directives first when sorting imports</source> <target state="translated">_Inserisci prima le direttive 'System' durante l'ordinamento delle direttive import</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_Me"> <source>Qualify event access with 'Me'</source> <target state="translated">Qualifica l'accesso agli eventi con 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_Me"> <source>Qualify field access with 'Me'</source> <target state="translated">Qualifica l'accesso ai campi con 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_Me"> <source>Qualify method access with 'Me'</source> <target state="translated">Qualifica l'accesso ai metodi con 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_Me"> <source>Qualify property access with 'Me'</source> <target state="translated">Qualifica l'accesso alle proprietà con 'Me'</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_Me"> <source>Do not prefer 'Me.'</source> <target state="translated">Non preferire 'Me.'</target> <note /> </trans-unit> <trans-unit id="Prefer_Me"> <source>Prefer 'Me.'</source> <target state="translated">Preferisci 'Me.'</target> <note /> </trans-unit> <trans-unit id="Me_preferences_colon"> <source>'Me.' preferences:</source> <target state="translated">'Preferenze per 'Me.':</target> <note /> </trans-unit> <trans-unit id="Predefined_type_preferences_colon"> <source>Predefined type preferences:</source> <target state="translated">Preferenze per tipi predefiniti:</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">_Evidenzia le parti corrispondenti di voci dell'elenco di completamento</target> <note /> </trans-unit> <trans-unit id="Show_completion_item_filters"> <source>Show completion item _filters</source> <target state="translated">Mostra i _filtri per le voci di completamento</target> <note /> </trans-unit> <trans-unit id="Completion_Lists"> <source>Completion Lists</source> <target state="translated">Elenchi di completamento</target> <note /> </trans-unit> <trans-unit id="Enter_key_behavior_colon"> <source>Enter key behavior:</source> <target state="translated">Comportamento del tasto INVIO:</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">Aggi_ungi una nuova riga dopo INVIO alla fine della parola digitata</target> <note /> </trans-unit> <trans-unit id="Always_add_new_line_on_enter"> <source>_Always add new line on enter</source> <target state="translated">_Aggiungi sempre una nuova riga dopo INVIO</target> <note /> </trans-unit> <trans-unit id="Never_add_new_line_on_enter"> <source>_Never add new line on enter</source> <target state="translated">_Non aggiungere mai una nuova riga dopo INVIO</target> <note /> </trans-unit> <trans-unit id="Always_include_snippets"> <source>Always include snippets</source> <target state="translated">Includi sempre i frammenti</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">Includi i frammenti quando si digita ?+TAB dopo un identificatore</target> <note /> </trans-unit> <trans-unit id="Never_include_snippets"> <source>Never include snippets</source> <target state="translated">Non includere mai i frammenti</target> <note /> </trans-unit> <trans-unit id="Snippets_behavior"> <source>Snippets behavior</source> <target state="translated">Comportamento dei frammenti</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">Mostra _elenco di completamento dopo l'eliminazione di un carattere</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">Mo_stra elenco di completamento dopo la digitazione di un carattere</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">Variabile locale inutilizzata</target> <note /> </trans-unit> <trans-unit id="VB_Coding_Conventions"> <source>VB Coding Conventions</source> <target state="translated">Convenzioni di scrittura codice VB</target> <note /> </trans-unit> <trans-unit id="nothing_checking_colon"> <source>'nothing' checking:</source> <target state="translated">'Controllo 'nothing':</target> <note /> </trans-unit> <trans-unit id="Fade_out_unused_imports"> <source>Fade out unused imports</source> <target state="translated">Applica dissolvenza a direttive import non usate</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">Segnala segnaposto non validi in chiamate 'String.Format'</target> <note /> </trans-unit> <trans-unit id="Separate_import_directive_groups"> <source>Separate import directive groups</source> <target state="translated">Separa gruppi di direttive import</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators: ^ * / \ Mod + - &amp; &lt;&lt; &gt;&gt;</source> <target state="translated">In operatori aritmetici: ^ * / \ Mod + - &amp; &lt;&lt; &gt;&gt;</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators: And AndAlso Or OrElse</source> <target state="translated">In altri operatori binari: And AndAlso Or OrElse</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="it" original="../BasicVSResources.resx"> <body> <trans-unit id="Add_missing_imports_on_paste"> <source>Add missing imports on paste</source> <target state="translated">Aggiungi Import mancanti dopo operazione Incolla</target> <note>'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="Collapse_imports_on_file_open"> <source>Collapse Imports on file open</source> <target state="translated">Comprimi importazioni all'apertura del file</target> <note /> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators: = &lt;&gt; &lt; &gt; &lt;= &gt;= Like Is</source> <target state="translated">In operatori relazionali: = &lt;&gt; &lt; &gt; &lt;= &gt;= Like Is</target> <note /> </trans-unit> <trans-unit id="Insert_apostrophe_at_the_start_of_new_lines_when_writing_apostrophe_comments"> <source>Insert ' at the start of new lines when writing ' comments</source> <target state="translated">Inserisci * all'inizio di nuove righe quando si scrivono commenti '</target> <note /> </trans-unit> <trans-unit id="Microsoft_Visual_Basic"> <source>Microsoft Visual Basic</source> <target state="translated">Microsoft Visual Basic</target> <note /> </trans-unit> <trans-unit id="Insert_Snippet"> <source>Insert Snippet</source> <target state="translated">Inserisci frammento</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="Automatic_insertion_of_Interface_and_MustOverride_members"> <source>Automatic _insertion of Interface and MustOverride members</source> <target state="translated">_Inserimento automatico di membri Interface e MustOverride</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">Mai</target> <note /> </trans-unit> <trans-unit id="Prefer_IsNot_expression"> <source>Prefer 'IsNot' expression</source> <target state="translated">Preferisci l'espressione 'IsNot'</target> <note /> </trans-unit> <trans-unit id="Prefer_Is_Nothing_for_reference_equality_checks"> <source>Prefer 'Is Nothing' for reference equality checks</source> <target state="translated">Preferisci 'Is Nothing' per i controlli di uguaglianza dei riferimenti</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_object_creation"> <source>Prefer simplified object creation</source> <target state="translated">Preferire la creazione semplificata degli oggetti</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_Imports"> <source>Remove unnecessary Imports</source> <target state="translated">Rimuovi direttive Import non necessarie</target> <note>{Locked="Import"} 'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="Show_hints_for_New_expressions"> <source>Show hints for 'New' expressions</source> <target state="translated">Mostra suggerimenti per le espressioni 'New'</target> <note /> </trans-unit> <trans-unit id="Show_items_from_unimported_namespaces"> <source>Show items from unimported namespaces</source> <target state="translated">Mostra elementi da spazi dei nomi non importati</target> <note /> </trans-unit> <trans-unit id="Show_procedure_line_separators"> <source>_Show procedure line separators</source> <target state="translated">_Mostra separatori di riga routine</target> <note /> </trans-unit> <trans-unit id="Don_t_put_ByRef_on_custom_structure"> <source>_Don't put ByRef on custom structure</source> <target state="translated">_Non inserire ByRef nella struttura personalizzata</target> <note /> </trans-unit> <trans-unit id="Editor_Help"> <source>Editor Help</source> <target state="translated">Guida Editor</target> <note /> </trans-unit> <trans-unit id="A_utomatic_insertion_of_end_constructs"> <source>A_utomatic insertion of end constructs</source> <target state="translated">Inserimento a_utomatico di costrutti End</target> <note /> </trans-unit> <trans-unit id="Highlight_related_keywords_under_cursor"> <source>Highlight related _keywords under cursor</source> <target state="translated">Evidenzia _parole chiave correlate sotto il cursore</target> <note /> </trans-unit> <trans-unit id="Highlight_references_to_symbol_under_cursor"> <source>_Highlight references to symbol under cursor</source> <target state="translated">_Evidenzia riferimenti a simbolo sotto il cursore</target> <note /> </trans-unit> <trans-unit id="Pretty_listing_reformatting_of_code"> <source>_Pretty listing (reformatting) of code</source> <target state="translated">_Riformattazione del codice</target> <note /> </trans-unit> <trans-unit id="Enter_outlining_mode_when_files_open"> <source>_Enter outlining mode when files open</source> <target state="translated">Attiva m_odalità struttura all'apertura dei file</target> <note /> </trans-unit> <trans-unit id="Extract_Method"> <source>Extract Method</source> <target state="translated">Estrai metodo</target> <note /> </trans-unit> <trans-unit id="Generate_XML_documentation_comments_for"> <source>_Generate XML documentation comments for '''</source> <target state="translated">_Genera commenti in formato documentazione XML per '''</target> <note>{Locked="'''"} "'''" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Highlighting"> <source>Highlighting</source> <target state="translated">Evidenziazione</target> <note /> </trans-unit> <trans-unit id="Optimize_for_solution_size"> <source>Optimize for solution size</source> <target state="translated">Ottimizza in base alle dimensioni della soluzione</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">Normale</target> <note /> </trans-unit> <trans-unit id="Show_remarks_in_Quick_Info"> <source>Show remarks in Quick Info</source> <target state="translated">Mostra i commenti in Informazioni rapide</target> <note /> </trans-unit> <trans-unit id="Small"> <source>Small</source> <target state="translated">Piccola</target> <note /> </trans-unit> <trans-unit id="Performance"> <source>Performance</source> <target state="translated">Prestazioni</target> <note /> </trans-unit> <trans-unit id="Show_preview_for_rename_tracking"> <source>Show preview for rename _tracking</source> <target state="translated">Mostra anteprima per verifica _ridenominazione</target> <note /> </trans-unit> <trans-unit id="Navigate_to_Object_Browser_for_symbols_defined_in_metadata"> <source>_Navigate to Object Browser for symbols defined in metadata</source> <target state="translated">_Passa a Visualizzatore oggetti per i simboli definiti nei metadati</target> <note /> </trans-unit> <trans-unit id="Go_to_Definition"> <source>Go to Definition</source> <target state="translated">Vai a definizione</target> <note /> </trans-unit> <trans-unit id="Import_Directives"> <source>Import Directives</source> <target state="translated">Direttive import</target> <note /> </trans-unit> <trans-unit id="Sort_imports"> <source>Sort imports</source> <target state="translated">Ordina direttive Import</target> <note>{Locked="Import"} 'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="Suggest_imports_for_types_in_NuGet_packages"> <source>Suggest imports for types in _NuGet packages</source> <target state="translated">Suggerisci le direttive import per i tipi in pacchetti _NuGet</target> <note /> </trans-unit> <trans-unit id="Suggest_imports_for_types_in_reference_assemblies"> <source>Suggest imports for types in _reference assemblies</source> <target state="translated">Suggerisci le direttive import per i tipi in _assembly di riferimento</target> <note /> </trans-unit> <trans-unit id="Place_System_directives_first_when_sorting_imports"> <source>_Place 'System' directives first when sorting imports</source> <target state="translated">_Inserisci prima le direttive 'System' durante l'ordinamento delle direttive import</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_Me"> <source>Qualify event access with 'Me'</source> <target state="translated">Qualifica l'accesso agli eventi con 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_Me"> <source>Qualify field access with 'Me'</source> <target state="translated">Qualifica l'accesso ai campi con 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_Me"> <source>Qualify method access with 'Me'</source> <target state="translated">Qualifica l'accesso ai metodi con 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_Me"> <source>Qualify property access with 'Me'</source> <target state="translated">Qualifica l'accesso alle proprietà con 'Me'</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_Me"> <source>Do not prefer 'Me.'</source> <target state="translated">Non preferire 'Me.'</target> <note /> </trans-unit> <trans-unit id="Prefer_Me"> <source>Prefer 'Me.'</source> <target state="translated">Preferisci 'Me.'</target> <note /> </trans-unit> <trans-unit id="Me_preferences_colon"> <source>'Me.' preferences:</source> <target state="translated">'Preferenze per 'Me.':</target> <note /> </trans-unit> <trans-unit id="Predefined_type_preferences_colon"> <source>Predefined type preferences:</source> <target state="translated">Preferenze per tipi predefiniti:</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">_Evidenzia le parti corrispondenti di voci dell'elenco di completamento</target> <note /> </trans-unit> <trans-unit id="Show_completion_item_filters"> <source>Show completion item _filters</source> <target state="translated">Mostra i _filtri per le voci di completamento</target> <note /> </trans-unit> <trans-unit id="Completion_Lists"> <source>Completion Lists</source> <target state="translated">Elenchi di completamento</target> <note /> </trans-unit> <trans-unit id="Enter_key_behavior_colon"> <source>Enter key behavior:</source> <target state="translated">Comportamento del tasto INVIO:</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">Aggi_ungi una nuova riga dopo INVIO alla fine della parola digitata</target> <note /> </trans-unit> <trans-unit id="Always_add_new_line_on_enter"> <source>_Always add new line on enter</source> <target state="translated">_Aggiungi sempre una nuova riga dopo INVIO</target> <note /> </trans-unit> <trans-unit id="Never_add_new_line_on_enter"> <source>_Never add new line on enter</source> <target state="translated">_Non aggiungere mai una nuova riga dopo INVIO</target> <note /> </trans-unit> <trans-unit id="Always_include_snippets"> <source>Always include snippets</source> <target state="translated">Includi sempre i frammenti</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">Includi i frammenti quando si digita ?+TAB dopo un identificatore</target> <note /> </trans-unit> <trans-unit id="Never_include_snippets"> <source>Never include snippets</source> <target state="translated">Non includere mai i frammenti</target> <note /> </trans-unit> <trans-unit id="Snippets_behavior"> <source>Snippets behavior</source> <target state="translated">Comportamento dei frammenti</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">Mostra _elenco di completamento dopo l'eliminazione di un carattere</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">Mo_stra elenco di completamento dopo la digitazione di un carattere</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">Variabile locale inutilizzata</target> <note /> </trans-unit> <trans-unit id="VB_Coding_Conventions"> <source>VB Coding Conventions</source> <target state="translated">Convenzioni di scrittura codice VB</target> <note /> </trans-unit> <trans-unit id="nothing_checking_colon"> <source>'nothing' checking:</source> <target state="translated">'Controllo 'nothing':</target> <note /> </trans-unit> <trans-unit id="Fade_out_unused_imports"> <source>Fade out unused imports</source> <target state="translated">Applica dissolvenza a direttive import non usate</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">Segnala segnaposto non validi in chiamate 'String.Format'</target> <note /> </trans-unit> <trans-unit id="Separate_import_directive_groups"> <source>Separate import directive groups</source> <target state="translated">Separa gruppi di direttive import</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators: ^ * / \ Mod + - &amp; &lt;&lt; &gt;&gt;</source> <target state="translated">In operatori aritmetici: ^ * / \ Mod + - &amp; &lt;&lt; &gt;&gt;</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators: And AndAlso Or OrElse</source> <target state="translated">In altri operatori binari: And AndAlso Or OrElse</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForNullableCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.UseCoalesceExpression { [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.UseCoalesceExpressionForNullable), Shared] internal class UseCoalesceExpressionForNullableCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseCoalesceExpressionForNullableCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseCoalesceExpressionForNullableDiagnosticId); protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary); public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_coalesce_expression, nameof(AnalyzersResources.Use_coalesce_expression)); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var expressionTypeOpt = semanticModel.Compilation.ExpressionOfTType(); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>(); var generator = editor.Generator; var root = editor.OriginalRoot; foreach (var diagnostic in diagnostics) { var conditionalExpression = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true); var conditionExpression = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan); var whenPart = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan); syntaxFacts.GetPartsOfConditionalExpression( conditionalExpression, out var condition, out var whenTrue, out var whenFalse); editor.ReplaceNode(conditionalExpression, (c, g) => { syntaxFacts.GetPartsOfConditionalExpression( c, out var currentCondition, out var currentWhenTrue, out var currentWhenFalse); var coalesceExpression = whenPart == whenTrue ? g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenTrue)) : g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenFalse)); if (semanticFacts.IsInExpressionTree( semanticModel, conditionalExpression, expressionTypeOpt, cancellationToken)) { coalesceExpression = coalesceExpression.WithAdditionalAnnotations( WarningAnnotation.Create(AnalyzersResources.Changes_to_expression_trees_may_result_in_behavior_changes_at_runtime)); } return coalesceExpression; }); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.UseCoalesceExpression { [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.UseCoalesceExpressionForNullable), Shared] internal class UseCoalesceExpressionForNullableCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseCoalesceExpressionForNullableCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseCoalesceExpressionForNullableDiagnosticId); protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary); public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_coalesce_expression, nameof(AnalyzersResources.Use_coalesce_expression)); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var expressionTypeOpt = semanticModel.Compilation.ExpressionOfTType(); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>(); var generator = editor.Generator; var root = editor.OriginalRoot; foreach (var diagnostic in diagnostics) { var conditionalExpression = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true); var conditionExpression = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan); var whenPart = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan); syntaxFacts.GetPartsOfConditionalExpression( conditionalExpression, out var condition, out var whenTrue, out var whenFalse); editor.ReplaceNode(conditionalExpression, (c, g) => { syntaxFacts.GetPartsOfConditionalExpression( c, out var currentCondition, out var currentWhenTrue, out var currentWhenFalse); var coalesceExpression = whenPart == whenTrue ? g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenTrue)) : g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenFalse)); if (semanticFacts.IsInExpressionTree( semanticModel, conditionalExpression, expressionTypeOpt, cancellationToken)) { coalesceExpression = coalesceExpression.WithAdditionalAnnotations( WarningAnnotation.Create(AnalyzersResources.Changes_to_expression_trees_may_result_in_behavior_changes_at_runtime)); } return coalesceExpression; }); } } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Def/Progression/GraphQueries/InheritsGraphQuery.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.GraphModel; using Microsoft.VisualStudio.GraphModel.Schemas; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed class InheritsGraphQuery : IGraphQuery { public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); var nodesToProcess = context.InputNodes; for (var depth = 0; depth < context.LinkDepth; depth++) { // This is the list of nodes we created and will process var newNodes = new HashSet<GraphNode>(); foreach (var node in nodesToProcess) { var symbol = graphBuilder.GetSymbol(node, cancellationToken); if (symbol is INamedTypeSymbol namedType) { if (namedType.BaseType != null) { var baseTypeNode = await graphBuilder.AddNodeAsync( namedType.BaseType, relatedNode: node, cancellationToken).ConfigureAwait(false); newNodes.Add(baseTypeNode); graphBuilder.AddLink(node, CodeLinkCategories.InheritsFrom, baseTypeNode, cancellationToken); } else if (namedType.TypeKind == TypeKind.Interface && !namedType.OriginalDefinition.AllInterfaces.IsEmpty) { foreach (var baseNode in namedType.OriginalDefinition.AllInterfaces.Distinct()) { var baseTypeNode = await graphBuilder.AddNodeAsync( baseNode, relatedNode: node, cancellationToken).ConfigureAwait(false); newNodes.Add(baseTypeNode); graphBuilder.AddLink(node, CodeLinkCategories.InheritsFrom, baseTypeNode, cancellationToken); } } } } nodesToProcess = newNodes; } return graphBuilder; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.GraphModel; using Microsoft.VisualStudio.GraphModel.Schemas; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed class InheritsGraphQuery : IGraphQuery { public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); var nodesToProcess = context.InputNodes; for (var depth = 0; depth < context.LinkDepth; depth++) { // This is the list of nodes we created and will process var newNodes = new HashSet<GraphNode>(); foreach (var node in nodesToProcess) { var symbol = graphBuilder.GetSymbol(node, cancellationToken); if (symbol is INamedTypeSymbol namedType) { if (namedType.BaseType != null) { var baseTypeNode = await graphBuilder.AddNodeAsync( namedType.BaseType, relatedNode: node, cancellationToken).ConfigureAwait(false); newNodes.Add(baseTypeNode); graphBuilder.AddLink(node, CodeLinkCategories.InheritsFrom, baseTypeNode, cancellationToken); } else if (namedType.TypeKind == TypeKind.Interface && !namedType.OriginalDefinition.AllInterfaces.IsEmpty) { foreach (var baseNode in namedType.OriginalDefinition.AllInterfaces.Distinct()) { var baseTypeNode = await graphBuilder.AddNodeAsync( baseNode, relatedNode: node, cancellationToken).ConfigureAwait(false); newNodes.Add(baseTypeNode); graphBuilder.AddLink(node, CodeLinkCategories.InheritsFrom, baseTypeNode, cancellationToken); } } } } nodesToProcess = newNodes; } return graphBuilder; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Test/Core/FX/ProcessUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using Xunit; namespace Roslyn.Test.Utilities { public static class ProcessUtilities { /// <summary> /// Launch a process, wait for it to complete, and return output, error, and exit code. /// </summary> public static ProcessResult Run( string fileName, string arguments, string workingDirectory = null, IEnumerable<KeyValuePair<string, string>> additionalEnvironmentVars = null, string stdInput = null, bool redirectStandardInput = false) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); var startInfo = new ProcessStartInfo { FileName = fileName, Arguments = arguments, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = stdInput != null || redirectStandardInput, WorkingDirectory = workingDirectory }; // In case the process is a console application that expects standard input // do not set CreateNoWindow to true to ensure that the input encoding // of both the test and the process fileName is equal. if (stdInput == null) { startInfo.CreateNoWindow = true; } if (additionalEnvironmentVars != null) { foreach (var entry in additionalEnvironmentVars) { startInfo.Environment[entry.Key] = entry.Value; } } using (var process = new Process { StartInfo = startInfo }) { StringBuilder outputBuilder = new StringBuilder(); StringBuilder errorBuilder = new StringBuilder(); process.OutputDataReceived += (sender, args) => { if (args.Data != null) outputBuilder.AppendLine(args.Data); }; process.ErrorDataReceived += (sender, args) => { if (args.Data != null) errorBuilder.AppendLine(args.Data); }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (stdInput != null) { process.StandardInput.Write(stdInput); process.StandardInput.Dispose(); } process.WaitForExit(); // Double check the process has actually exited Debug.Assert(process.HasExited); return new ProcessResult(process.ExitCode, outputBuilder.ToString(), errorBuilder.ToString()); } } /// <summary> /// Launch a process, and return Process object. The process continues to run asynchronously. /// You cannot capture the output. /// </summary> public static Process StartProcess(string fileName, string arguments, string workingDirectory = null) { if (fileName == null) { throw new ArgumentNullException(nameof(fileName)); } var startInfo = new ProcessStartInfo { FileName = fileName, Arguments = arguments, UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = workingDirectory }; Process p = new Process { StartInfo = startInfo }; p.Start(); return p; } public static string RunAndGetOutput(string exeFileName, string arguments = null, int expectedRetCode = 0, string startFolder = null) { ProcessStartInfo startInfo = new ProcessStartInfo(exeFileName); if (arguments != null) { startInfo.Arguments = arguments; } string result = null; startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.UseShellExecute = false; if (startFolder != null) { startInfo.WorkingDirectory = startFolder; } using (var process = System.Diagnostics.Process.Start(startInfo)) { // Do not wait for the child process to exit before reading to the end of its // redirected stream. Read the output stream first and then wait. Doing otherwise // might cause a deadlock. result = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); process.WaitForExit(); Assert.True(expectedRetCode == process.ExitCode, $"Unexpected exit code: {process.ExitCode} (expecting {expectedRetCode}). Process output: {result}. Process error: {error}"); } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using Xunit; namespace Roslyn.Test.Utilities { public static class ProcessUtilities { /// <summary> /// Launch a process, wait for it to complete, and return output, error, and exit code. /// </summary> public static ProcessResult Run( string fileName, string arguments, string workingDirectory = null, IEnumerable<KeyValuePair<string, string>> additionalEnvironmentVars = null, string stdInput = null, bool redirectStandardInput = false) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); var startInfo = new ProcessStartInfo { FileName = fileName, Arguments = arguments, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = stdInput != null || redirectStandardInput, WorkingDirectory = workingDirectory }; // In case the process is a console application that expects standard input // do not set CreateNoWindow to true to ensure that the input encoding // of both the test and the process fileName is equal. if (stdInput == null) { startInfo.CreateNoWindow = true; } if (additionalEnvironmentVars != null) { foreach (var entry in additionalEnvironmentVars) { startInfo.Environment[entry.Key] = entry.Value; } } using (var process = new Process { StartInfo = startInfo }) { StringBuilder outputBuilder = new StringBuilder(); StringBuilder errorBuilder = new StringBuilder(); process.OutputDataReceived += (sender, args) => { if (args.Data != null) outputBuilder.AppendLine(args.Data); }; process.ErrorDataReceived += (sender, args) => { if (args.Data != null) errorBuilder.AppendLine(args.Data); }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (stdInput != null) { process.StandardInput.Write(stdInput); process.StandardInput.Dispose(); } process.WaitForExit(); // Double check the process has actually exited Debug.Assert(process.HasExited); return new ProcessResult(process.ExitCode, outputBuilder.ToString(), errorBuilder.ToString()); } } /// <summary> /// Launch a process, and return Process object. The process continues to run asynchronously. /// You cannot capture the output. /// </summary> public static Process StartProcess(string fileName, string arguments, string workingDirectory = null) { if (fileName == null) { throw new ArgumentNullException(nameof(fileName)); } var startInfo = new ProcessStartInfo { FileName = fileName, Arguments = arguments, UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = workingDirectory }; Process p = new Process { StartInfo = startInfo }; p.Start(); return p; } public static string RunAndGetOutput(string exeFileName, string arguments = null, int expectedRetCode = 0, string startFolder = null) { ProcessStartInfo startInfo = new ProcessStartInfo(exeFileName); if (arguments != null) { startInfo.Arguments = arguments; } string result = null; startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.UseShellExecute = false; if (startFolder != null) { startInfo.WorkingDirectory = startFolder; } using (var process = System.Diagnostics.Process.Start(startInfo)) { // Do not wait for the child process to exit before reading to the end of its // redirected stream. Read the output stream first and then wait. Doing otherwise // might cause a deadlock. result = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); process.WaitForExit(); Assert.True(expectedRetCode == process.ExitCode, $"Unexpected exit code: {process.ExitCode} (expecting {expectedRetCode}). Process output: {result}. Process error: {error}"); } return result; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Scripting/Core/ScriptVariable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Reflection; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// A variable declared by the script. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] public sealed class ScriptVariable { private readonly object _instance; private readonly FieldInfo _field; internal ScriptVariable(object instance, FieldInfo field) { Debug.Assert(instance != null); Debug.Assert(field != null); _instance = instance; _field = field; } /// <summary> /// The name of the variable. /// </summary> public string Name => _field.Name; /// <summary> /// The type of the variable. /// </summary> public Type Type => _field.FieldType; /// <summary> /// True if the variable can't be written to (it's declared as readonly or a constant). /// </summary> public bool IsReadOnly => _field.IsInitOnly || _field.IsLiteral; /// <summary> /// The value of the variable after running the script. /// </summary> /// <exception cref="InvalidOperationException">Variable is read-only or a constant.</exception> /// <exception cref="ArgumentException">The type of the specified <paramref name="value"/> isn't assignable to the type of the variable.</exception> public object Value { get { return _field.GetValue(_instance); } set { if (_field.IsInitOnly) { throw new InvalidOperationException(ScriptingResources.CannotSetReadOnlyVariable); } if (_field.IsLiteral) { throw new InvalidOperationException(ScriptingResources.CannotSetConstantVariable); } _field.SetValue(_instance, value); } } private string GetDebuggerDisplay() => $"{Name}: {Value ?? "<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.Diagnostics; using System.Reflection; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// A variable declared by the script. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] public sealed class ScriptVariable { private readonly object _instance; private readonly FieldInfo _field; internal ScriptVariable(object instance, FieldInfo field) { Debug.Assert(instance != null); Debug.Assert(field != null); _instance = instance; _field = field; } /// <summary> /// The name of the variable. /// </summary> public string Name => _field.Name; /// <summary> /// The type of the variable. /// </summary> public Type Type => _field.FieldType; /// <summary> /// True if the variable can't be written to (it's declared as readonly or a constant). /// </summary> public bool IsReadOnly => _field.IsInitOnly || _field.IsLiteral; /// <summary> /// The value of the variable after running the script. /// </summary> /// <exception cref="InvalidOperationException">Variable is read-only or a constant.</exception> /// <exception cref="ArgumentException">The type of the specified <paramref name="value"/> isn't assignable to the type of the variable.</exception> public object Value { get { return _field.GetValue(_instance); } set { if (_field.IsInitOnly) { throw new InvalidOperationException(ScriptingResources.CannotSetReadOnlyVariable); } if (_field.IsLiteral) { throw new InvalidOperationException(ScriptingResources.CannotSetConstantVariable); } _field.SetValue(_instance, value); } } private string GetDebuggerDisplay() => $"{Name}: {Value ?? "<null>"}"; } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/Core.Wpf/SignatureHelp/ModelUpdatedEventsArgs.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal sealed class ModelUpdatedEventsArgs : EventArgs { public ModelUpdatedEventsArgs(Model? newModel) { NewModel = newModel; } public Model? NewModel { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal sealed class ModelUpdatedEventsArgs : EventArgs { public ModelUpdatedEventsArgs(Model? newModel) { NewModel = newModel; } public Model? NewModel { get; } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/CSharp/Impl/ProjectSystemShim/Interop/ICSInputSet.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop { [ComImport] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [Guid("4D5D4C22-EE19-11d2-B556-00C04F68D4DB")] internal interface ICSInputSet { ICSCompiler GetCompiler(); void AddSourceFile([MarshalAs(UnmanagedType.LPWStr)] string filename); void RemoveSourceFile([MarshalAs(UnmanagedType.LPWStr)] string filename); void RemoveAllSourceFiles(); void AddResourceFile([MarshalAs(UnmanagedType.LPWStr)] string filename, [MarshalAs(UnmanagedType.LPWStr)] string ident, bool embed, bool vis); void RemoveResourceFile([MarshalAs(UnmanagedType.LPWStr)] string filename, [MarshalAs(UnmanagedType.LPWStr)] string ident, bool embed, bool vis); void SetWin32Resource([MarshalAs(UnmanagedType.LPWStr)] string filename); void SetOutputFileName([MarshalAs(UnmanagedType.LPWStr)] string filename); void SetOutputFileType(OutputFileType fileType); void SetImageBase(uint imageBase); void SetMainClass([MarshalAs(UnmanagedType.LPWStr)] string fullyQualifiedClassName); void SetWin32Icon([MarshalAs(UnmanagedType.LPWStr)] string iconFileName); void SetFileAlignment(uint align); void SetImageBase2(ulong imageBase); void SetPdbFileName([MarshalAs(UnmanagedType.LPWStr)] string filename); string GetWin32Resource(); void SetWin32Manifest([MarshalAs(UnmanagedType.LPWStr)] string manifestFileName); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop { [ComImport] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [Guid("4D5D4C22-EE19-11d2-B556-00C04F68D4DB")] internal interface ICSInputSet { ICSCompiler GetCompiler(); void AddSourceFile([MarshalAs(UnmanagedType.LPWStr)] string filename); void RemoveSourceFile([MarshalAs(UnmanagedType.LPWStr)] string filename); void RemoveAllSourceFiles(); void AddResourceFile([MarshalAs(UnmanagedType.LPWStr)] string filename, [MarshalAs(UnmanagedType.LPWStr)] string ident, bool embed, bool vis); void RemoveResourceFile([MarshalAs(UnmanagedType.LPWStr)] string filename, [MarshalAs(UnmanagedType.LPWStr)] string ident, bool embed, bool vis); void SetWin32Resource([MarshalAs(UnmanagedType.LPWStr)] string filename); void SetOutputFileName([MarshalAs(UnmanagedType.LPWStr)] string filename); void SetOutputFileType(OutputFileType fileType); void SetImageBase(uint imageBase); void SetMainClass([MarshalAs(UnmanagedType.LPWStr)] string fullyQualifiedClassName); void SetWin32Icon([MarshalAs(UnmanagedType.LPWStr)] string iconFileName); void SetFileAlignment(uint align); void SetImageBase2(ulong imageBase); void SetPdbFileName([MarshalAs(UnmanagedType.LPWStr)] string filename); string GetWin32Resource(); void SetWin32Manifest([MarshalAs(UnmanagedType.LPWStr)] string manifestFileName); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.ja.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="ja" original="../VisualBasicAnalyzersResources.resx"> <body> <trans-unit id="GetType_can_be_converted_to_NameOf"> <source>'GetType' can be converted to 'NameOf'</source> <target state="translated">'GetType' を 'NameOf' に変換できます</target> <note /> </trans-unit> <trans-unit id="If_statement_can_be_simplified"> <source>'If' statement can be simplified</source> <target state="translated">'if' ステートメントは簡素化できます</target> <note /> </trans-unit> <trans-unit id="Imports_statement_is_unnecessary"> <source>Imports statement is unnecessary.</source> <target state="translated">Imports ステートメントは不要です。</target> <note /> </trans-unit> <trans-unit id="Object_creation_can_be_simplified"> <source>Object creation can be simplified</source> <target state="translated">オブジェクト作成を簡素化できます</target> <note /> </trans-unit> <trans-unit id="Remove_ByVal"> <source>'ByVal' keyword is unnecessary and can be removed.</source> <target state="translated">'ByVal' キーワードは必要ありません。削除することができます。</target> <note>{locked: ByVal}This is a Visual Basic keyword and should not be localized or have its casing changed</note> </trans-unit> <trans-unit id="Use_IsNot_Nothing_check"> <source>Use 'IsNot Nothing' check</source> <target state="translated">IsNot Nothing' チェックを使用します</target> <note /> </trans-unit> <trans-unit id="Use_IsNot_expression"> <source>Use 'IsNot' expression</source> <target state="translated">'IsNot' 式を使用する</target> <note>{locked: IsNot}This is a Visual Basic keyword and should not be localized or have its casing changed</note> </trans-unit> <trans-unit id="Use_Is_Nothing_check"> <source>Use 'Is Nothing' check</source> <target state="translated">Is Nothing' チェックを使用します</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="ja" original="../VisualBasicAnalyzersResources.resx"> <body> <trans-unit id="GetType_can_be_converted_to_NameOf"> <source>'GetType' can be converted to 'NameOf'</source> <target state="translated">'GetType' を 'NameOf' に変換できます</target> <note /> </trans-unit> <trans-unit id="If_statement_can_be_simplified"> <source>'If' statement can be simplified</source> <target state="translated">'if' ステートメントは簡素化できます</target> <note /> </trans-unit> <trans-unit id="Imports_statement_is_unnecessary"> <source>Imports statement is unnecessary.</source> <target state="translated">Imports ステートメントは不要です。</target> <note /> </trans-unit> <trans-unit id="Object_creation_can_be_simplified"> <source>Object creation can be simplified</source> <target state="translated">オブジェクト作成を簡素化できます</target> <note /> </trans-unit> <trans-unit id="Remove_ByVal"> <source>'ByVal' keyword is unnecessary and can be removed.</source> <target state="translated">'ByVal' キーワードは必要ありません。削除することができます。</target> <note>{locked: ByVal}This is a Visual Basic keyword and should not be localized or have its casing changed</note> </trans-unit> <trans-unit id="Use_IsNot_Nothing_check"> <source>Use 'IsNot Nothing' check</source> <target state="translated">IsNot Nothing' チェックを使用します</target> <note /> </trans-unit> <trans-unit id="Use_IsNot_expression"> <source>Use 'IsNot' expression</source> <target state="translated">'IsNot' 式を使用する</target> <note>{locked: IsNot}This is a Visual Basic keyword and should not be localized or have its casing changed</note> </trans-unit> <trans-unit id="Use_Is_Nothing_check"> <source>Use 'Is Nothing' check</source> <target state="translated">Is Nothing' チェックを使用します</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/InternalUtilities/VoidResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Roslyn.Utilities { /// <summary> /// Explicitly indicates result is void /// </summary> internal readonly struct VoidResult : IEquatable<VoidResult> { public override bool Equals(object? obj) => obj is VoidResult; public override int GetHashCode() => 0; public bool Equals(VoidResult other) => true; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Roslyn.Utilities { /// <summary> /// Explicitly indicates result is void /// </summary> internal readonly struct VoidResult : IEquatable<VoidResult> { public override bool Equals(object? obj) => obj is VoidResult; public override int GetHashCode() => 0; public bool Equals(VoidResult other) => true; } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/DiagnosticAnalyzer/CompilationStartedEvent.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// The first event placed into a compilation's event queue. /// </summary> internal sealed class CompilationStartedEvent : CompilationEvent { public ImmutableArray<AdditionalText> AdditionalFiles { get; } private CompilationStartedEvent(Compilation compilation, ImmutableArray<AdditionalText> additionalFiles) : base(compilation) { AdditionalFiles = additionalFiles; } public CompilationStartedEvent(Compilation compilation) : this(compilation, ImmutableArray<AdditionalText>.Empty) { } public override string ToString() { return "CompilationStartedEvent"; } public CompilationStartedEvent WithAdditionalFiles(ImmutableArray<AdditionalText> additionalFiles) => new CompilationStartedEvent(Compilation, additionalFiles); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// The first event placed into a compilation's event queue. /// </summary> internal sealed class CompilationStartedEvent : CompilationEvent { public ImmutableArray<AdditionalText> AdditionalFiles { get; } private CompilationStartedEvent(Compilation compilation, ImmutableArray<AdditionalText> additionalFiles) : base(compilation) { AdditionalFiles = additionalFiles; } public CompilationStartedEvent(Compilation compilation) : this(compilation, ImmutableArray<AdditionalText>.Empty) { } public override string ToString() { return "CompilationStartedEvent"; } public CompilationStartedEvent WithAdditionalFiles(ImmutableArray<AdditionalText> additionalFiles) => new CompilationStartedEvent(Compilation, additionalFiles); } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/EditorFeatures/TestUtilities/MoveStaticMembers/TestMoveStaticMembersService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MoveStaticMembers; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Test.Utilities.MoveStaticMembers { [ExportWorkspaceService(typeof(IMoveStaticMembersOptionsService))] [Shared] [PartNotDiscoverable] internal class TestMoveStaticMembersService : IMoveStaticMembersOptionsService { [ImportingConstructor] [System.Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestMoveStaticMembersService() { } public string? DestinationName { get; set; } public ImmutableArray<string> SelectedMembers { get; set; } public ImmutableArray<string> ExpectedPrecheckedMembers { get; set; } public string? Filename { get; set; } public bool CreateNew { get; set; } = true; public MoveStaticMembersOptions GetMoveMembersToTypeOptions(Document document, INamedTypeSymbol selectedType, ImmutableArray<ISymbol> selectedNodeSymbols) { if (!ExpectedPrecheckedMembers.IsEmpty) { // if we expect to have prechecked members and don't have the correct ones, error var actualPrecheckedMembers = selectedNodeSymbols.SelectAsArray(n => n.Name).Sort(); if (!ExpectedPrecheckedMembers.Sort().SequenceEqual(actualPrecheckedMembers)) { System.Diagnostics.Debug.Fail("Expected Prechecked members did not match recieved members"); var errMsg = string.Format("Expected: {0} \n Actual: {1}", ExpectedPrecheckedMembers, actualPrecheckedMembers); System.Diagnostics.Debug.Fail(errMsg); throw new InvalidOperationException(errMsg); } } var selectedMembers = selectedType.GetMembers().WhereAsArray(symbol => SelectedMembers.Contains(symbol.Name)); if (CreateNew) { var namespaceDisplay = selectedType.ContainingNamespace.IsGlobalNamespace ? string.Empty : selectedType.ContainingNamespace.ToDisplayString(); // just return all the selected members return new MoveStaticMembersOptions( Filename!, string.Join(".", namespaceDisplay, DestinationName!), selectedMembers); } var destination = selectedType.ContainingNamespace.GetAllTypes(CancellationToken.None).First(t => t.ToDisplayString() == DestinationName); return new MoveStaticMembersOptions(destination, selectedMembers); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MoveStaticMembers; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Test.Utilities.MoveStaticMembers { [ExportWorkspaceService(typeof(IMoveStaticMembersOptionsService))] [Shared] [PartNotDiscoverable] internal class TestMoveStaticMembersService : IMoveStaticMembersOptionsService { [ImportingConstructor] [System.Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestMoveStaticMembersService() { } public string? DestinationName { get; set; } public ImmutableArray<string> SelectedMembers { get; set; } public ImmutableArray<string> ExpectedPrecheckedMembers { get; set; } public string? Filename { get; set; } public bool CreateNew { get; set; } = true; public MoveStaticMembersOptions GetMoveMembersToTypeOptions(Document document, INamedTypeSymbol selectedType, ImmutableArray<ISymbol> selectedNodeSymbols) { if (!ExpectedPrecheckedMembers.IsEmpty) { // if we expect to have prechecked members and don't have the correct ones, error var actualPrecheckedMembers = selectedNodeSymbols.SelectAsArray(n => n.Name).Sort(); if (!ExpectedPrecheckedMembers.Sort().SequenceEqual(actualPrecheckedMembers)) { System.Diagnostics.Debug.Fail("Expected Prechecked members did not match recieved members"); var errMsg = string.Format("Expected: {0} \n Actual: {1}", ExpectedPrecheckedMembers, actualPrecheckedMembers); System.Diagnostics.Debug.Fail(errMsg); throw new InvalidOperationException(errMsg); } } var selectedMembers = selectedType.GetMembers().WhereAsArray(symbol => SelectedMembers.Contains(symbol.Name)); if (CreateNew) { var namespaceDisplay = selectedType.ContainingNamespace.IsGlobalNamespace ? string.Empty : selectedType.ContainingNamespace.ToDisplayString(); // just return all the selected members return new MoveStaticMembersOptions( Filename!, string.Join(".", namespaceDisplay, DestinationName!), selectedMembers); } var destination = selectedType.ContainingNamespace.GetAllTypes(CancellationToken.None).First(t => t.ToDisplayString() == DestinationName); return new MoveStaticMembersOptions(destination, selectedMembers); } } }
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/VisualStudio/Core/Test/Venus/CSharpContainedLanguageSupportTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.CSharp.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus Imports Microsoft.VisualStudio.TextManager.Interop Imports Roslyn.Test.Utilities Imports Roslyn.Utilities Imports TextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus Public Class CSharpContainedLanguageCodeSupportTests Inherits AbstractContainedLanguageCodeSupportTests #Region "IsValidId Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_1() AssertValidId("field") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_Escaped() AssertValidId("@field") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_EscapedKeyword() AssertValidId("@class") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_ContainsNumbers() AssertValidId("abc123") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_Keyword() AssertNotValidId("class") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_StartsWithNumber() AssertNotValidId("123abc") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_Punctuation() AssertNotValidId("abc.abc") End Sub ' TODO: Does Dev10 cover more here, like conflicts with existing members? #End Region #Region "GetBaseClassName Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_NonexistingClass() Dim code As String = "class C { }" Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.False(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "A", CancellationToken.None, baseClassName)) Assert.Null(baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_DerivedFromObject() Dim code As String = "class C { }" Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C", CancellationToken.None, baseClassName)) Assert.Equal("object", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_DerivedFromFrameworkType() Dim code As String = "class C : Exception { }" Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C", CancellationToken.None, baseClassName)) Assert.Equal("Exception", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_DerivedFromUserDefinedType() Dim code As String = "class B { } class C : B { }" Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C", CancellationToken.None, baseClassName)) Assert.Equal("B", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_FullyQualifiedNames() Dim code As String = "namespace N { class B { } class C : B { } }" Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "N.C", CancellationToken.None, baseClassName)) Assert.Equal("N.B", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_MinimallyQualifiedNames() Dim code As String = "namespace N { class B { } class C : B { } }" Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "N.C", CancellationToken.None, baseClassName)) Assert.Equal("N.B", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_EscapedKeyword() Dim code As String = "class @class { } class Derived : @class { }" Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "Derived", CancellationToken.None, baseClassName)) Assert.Equal("@class", baseClassName) End Using End Sub #End Region #Region "CreateUniqueEventName Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_ButtonClick() Dim code As String = <text> public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, workspace.GlobalOptions, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click", eventName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_NameCollisionWithEventHandler() Dim code As String = <text> public class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, workspace.GlobalOptions, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click1", eventName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_NameCollisionWithOtherMembers() Dim code As String = <text> public class _Default : System.Web.UI.Page { public int Button1_Click { get; set; } protected void Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, workspace.GlobalOptions, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click1", eventName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_NameCollisionFromPartialClass() Dim code As String = <text> public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } public partial class _Default { public int Button1_Click { get; set; } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, workspace.GlobalOptions, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click1", eventName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_NameCollisionFromBaseClass() Dim code As String = <text> public class _Default : MyBaseClass { protected void Page_Load(object sender, EventArgs e) { } } public class MyBaseClass { protected void Button1_Click(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, workspace.GlobalOptions, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click1", eventName) End Using End Sub #End Region #Region "GetCompatibleEventHandlers" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetCompatibleEventHandlers_EventDoesntExist() Dim code As String = <text> using System; public class Button { } public class _Default { Button button; protected void Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Assert.Throws(Of InvalidOperationException)( Sub() ContainedLanguageCodeSupport.GetCompatibleEventHandlers( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", cancellationToken:=Nothing) End Sub) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetCompatibleEventHandlers_ObjTypeNameIsWrong() Dim code As String = <text> using System; namespace Test { public class Button { public event EventHandler Click; } public class _Default { Button button; protected void Page_Load(object sender, EventArgs e) { } } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Assert.Throws(Of InvalidOperationException)( Sub() ContainedLanguageCodeSupport.GetCompatibleEventHandlers( document:=document, className:="_Default", objectTypeName:="Form", nameOfEvent:="Click", cancellationToken:=Nothing) End Sub) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetCompatibleEventHandlers_MatchExists() Dim code As String = <text> using System; public class Button { public event EventHandler Click; } public class _Default { Button button; protected void Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlers = ContainedLanguageCodeSupport.GetCompatibleEventHandlers( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal(1, eventHandlers.Count()) Assert.Equal("Page_Load", eventHandlers.Single().Item1) Assert.Equal("Page_Load(object,System.EventArgs)", eventHandlers.Single().Item2) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetCompatibleEventHandlers_MatchesExist() Dim code As String = <text> using System; public class Button { public event EventHandler Click; } public class _Default { Button button; protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlers = ContainedLanguageCodeSupport.GetCompatibleEventHandlers( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal(2, eventHandlers.Count()) ' It has to be page_load and button click, but are they always ordered in the same way? End Using End Sub ' add tests for CompatibleSignatureToDelegate (#params, return type) #End Region #Region "GetEventHandlerMemberId" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetEventHandlerMemberId_HandlerExists() Dim code As String = <text> using System; public class Button { public event EventHandler Click; } public class _Default { Button button; protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerId = ContainedLanguageCodeSupport.GetEventHandlerMemberId( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", eventHandlerName:="Button1_Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click(object,System.EventArgs)", eventHandlerId) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetEventHandlerMemberId_CantFindHandler() Dim code As String = <text> using System; public class Button { public event EventHandler Click; } public class _Default { Button button; }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerId = ContainedLanguageCodeSupport.GetEventHandlerMemberId( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", eventHandlerName:="Button1_Click", cancellationToken:=Nothing) Assert.Equal(Nothing, eventHandlerId) End Using End Sub #End Region #Region "EnsureEventHandler" ' TODO: log a bug, Kevin doesn't use uint itemidInsertionPoint thats sent in. <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestEnsureEventHandler_HandlerExists() Dim code As String = <text> using System; public class Button { public event EventHandler Click; } public class _Default { Button button; protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerIdTextPosition = ContainedLanguageCodeSupport.EnsureEventHandler( thisDocument:=document, targetDocument:=document, className:="_Default", objectName:="", objectTypeName:="Button", nameOfEvent:="Click", eventHandlerName:="Button1_Click", itemidInsertionPoint:=0, useHandlesClause:=False, additionalFormattingRule:=BlankLineInGeneratedMethodFormattingRule.Instance, workspace.GlobalOptions, cancellationToken:=Nothing) ' Since a valid handler exists, item2 and item3 of the tuple returned must be nothing Assert.Equal("Button1_Click(object,System.EventArgs)", eventHandlerIdTextPosition.Item1) Assert.Equal(Nothing, eventHandlerIdTextPosition.Item2) Assert.Equal(New TextSpan(), eventHandlerIdTextPosition.Item3) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestEnsureEventHandler_GenerateNewHandler() Dim code As String = <text> using System; public class Button { public event EventHandler Click; } public class _Default { Button button; protected void Page_Load(object sender, EventArgs e) { } }</text>.NormalizedValue Dim generatedCode As String = <text> protected void Button1_Click(object sender, EventArgs e) { } </text>.NormalizedValue Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerIdTextPosition = ContainedLanguageCodeSupport.EnsureEventHandler( thisDocument:=document, targetDocument:=document, className:="_Default", objectName:="", objectTypeName:="Button", nameOfEvent:="Click", eventHandlerName:="Button1_Click", itemidInsertionPoint:=0, useHandlesClause:=False, additionalFormattingRule:=BlankLineInGeneratedMethodFormattingRule.Instance, workspace.GlobalOptions, cancellationToken:=Nothing) Assert.Equal("Button1_Click(object,System.EventArgs)", eventHandlerIdTextPosition.Item1) TokenUtilities.AssertTokensEqual(generatedCode, eventHandlerIdTextPosition.Item2, Language) Assert.Equal(New TextSpan With {.iStartLine = 15, .iEndLine = 15}, eventHandlerIdTextPosition.Item3) End Using End Sub #End Region #Region "GetMemberNavigationPoint" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMemberNavigationPoint() Dim code As String = <text> using System; public class Button { public event EventHandler Click; } public class _Default { Button button; protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { } }</text>.Value ' Expect the cursor to be inside the method body of Button1_Click, line 18 column 8 Dim expectedSpan As New Microsoft.VisualStudio.TextManager.Interop.TextSpan() With { .iStartLine = 18, .iStartIndex = 8, .iEndLine = 18, .iEndIndex = 8 } Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim targetDocument As Document = Nothing Dim actualSpan As TextSpan = Nothing If Not ContainedLanguageCodeSupport.TryGetMemberNavigationPoint( thisDocument:=document, workspace.GlobalOptions, className:="_Default", uniqueMemberID:="Button1_Click(object,System.EventArgs)", textSpan:=actualSpan, targetDocument:=targetDocument, cancellationToken:=Nothing) Then Assert.True(False, "Should have succeeded") End If Assert.Equal(expectedSpan, actualSpan) End Using End Sub #End Region #Region "GetMembers" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_EventHandlersWrongParamType() Dim code As String = <text> using System; public partial class _Default { protected void Page_Load(object sender, object e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS, cancellationToken:=Nothing) Assert.Equal(0, members.Count()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_EventHandlersWrongParamCount() Dim code As String = <text> using System; public partial class _Default { protected void Page_Load(object sender) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS, cancellationToken:=Nothing) Assert.Equal(0, members.Count()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_EventHandlersWrongReturnType() Dim code As String = <text> using System; public partial class _Default { protected int Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS, cancellationToken:=Nothing) Assert.Equal(0, members.Count()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_EventHandlers() Dim code As String = <text> using System; public partial class _Default { int a; protected void Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS, cancellationToken:=Nothing) Assert.Equal(1, members.Count()) Dim userFunction = members.First() Assert.Equal("Page_Load", userFunction.Item1) Assert.Equal("Page_Load(object,System.EventArgs)", userFunction.Item2) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_UserFunctions() Dim code As String = <text> using System; public partial class _Default { protected void Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_USER_FUNCTIONS, cancellationToken:=Nothing) Assert.Equal(1, members.Count()) Dim userFunction = members.First() Assert.Equal("Page_Load", userFunction.Item1) Assert.Equal("Page_Load(object,System.EventArgs)", userFunction.Item2) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_Events() Dim code As String = <text> using System; public class Button { public event EventHandler Click; }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="Button", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS, cancellationToken:=Nothing) Assert.Equal(1, members.Count()) Dim userFunction = members.First() Assert.Equal("Click", userFunction.Item1) Assert.Equal("Click(EVENT)", userFunction.Item2) End Using End Sub #End Region #Region "OnRenamed (TryRenameElement)" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_ResolvableMembers() Dim code As String = <text> using System; public partial class _Default { protected void Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER, oldFullyQualifiedName:="_Default.Page_Load", newFullyQualifiedName:="_Default.Page_Load1", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.True(renameSucceeded) End Using End Sub ' TODO: Who tests the fully qualified names and their absence? <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_UnresolvableMembers() Dim code As String = <text> using System; public partial class _Default { protected void Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER, oldFullyQualifiedName:="_Default.Fictional", newFullyQualifiedName:="_Default.Fictional1", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.False(renameSucceeded) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_ResolvableClass() Dim code As String = <text>public partial class Goo { }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_CLASS, oldFullyQualifiedName:="Goo", newFullyQualifiedName:="Bar", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.True(renameSucceeded) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_ResolvableNamespace() Dim code As String = <text>namespace Goo { }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_NAMESPACE, oldFullyQualifiedName:="Goo", newFullyQualifiedName:="Bar", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.True(renameSucceeded) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_Button() Dim code As String = <text> using System; public class Button { public event EventHandler Click; } public class _Default { Button button; protected void Button_Click(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER, oldFullyQualifiedName:="_Default.button", newFullyQualifiedName:="_Default.button1", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.True(renameSucceeded) End Using End Sub #End Region Protected Overrides ReadOnly Property Language As String Get Return "C#" End Get End Property Protected Overrides ReadOnly Property DefaultCode As String Get Return "class C { }" End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.CSharp.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus Imports Microsoft.VisualStudio.TextManager.Interop Imports Roslyn.Test.Utilities Imports Roslyn.Utilities Imports TextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus Public Class CSharpContainedLanguageCodeSupportTests Inherits AbstractContainedLanguageCodeSupportTests #Region "IsValidId Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_1() AssertValidId("field") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_Escaped() AssertValidId("@field") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_EscapedKeyword() AssertValidId("@class") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_ContainsNumbers() AssertValidId("abc123") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_Keyword() AssertNotValidId("class") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_StartsWithNumber() AssertNotValidId("123abc") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestIsValidId_Punctuation() AssertNotValidId("abc.abc") End Sub ' TODO: Does Dev10 cover more here, like conflicts with existing members? #End Region #Region "GetBaseClassName Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_NonexistingClass() Dim code As String = "class C { }" Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.False(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "A", CancellationToken.None, baseClassName)) Assert.Null(baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_DerivedFromObject() Dim code As String = "class C { }" Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C", CancellationToken.None, baseClassName)) Assert.Equal("object", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_DerivedFromFrameworkType() Dim code As String = "class C : Exception { }" Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C", CancellationToken.None, baseClassName)) Assert.Equal("Exception", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_DerivedFromUserDefinedType() Dim code As String = "class B { } class C : B { }" Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C", CancellationToken.None, baseClassName)) Assert.Equal("B", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_FullyQualifiedNames() Dim code As String = "namespace N { class B { } class C : B { } }" Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "N.C", CancellationToken.None, baseClassName)) Assert.Equal("N.B", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_MinimallyQualifiedNames() Dim code As String = "namespace N { class B { } class C : B { } }" Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "N.C", CancellationToken.None, baseClassName)) Assert.Equal("N.B", baseClassName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetBaseClassName_EscapedKeyword() Dim code As String = "class @class { } class Derived : @class { }" Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim baseClassName As String = Nothing Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "Derived", CancellationToken.None, baseClassName)) Assert.Equal("@class", baseClassName) End Using End Sub #End Region #Region "CreateUniqueEventName Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_ButtonClick() Dim code As String = <text> public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, workspace.GlobalOptions, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click", eventName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_NameCollisionWithEventHandler() Dim code As String = <text> public class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, workspace.GlobalOptions, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click1", eventName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_NameCollisionWithOtherMembers() Dim code As String = <text> public class _Default : System.Web.UI.Page { public int Button1_Click { get; set; } protected void Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, workspace.GlobalOptions, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click1", eventName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_NameCollisionFromPartialClass() Dim code As String = <text> public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } public partial class _Default { public int Button1_Click { get; set; } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, workspace.GlobalOptions, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click1", eventName) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestCreateUniqueEventName_NameCollisionFromBaseClass() Dim code As String = <text> public class _Default : MyBaseClass { protected void Page_Load(object sender, EventArgs e) { } } public class MyBaseClass { protected void Button1_Click(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName( document:=document, workspace.GlobalOptions, className:="_Default", objectName:="Button1", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click1", eventName) End Using End Sub #End Region #Region "GetCompatibleEventHandlers" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetCompatibleEventHandlers_EventDoesntExist() Dim code As String = <text> using System; public class Button { } public class _Default { Button button; protected void Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Assert.Throws(Of InvalidOperationException)( Sub() ContainedLanguageCodeSupport.GetCompatibleEventHandlers( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", cancellationToken:=Nothing) End Sub) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetCompatibleEventHandlers_ObjTypeNameIsWrong() Dim code As String = <text> using System; namespace Test { public class Button { public event EventHandler Click; } public class _Default { Button button; protected void Page_Load(object sender, EventArgs e) { } } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Assert.Throws(Of InvalidOperationException)( Sub() ContainedLanguageCodeSupport.GetCompatibleEventHandlers( document:=document, className:="_Default", objectTypeName:="Form", nameOfEvent:="Click", cancellationToken:=Nothing) End Sub) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetCompatibleEventHandlers_MatchExists() Dim code As String = <text> using System; public class Button { public event EventHandler Click; } public class _Default { Button button; protected void Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlers = ContainedLanguageCodeSupport.GetCompatibleEventHandlers( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal(1, eventHandlers.Count()) Assert.Equal("Page_Load", eventHandlers.Single().Item1) Assert.Equal("Page_Load(object,System.EventArgs)", eventHandlers.Single().Item2) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetCompatibleEventHandlers_MatchesExist() Dim code As String = <text> using System; public class Button { public event EventHandler Click; } public class _Default { Button button; protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlers = ContainedLanguageCodeSupport.GetCompatibleEventHandlers( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", cancellationToken:=Nothing) Assert.Equal(2, eventHandlers.Count()) ' It has to be page_load and button click, but are they always ordered in the same way? End Using End Sub ' add tests for CompatibleSignatureToDelegate (#params, return type) #End Region #Region "GetEventHandlerMemberId" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetEventHandlerMemberId_HandlerExists() Dim code As String = <text> using System; public class Button { public event EventHandler Click; } public class _Default { Button button; protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerId = ContainedLanguageCodeSupport.GetEventHandlerMemberId( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", eventHandlerName:="Button1_Click", cancellationToken:=Nothing) Assert.Equal("Button1_Click(object,System.EventArgs)", eventHandlerId) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetEventHandlerMemberId_CantFindHandler() Dim code As String = <text> using System; public class Button { public event EventHandler Click; } public class _Default { Button button; }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerId = ContainedLanguageCodeSupport.GetEventHandlerMemberId( document:=document, className:="_Default", objectTypeName:="Button", nameOfEvent:="Click", eventHandlerName:="Button1_Click", cancellationToken:=Nothing) Assert.Equal(Nothing, eventHandlerId) End Using End Sub #End Region #Region "EnsureEventHandler" ' TODO: log a bug, Kevin doesn't use uint itemidInsertionPoint thats sent in. <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestEnsureEventHandler_HandlerExists() Dim code As String = <text> using System; public class Button { public event EventHandler Click; } public class _Default { Button button; protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerIdTextPosition = ContainedLanguageCodeSupport.EnsureEventHandler( thisDocument:=document, targetDocument:=document, className:="_Default", objectName:="", objectTypeName:="Button", nameOfEvent:="Click", eventHandlerName:="Button1_Click", itemidInsertionPoint:=0, useHandlesClause:=False, additionalFormattingRule:=BlankLineInGeneratedMethodFormattingRule.Instance, workspace.GlobalOptions, cancellationToken:=Nothing) ' Since a valid handler exists, item2 and item3 of the tuple returned must be nothing Assert.Equal("Button1_Click(object,System.EventArgs)", eventHandlerIdTextPosition.Item1) Assert.Equal(Nothing, eventHandlerIdTextPosition.Item2) Assert.Equal(New TextSpan(), eventHandlerIdTextPosition.Item3) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestEnsureEventHandler_GenerateNewHandler() Dim code As String = <text> using System; public class Button { public event EventHandler Click; } public class _Default { Button button; protected void Page_Load(object sender, EventArgs e) { } }</text>.NormalizedValue Dim generatedCode As String = <text> protected void Button1_Click(object sender, EventArgs e) { } </text>.NormalizedValue Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim eventHandlerIdTextPosition = ContainedLanguageCodeSupport.EnsureEventHandler( thisDocument:=document, targetDocument:=document, className:="_Default", objectName:="", objectTypeName:="Button", nameOfEvent:="Click", eventHandlerName:="Button1_Click", itemidInsertionPoint:=0, useHandlesClause:=False, additionalFormattingRule:=BlankLineInGeneratedMethodFormattingRule.Instance, workspace.GlobalOptions, cancellationToken:=Nothing) Assert.Equal("Button1_Click(object,System.EventArgs)", eventHandlerIdTextPosition.Item1) TokenUtilities.AssertTokensEqual(generatedCode, eventHandlerIdTextPosition.Item2, Language) Assert.Equal(New TextSpan With {.iStartLine = 15, .iEndLine = 15}, eventHandlerIdTextPosition.Item3) End Using End Sub #End Region #Region "GetMemberNavigationPoint" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMemberNavigationPoint() Dim code As String = <text> using System; public class Button { public event EventHandler Click; } public class _Default { Button button; protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { } }</text>.Value ' Expect the cursor to be inside the method body of Button1_Click, line 18 column 8 Dim expectedSpan As New Microsoft.VisualStudio.TextManager.Interop.TextSpan() With { .iStartLine = 18, .iStartIndex = 8, .iEndLine = 18, .iEndIndex = 8 } Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim targetDocument As Document = Nothing Dim actualSpan As TextSpan = Nothing If Not ContainedLanguageCodeSupport.TryGetMemberNavigationPoint( thisDocument:=document, workspace.GlobalOptions, className:="_Default", uniqueMemberID:="Button1_Click(object,System.EventArgs)", textSpan:=actualSpan, targetDocument:=targetDocument, cancellationToken:=Nothing) Then Assert.True(False, "Should have succeeded") End If Assert.Equal(expectedSpan, actualSpan) End Using End Sub #End Region #Region "GetMembers" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_EventHandlersWrongParamType() Dim code As String = <text> using System; public partial class _Default { protected void Page_Load(object sender, object e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS, cancellationToken:=Nothing) Assert.Equal(0, members.Count()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_EventHandlersWrongParamCount() Dim code As String = <text> using System; public partial class _Default { protected void Page_Load(object sender) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS, cancellationToken:=Nothing) Assert.Equal(0, members.Count()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_EventHandlersWrongReturnType() Dim code As String = <text> using System; public partial class _Default { protected int Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS, cancellationToken:=Nothing) Assert.Equal(0, members.Count()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_EventHandlers() Dim code As String = <text> using System; public partial class _Default { int a; protected void Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS, cancellationToken:=Nothing) Assert.Equal(1, members.Count()) Dim userFunction = members.First() Assert.Equal("Page_Load", userFunction.Item1) Assert.Equal("Page_Load(object,System.EventArgs)", userFunction.Item2) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_UserFunctions() Dim code As String = <text> using System; public partial class _Default { protected void Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="_Default", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_USER_FUNCTIONS, cancellationToken:=Nothing) Assert.Equal(1, members.Count()) Dim userFunction = members.First() Assert.Equal("Page_Load", userFunction.Item1) Assert.Equal("Page_Load(object,System.EventArgs)", userFunction.Item2) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestGetMembers_Events() Dim code As String = <text> using System; public class Button { public event EventHandler Click; }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim members = ContainedLanguageCodeSupport.GetMembers( document:=document, className:="Button", codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS, cancellationToken:=Nothing) Assert.Equal(1, members.Count()) Dim userFunction = members.First() Assert.Equal("Click", userFunction.Item1) Assert.Equal("Click(EVENT)", userFunction.Item2) End Using End Sub #End Region #Region "OnRenamed (TryRenameElement)" <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_ResolvableMembers() Dim code As String = <text> using System; public partial class _Default { protected void Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER, oldFullyQualifiedName:="_Default.Page_Load", newFullyQualifiedName:="_Default.Page_Load1", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.True(renameSucceeded) End Using End Sub ' TODO: Who tests the fully qualified names and their absence? <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_UnresolvableMembers() Dim code As String = <text> using System; public partial class _Default { protected void Page_Load(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER, oldFullyQualifiedName:="_Default.Fictional", newFullyQualifiedName:="_Default.Fictional1", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.False(renameSucceeded) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_ResolvableClass() Dim code As String = <text>public partial class Goo { }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_CLASS, oldFullyQualifiedName:="Goo", newFullyQualifiedName:="Bar", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.True(renameSucceeded) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_ResolvableNamespace() Dim code As String = <text>namespace Goo { }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_NAMESPACE, oldFullyQualifiedName:="Goo", newFullyQualifiedName:="Bar", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.True(renameSucceeded) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub TestTryRenameElement_Button() Dim code As String = <text> using System; public class Button { public event EventHandler Click; } public class _Default { Button button; protected void Button_Click(object sender, EventArgs e) { } }</text>.Value Using workspace = GetWorkspace(code) Dim document = GetDocument(workspace) Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement( document:=document, clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER, oldFullyQualifiedName:="_Default.button", newFullyQualifiedName:="_Default.button1", refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService), cancellationToken:=Nothing) Assert.True(renameSucceeded) End Using End Sub #End Region Protected Overrides ReadOnly Property Language As String Get Return "C#" End Get End Property Protected Overrides ReadOnly Property DefaultCode As String Get Return "class C { }" End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Test/Resources/Core/SymbolsTests/RefAssembly/MVID1.dll
MZ@ !L!This program cannot be run in DOS mode. $PEL 4" 0jC@  @CO` B@@H.mvid @B.textp@ `.reloc `@BQn^G <M7LCHT@ zBSJB v4.0.30319l#~X#StringsD#USH#GUIDXP#BlobG 31lQ P@  ). .".A.#J <Module>CMVIDnetstandardDebuggableAttributeCompilationRelaxationsAttributeReferenceAssemblyAttributeRuntimeCompatibilityAttributeMVID.dllSystem.ctorSystem.DiagnosticsSystem.Runtime.CompilerServicesDebuggingModesObjectQn^G <M7   {-QTWrapNonExceptionThrows@CZC@LC_CorDllMainmscoree.dll%@@ l3
MZ@ !L!This program cannot be run in DOS mode. $PEL 4" 0jC@  @CO` B@@H.mvid @B.textp@ `.reloc `@BQn^G <M7LCHT@ zBSJB v4.0.30319l#~X#StringsD#USH#GUIDXP#BlobG 31lQ P@  ). .".A.#J <Module>CMVIDnetstandardDebuggableAttributeCompilationRelaxationsAttributeReferenceAssemblyAttributeRuntimeCompatibilityAttributeMVID.dllSystem.ctorSystem.DiagnosticsSystem.Runtime.CompilerServicesDebuggingModesObjectQn^G <M7   {-QTWrapNonExceptionThrows@CZC@LC_CorDllMainmscoree.dll%@@ l3
-1
dotnet/roslyn
55,971
Theme some dialogs
Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
ryzngard
"2021-08-27T20:10:35Z"
"2022-07-12T20:08:34Z"
07297d927b3ffd4d44f048602950947e9a040dd2
2cd995df98f17f1ceebba0d93729d8a4336ebe26
Theme some dialogs. Theme pull members up, extract interface, and extract class. ### Extract Class ![image](https://user-images.githubusercontent.com/475144/147613347-811ba1a0-6935-4a7b-93d6-ab7954e61025.png) ![image](https://user-images.githubusercontent.com/475144/147613405-ce989054-e738-4661-b748-bda1c8776c4e.png) ### Extract Interface ![image](https://user-images.githubusercontent.com/475144/147613329-fa94cf08-eb40-4c3a-9d32-074fc72c070c.png) ![image](https://user-images.githubusercontent.com/475144/147613397-f150226d-cc5e-422f-b83f-11288fa1699a.png) ### Pull Members Up ![image](https://user-images.githubusercontent.com/475144/147613371-7962f7cf-ab8c-4b41-a89d-7943178446c1.png) ![image](https://user-images.githubusercontent.com/475144/147613417-2f47bcf0-e4bc-4a4f-9218-15989972091d.png)
./src/Compilers/Core/Portable/ReferenceManager/AssemblyDataForAssemblyBeingBuilt.cs
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class CommonReferenceManager<TCompilation, TAssemblySymbol> { protected sealed class AssemblyDataForAssemblyBeingBuilt : AssemblyData { private readonly AssemblyIdentity _assemblyIdentity; // assemblies referenced directly by the assembly: private readonly ImmutableArray<AssemblyData> _referencedAssemblyData; // all referenced assembly names including assemblies referenced by modules: private readonly ImmutableArray<AssemblyIdentity> _referencedAssemblies; public AssemblyDataForAssemblyBeingBuilt( AssemblyIdentity identity, ImmutableArray<AssemblyData> referencedAssemblyData, ImmutableArray<PEModule> modules) { Debug.Assert(identity != null); Debug.Assert(!referencedAssemblyData.IsDefault); _assemblyIdentity = identity; _referencedAssemblyData = referencedAssemblyData; var refs = ArrayBuilder<AssemblyIdentity>.GetInstance(referencedAssemblyData.Length + modules.Length); //approximate size foreach (AssemblyData data in referencedAssemblyData) { refs.Add(data.Identity); } // add assembly names from modules: for (int i = 1; i <= modules.Length; i++) { refs.AddRange(modules[i - 1].ReferencedAssemblies); } _referencedAssemblies = refs.ToImmutableAndFree(); } public override AssemblyIdentity Identity { get { return _assemblyIdentity; } } public override ImmutableArray<AssemblyIdentity> AssemblyReferences { get { return _referencedAssemblies; } } public override IEnumerable<TAssemblySymbol> AvailableSymbols { get { throw ExceptionUtilities.Unreachable; } } public override AssemblyReferenceBinding[] BindAssemblyReferences( ImmutableArray<AssemblyData> assemblies, AssemblyIdentityComparer assemblyIdentityComparer) { var boundReferences = new AssemblyReferenceBinding[_referencedAssemblies.Length]; for (int i = 0; i < _referencedAssemblyData.Length; i++) { Debug.Assert(ReferenceEquals(_referencedAssemblyData[i], assemblies[i + 1])); boundReferences[i] = new AssemblyReferenceBinding(assemblies[i + 1].Identity, i + 1); } // references from added modules shouldn't resolve against the assembly being built (definition #0) const int definitionStartIndex = 1; // resolve references coming from linked modules: for (int i = _referencedAssemblyData.Length; i < _referencedAssemblies.Length; i++) { boundReferences[i] = ResolveReferencedAssembly( _referencedAssemblies[i], assemblies, definitionStartIndex, assemblyIdentityComparer); } return boundReferences; } public override bool IsMatchingAssembly(TAssemblySymbol? assembly) { throw ExceptionUtilities.Unreachable; } public override bool ContainsNoPiaLocalTypes { get { throw ExceptionUtilities.Unreachable; } } public override bool IsLinked { get { return false; } } public override bool DeclaresTheObjectClass { get { return false; } } public override Compilation? SourceCompilation => 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.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class CommonReferenceManager<TCompilation, TAssemblySymbol> { protected sealed class AssemblyDataForAssemblyBeingBuilt : AssemblyData { private readonly AssemblyIdentity _assemblyIdentity; // assemblies referenced directly by the assembly: private readonly ImmutableArray<AssemblyData> _referencedAssemblyData; // all referenced assembly names including assemblies referenced by modules: private readonly ImmutableArray<AssemblyIdentity> _referencedAssemblies; public AssemblyDataForAssemblyBeingBuilt( AssemblyIdentity identity, ImmutableArray<AssemblyData> referencedAssemblyData, ImmutableArray<PEModule> modules) { Debug.Assert(identity != null); Debug.Assert(!referencedAssemblyData.IsDefault); _assemblyIdentity = identity; _referencedAssemblyData = referencedAssemblyData; var refs = ArrayBuilder<AssemblyIdentity>.GetInstance(referencedAssemblyData.Length + modules.Length); //approximate size foreach (AssemblyData data in referencedAssemblyData) { refs.Add(data.Identity); } // add assembly names from modules: for (int i = 1; i <= modules.Length; i++) { refs.AddRange(modules[i - 1].ReferencedAssemblies); } _referencedAssemblies = refs.ToImmutableAndFree(); } public override AssemblyIdentity Identity { get { return _assemblyIdentity; } } public override ImmutableArray<AssemblyIdentity> AssemblyReferences { get { return _referencedAssemblies; } } public override IEnumerable<TAssemblySymbol> AvailableSymbols { get { throw ExceptionUtilities.Unreachable; } } public override AssemblyReferenceBinding[] BindAssemblyReferences( ImmutableArray<AssemblyData> assemblies, AssemblyIdentityComparer assemblyIdentityComparer) { var boundReferences = new AssemblyReferenceBinding[_referencedAssemblies.Length]; for (int i = 0; i < _referencedAssemblyData.Length; i++) { Debug.Assert(ReferenceEquals(_referencedAssemblyData[i], assemblies[i + 1])); boundReferences[i] = new AssemblyReferenceBinding(assemblies[i + 1].Identity, i + 1); } // references from added modules shouldn't resolve against the assembly being built (definition #0) const int definitionStartIndex = 1; // resolve references coming from linked modules: for (int i = _referencedAssemblyData.Length; i < _referencedAssemblies.Length; i++) { boundReferences[i] = ResolveReferencedAssembly( _referencedAssemblies[i], assemblies, definitionStartIndex, assemblyIdentityComparer); } return boundReferences; } public override bool IsMatchingAssembly(TAssemblySymbol? assembly) { throw ExceptionUtilities.Unreachable; } public override bool ContainsNoPiaLocalTypes { get { throw ExceptionUtilities.Unreachable; } } public override bool IsLinked { get { return false; } } public override bool DeclaresTheObjectClass { get { return false; } } public override Compilation? SourceCompilation => null; } } }
-1